# 🚀 Next.js Migration Roadmap - PLAGIS Frontend

## 📋 Executive Summary

**Goal:** Migrate PLAGIS frontend from plain HTML/JavaScript to Next.js framework

**Current State:**
- `login.html` - Authentication page
- `index_v3.html` - Main application (2,300+ lines of code)
- Backend API: FastAPI at `http://localhost:8001`
- Static file server on port `7000`

**Target State:**
- Modern Next.js application
- Component-based architecture
- Better state management
- Type safety with TypeScript
- Improved developer experience
- Production-ready deployment

---

## 🎯 Why Next.js?

### Current Pain Points
1. **Code Complexity** - Single 2,300+ line HTML file
2. **No Component Reusability** - Duplicate code across pages
3. **State Management** - Manual localStorage handling, no reactive state
4. **No Type Safety** - Vanilla JavaScript prone to runtime errors
5. **Hard to Test** - No testing framework or structure
6. **Poor Developer Experience** - No hot reload, manual debugging
7. **Scalability Issues** - Adding features becomes increasingly difficult

### Next.js Benefits
1. ✅ **Component Architecture** - Reusable UI components
2. ✅ **React Hooks** - Clean state management
3. ✅ **TypeScript** - Type safety and better IDE support
4. ✅ **File-based Routing** - Automatic routing system
5. ✅ **API Routes** - Optional backend proxy layer
6. ✅ **Built-in Optimization** - Code splitting, lazy loading, image optimization
7. ✅ **Hot Module Replacement** - Instant feedback during development
8. ✅ **Production Ready** - Built-in production optimizations
9. ✅ **SEO Friendly** - Server-side rendering capabilities
10. ✅ **Testing Support** - Jest, React Testing Library integration

---

## 🗺️ Migration Strategy

### Phase 1: Project Setup & Infrastructure (Week 1)
**Goal:** Get Next.js project running alongside existing HTML

#### Tasks:
1. **Create Next.js Project**
   ```bash
   npx create-next-app@latest plagis-nextjs --typescript --tailwind --app
   ```

2. **Project Structure Setup**
   ```
   plagis-nextjs/
   ├── src/
   │   ├── app/                    # Next.js 13+ App Router
   │   │   ├── layout.tsx          # Root layout
   │   │   ├── page.tsx            # Home/redirect page
   │   │   ├── login/
   │   │   │   └── page.tsx        # Login page
   │   │   └── dashboard/
   │   │       └── page.tsx        # Main app (index_v3)
   │   ├── components/             # Reusable components
   │   │   ├── auth/
   │   │   │   ├── LoginForm.tsx
   │   │   │   └── AuthGuard.tsx
   │   │   ├── search/
   │   │   │   ├── TransactionSearch.tsx
   │   │   │   ├── DocumentSearch.tsx
   │   │   │   └── PropertySearch.tsx
   │   │   ├── results/
   │   │   │   ├── TransactionResults.tsx
   │   │   │   └── DocumentList.tsx
   │   │   ├── details/
   │   │   │   ├── TransactionDetails.tsx
   │   │   │   ├── PartyDetails.tsx
   │   │   │   └── PropertyDetails.tsx
   │   │   ├── ui/
   │   │   │   ├── Button.tsx
   │   │   │   ├── Input.tsx
   │   │   │   ├── Modal.tsx
   │   │   │   └── Card.tsx
   │   │   └── layout/
   │   │       ├── Sidebar.tsx
   │   │       ├── Header.tsx
   │   │       └── Footer.tsx
   │   ├── lib/                    # Utilities & helpers
   │   │   ├── api.ts              # API client
   │   │   ├── auth.ts             # Auth utilities
   │   │   └── types.ts            # TypeScript types
   │   ├── hooks/                  # Custom React hooks
   │   │   ├── useAuth.ts
   │   │   ├── useTransaction.ts
   │   │   └── useDocuments.ts
   │   └── context/                # React Context
   │       └── AuthContext.tsx
   └── public/                     # Static assets
   ```

3. **Dependencies to Install**
   ```json
   {
     "dependencies": {
       "next": "^14.0.0",
       "react": "^18.2.0",
       "react-dom": "^18.2.0",
       "axios": "^1.6.0",
       "zustand": "^4.4.0",
       "react-query": "^3.39.0",
       "date-fns": "^2.30.0",
       "lucide-react": "^0.292.0"
     },
     "devDependencies": {
       "@types/node": "^20.0.0",
       "@types/react": "^18.2.0",
       "typescript": "^5.3.0",
       "tailwindcss": "^3.3.0",
       "eslint": "^8.54.0",
       "prettier": "^3.1.0"
     }
   }
   ```

4. **Configuration Files**
   - `next.config.js` - Configure API proxy
   - `tsconfig.json` - TypeScript configuration
   - `tailwind.config.js` - Tailwind CSS setup
   - `.env.local` - Environment variables

#### Deliverables:
- ✅ Working Next.js project
- ✅ Basic routing structure
- ✅ Development server running
- ✅ Can coexist with existing HTML (different ports)

---

### Phase 2: Authentication Migration (Week 2)
**Goal:** Migrate login.html to Next.js

#### Tasks:
1. **Create Auth Components**
   - `LoginForm.tsx` - Login form component
   - `AuthGuard.tsx` - Protected route wrapper
   - `AuthContext.tsx` - Global auth state

2. **Implement Auth Logic**
   ```typescript
   // lib/api.ts
   export const loginUser = async (username: string, password: string) => {
     const formData = new URLSearchParams();
     formData.append('username', username);
     formData.append('password', password);
     
     const response = await fetch(`${API_BASE_URL}/auth/login`, {
       method: 'POST',
       headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
       body: formData
     });
     
     return response.json();
   };
   ```

3. **Auth State Management**
   - Use React Context or Zustand
   - Token storage (localStorage)
   - Auto token refresh
   - Auth status tracking

4. **Styling Migration**
   - Convert CSS to Tailwind classes
   - Maintain glassmorphism design
   - Responsive design improvements

#### Deliverables:
- ✅ Working login page in Next.js
- ✅ Authentication flow functional
- ✅ Token management working
- ✅ Visual parity with current design

---

### Phase 3: Main Dashboard Structure (Week 3)
**Goal:** Create skeleton of main application

#### Tasks:
1. **Layout Components**
   - `Sidebar.tsx` - Navigation sidebar
   - `Header.tsx` - Top header with user info
   - `DashboardLayout.tsx` - Main layout wrapper

2. **Routing Setup**
   ```
   /dashboard
   /dashboard/transactions
   /dashboard/documents
   /dashboard/properties
   /dashboard/parties
   /dashboard/transaction/[id]
   ```

3. **State Management Setup**
   - React Query for API calls
   - Zustand for global state
   - Context for auth

4. **API Client Setup**
   ```typescript
   // lib/api.ts
   class ApiClient {
     private baseUrl = process.env.NEXT_PUBLIC_API_URL;
     
     async get(endpoint: string) { }
     async post(endpoint: string, data: any) { }
     async put(endpoint: string, data: any) { }
     async delete(endpoint: string) { }
   }
   ```

#### Deliverables:
- ✅ Dashboard layout functional
- ✅ Navigation working
- ✅ Protected routes setup
- ✅ API client ready

---

### Phase 4: Search Components Migration (Week 4)
**Goal:** Migrate search functionality

#### Tasks:
1. **Transaction Search Component**
   ```tsx
   // components/search/TransactionSearch.tsx
   export function TransactionSearch() {
     const [formData, setFormData] = useState({
       transactionNumber: '',
       documentNumber: '',
       transactionType: '',
       // ... more fields
     });
     
     const { data, isLoading, error } = useTransactionSearch(formData);
     
     return (
       <form onSubmit={handleSearch}>
         {/* Search fields */}
       </form>
     );
   }
   ```

2. **Document Search Component**
3. **Property Search Component**
4. **Party Search Component**

5. **Custom Hooks**
   ```typescript
   // hooks/useTransactionSearch.ts
   export function useTransactionSearch(params: SearchParams) {
     return useQuery(['transactions', params], () => 
       apiClient.searchTransactions(params)
     );
   }
   ```

#### Deliverables:
- ✅ All search forms functional
- ✅ API integration complete
- ✅ Loading states handled
- ✅ Error handling implemented

---

### Phase 5: Results & Details Migration (Week 5)
**Goal:** Migrate results display and detail views

#### Tasks:
1. **Results Components**
   - `TransactionResults.tsx` - Transaction results table
   - `DocumentList.tsx` - Document list
   - `ResultsPagination.tsx` - Pagination controls

2. **Details Components**
   - `TransactionDetails.tsx` - Full transaction view
   - `PartyDetails.tsx` - Party information
   - `PropertyDetails.tsx` - Property information
   - `DocumentViewer.tsx` - PDF viewer modal

3. **Data Management**
   - React Query caching
   - Optimistic updates
   - Background refetching

#### Deliverables:
- ✅ Results display working
- ✅ Detail views functional
- ✅ Document viewing working
- ✅ Data caching optimized

---

### Phase 6: Testing & Quality Assurance (Week 6)
**Goal:** Ensure quality and reliability

#### Tasks:
1. **Unit Tests**
   ```typescript
   // __tests__/components/LoginForm.test.tsx
   describe('LoginForm', () => {
     it('should submit valid credentials', () => {
       // test implementation
     });
   });
   ```

2. **Integration Tests**
   - API integration tests
   - Auth flow tests
   - Search functionality tests

3. **E2E Tests**
   - User journey tests with Playwright
   - Critical path testing

4. **Performance Testing**
   - Lighthouse audits
   - Load time optimization
   - Bundle size analysis

#### Deliverables:
- ✅ 80%+ test coverage
- ✅ All critical paths tested
- ✅ Performance benchmarks met
- ✅ Accessibility compliance

---

### Phase 7: Deployment & Rollout (Week 7)
**Goal:** Deploy to production

#### Tasks:
1. **Production Build**
   ```bash
   npm run build
   npm run start
   ```

2. **Environment Setup**
   - Production environment variables
   - API endpoint configuration
   - Error logging (Sentry)

3. **Deployment Strategy**
   - **Option A:** Static export (if no SSR needed)
   - **Option B:** Node.js server
   - **Option C:** Docker container

4. **Rollout Plan**
   - Beta testing with select users
   - Gradual rollout
   - Monitor for issues
   - Keep HTML version as fallback

#### Deliverables:
- ✅ Production deployment
- ✅ Monitoring setup
- ✅ Rollback plan ready
- ✅ Documentation complete

---

## 🔧 Technical Decisions

### TypeScript Types

```typescript
// lib/types.ts

export interface User {
  id: number;
  username: string;
  full_name: string;
  role: string;
}

export interface Transaction {
  id: number;
  transaction_number: string;
  transaction_type: string;
  transaction_type_label: string;
  transaction_status: string;
  transaction_status_label: string;
  application_date: string;
  complete_date: string;
  instrument_number?: string;
  page_number?: string;
  volume?: string;
  region?: string;
}

export interface Document {
  id: number;
  document_number: string;
  document_type: number;
  document_type_label: string;
  page_count: number;
  date_issued?: string;
  registration_number?: string;
}

export interface Party {
  id: number;
  full_name: string;
  person_type_label: string;
  legal_role_label: string;
  state_label?: string;
  lga?: string;
}

export interface Property {
  id: number;
  property_no: string;
  upin: string;
  area_size?: number;
  property_type_label: string;
  block_no?: string;
  plot_no?: string;
  role: 'Source' | 'Target' | 'Related';
}

export interface SearchParams {
  transaction_number?: string;
  document_number?: string;
  transaction_type?: string;
  transaction_status?: string;
  application_date_from?: string;
  application_date_to?: string;
  instrument_number?: string;
  page_number?: string;
}
```

### API Client

```typescript
// lib/api.ts
import axios, { AxiosInstance } from 'axios';

class ApiClient {
  private client: AxiosInstance;
  
  constructor() {
    this.client = axios.create({
      baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8001',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
    // Request interceptor - add auth token
    this.client.interceptors.request.use((config) => {
      const token = localStorage.getItem('access_token');
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    });
    
    // Response interceptor - handle 401
    this.client.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response?.status === 401) {
          localStorage.clear();
          window.location.href = '/login';
        }
        return Promise.reject(error);
      }
    );
  }
  
  // Auth
  async login(username: string, password: string) { }
  async logout() { }
  async getCurrentUser() { }
  
  // Transactions
  async searchTransactions(params: SearchParams) { }
  async getTransaction(id: number) { }
  
  // Documents
  async getDocumentsByNumber(documentNumber: string) { }
  async getDocumentPdf(id: number) { }
  
  // Dictionaries
  async getDocumentTypes() { }
  async getTransactionTypes() { }
  async getTransactionStatuses() { }
}

export const apiClient = new ApiClient();
```

### State Management with Zustand

```typescript
// store/authStore.ts
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  login: (token: string, user: User) => void;
  logout: () => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      user: null,
      token: null,
      isAuthenticated: false,
      login: (token, user) => set({ token, user, isAuthenticated: true }),
      logout: () => set({ token: null, user: null, isAuthenticated: false }),
    }),
    {
      name: 'auth-storage',
    }
  )
);
```

---

## 🎨 UI Component Library Decision

### Option 1: Tailwind CSS + shadcn/ui (Recommended)
**Pros:**
- Highly customizable
- Great TypeScript support
- Copy-paste components
- No dependencies bloat
- Accessible by default

**Cons:**
- Need to setup initially
- More manual work

### Option 2: Material-UI
**Pros:**
- Complete component library
- Mature and stable
- Good documentation

**Cons:**
- Heavier bundle size
- Less customizable

**Recommendation:** Go with Tailwind + shadcn/ui for flexibility

---

## 📊 Comparison: Before vs After

| Feature | Current (HTML) | Next.js |
|---------|---------------|---------|
| **File Structure** | 2 HTML files (2,300+ lines) | ~50 organized files |
| **Code Reusability** | Copy-paste | Components |
| **State Management** | Manual localStorage | React hooks + Zustand |
| **Type Safety** | None | Full TypeScript |
| **Testing** | Manual | Automated tests |
| **Development Speed** | Slow (refresh required) | Fast (HMR) |
| **Build Time** | None | ~30 seconds |
| **Bundle Size** | ~100KB | ~200KB (optimized) |
| **Performance** | Good | Better (code splitting) |
| **Maintainability** | Difficult | Easy |
| **Scalability** | Limited | Excellent |

---

## 🚨 Risk Mitigation

### Risk 1: Learning Curve
**Impact:** Medium  
**Mitigation:**
- Start with simple components
- Use TypeScript from day 1
- Follow Next.js documentation closely
- Pair programming sessions

### Risk 2: Timeline Overrun
**Impact:** High  
**Mitigation:**
- Keep HTML version running
- Phased rollout
- Weekly check-ins
- Buffer time in schedule

### Risk 3: API Compatibility Issues
**Impact:** Low  
**Mitigation:**
- API remains unchanged
- Extensive testing
- Use same API client pattern

### Risk 4: Performance Regression
**Impact:** Medium  
**Mitigation:**
- Performance benchmarks
- Lighthouse CI
- Load testing
- Code splitting

---

## 💰 Estimated Effort

### Time Breakdown
- **Setup & Infrastructure:** 5 days
- **Authentication:** 5 days
- **Dashboard Structure:** 5 days
- **Search Components:** 7 days
- **Results & Details:** 7 days
- **Testing & QA:** 7 days
- **Deployment:** 3 days
- **Buffer:** 5 days

**Total:** ~7 weeks (1 developer)  
**Total:** ~4 weeks (2 developers)

### Development Team Recommendation
- 1x Senior React/Next.js Developer
- 1x UI/UX Developer (part-time for design consistency)
- 1x QA Engineer (for testing phase)

---

## 📝 Success Criteria

1. ✅ All features from HTML version working
2. ✅ Performance equal or better than current
3. ✅ 80%+ test coverage
4. ✅ Zero breaking bugs in production
5. ✅ Positive user feedback
6. ✅ Developer satisfaction improved
7. ✅ Easier to add new features
8. ✅ Better error handling
9. ✅ Improved accessibility
10. ✅ Mobile responsive

---

## 🎯 Quick Start Checklist

To start immediately:

### Week 1 - Day 1 Tasks
- [ ] Install Node.js (v18+ recommended)
- [ ] Create Next.js project
- [ ] Setup Git repository
- [ ] Install core dependencies
- [ ] Configure TypeScript
- [ ] Setup Tailwind CSS
- [ ] Create basic folder structure
- [ ] Setup environment variables
- [ ] Run dev server
- [ ] Create first page (login)

### Commands to Run
```bash
# Create project
npx create-next-app@latest plagis-nextjs --typescript --tailwind --app --src-dir

# Navigate to project
cd plagis-nextjs

# Install additional dependencies
npm install axios zustand @tanstack/react-query date-fns lucide-react

# Run development server
npm run dev

# Open browser
# http://localhost:3000
```

---

## 📚 Resources

### Documentation
- [Next.js Documentation](https://nextjs.org/docs)
- [React Documentation](https://react.dev)
- [TypeScript Handbook](https://www.typescriptlang.org/docs/)
- [Tailwind CSS](https://tailwindcss.com/docs)

### Learning Resources
- [Next.js Tutorial](https://nextjs.org/learn)
- [React Query Guide](https://tanstack.com/query/latest/docs/react/overview)
- [Zustand Guide](https://docs.pmnd.rs/zustand/getting-started/introduction)

---

## 🤔 Decision Time

### Should we proceed?

**Arguments FOR:**
- ✅ Better long-term maintainability
- ✅ Easier to add features
- ✅ Modern development experience
- ✅ Better performance potential
- ✅ Easier testing
- ✅ Industry standard approach

**Arguments AGAINST:**
- ❌ Learning curve
- ❌ Initial time investment
- ❌ More complex deployment
- ❌ Larger bundle size

### Recommendation: **YES, PROCEED**

The benefits far outweigh the costs. The current HTML approach is reaching its complexity limits and will only get harder to maintain.

---

## 📞 Next Steps

1. **Review this roadmap** - Discuss and adjust timeline
2. **Get team buy-in** - Ensure everyone understands the change
3. **Setup development environment** - Install required tools
4. **Start Phase 1** - Create Next.js project
5. **Weekly check-ins** - Track progress and adjust

---

**Created:** November 11, 2025  
**Status:** Proposal - Awaiting Approval  
**Estimated Completion:** 7 weeks from approval

