import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { mockApplications, mockAuditLogs, mockDocuments, mockWorkNotes, mockLevel1Scores, mockQuestionnaireResponses, Application, ApplicationStatus } from '../../lib/mock-data';
import { onboardingService } from '../../services/onboarding.service';
import { WorkNotesPage } from './WorkNotesPage';
import QuestionnaireForm from '../dealer/QuestionnaireForm';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/card';
import {
  ArrowLeft,
  CheckCircle,
  XCircle,
  MessageSquare,
  Calendar,
  Clock,
  Upload,
  Download,
  FileText,
  User,
  MapPin,
  Mail,
  Phone,
  GraduationCap,
  Bike,
  Award,
  AlertCircle,
  ClipboardList,
  ChevronDown,
  ChevronRight,
  GitBranch,
  Star
} from 'lucide-react';
import { Progress } from '../ui/progress';
import { Textarea } from '../ui/textarea';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
import { ScrollArea } from '../ui/scroll-area';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '../ui/table';
import { Checkbox } from '../ui/checkbox';
import { Separator } from '../ui/separator';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '../ui/select';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '../ui/dropdown-menu';



interface ProcessStage {
  id: number | string;
  name: string;
  status: 'completed' | 'active' | 'pending';
  date?: string;
  description?: string;
  evaluators?: string[];
  documentsUploaded?: number;
  isParallel?: boolean;
  branches?: {
    name: string;
    color: string;
    stages: ProcessStage[];
  }[];
}

export function ApplicationDetails() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const applicationId = id || '';
  const onBack = () => navigate(-1);
  // const application = mockApplications.find(app => app.id === applicationId);
  const [application, setApplication] = useState<Application | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchApplication = async () => {
      try {
        setLoading(true);
        const data = await onboardingService.getApplicationById(applicationId);

        // Helper to find stage date
        const getStageDate = (stageName: string) => {
          const stage = data.progressTracking?.find((p: any) => p.stageName === stageName);
          return stage?.stageCompletedAt ? new Date(stage.stageCompletedAt).toISOString().split('T')[0] :
            stage?.stageStartedAt ? new Date(stage.stageStartedAt).toISOString().split('T')[0] : undefined;
        };

        // Map backend data to frontend Application interface
        const mappedApp: Application = {
          id: data.id,
          registrationNumber: data.applicationId || 'N/A',
          name: data.applicantName,
          email: data.email,
          phone: data.phone,
          age: data.age,
          education: data.education,
          residentialAddress: data.address || data.city || '',
          businessAddress: data.address || '',
          preferredLocation: data.preferredLocation,
          state: data.state,
          ownsBike: data.ownRoyalEnfield === 'yes',
          pastExperience: data.experienceYears ? `${data.experienceYears} years` : (data.description || ''),
          status: data.overallStatus as ApplicationStatus,
          questionnaireMarks: 0,
          rank: 0,
          totalApplicantsAtLocation: 0,
          submissionDate: data.createdAt,
          assignedUsers: [],
          progress: data.progressPercentage || 0,
          isShortlisted: data.isShortlisted || true, // Default to true for now
          // Add other fields to match interface
          companyName: data.companyName,
          source: data.source,
          existingDealer: data.existingDealer,
          royalEnfieldModel: data.royalEnfieldModel,
          description: data.description,
          pincode: data.pincode,
          locationType: data.locationType,
          ownRoyalEnfield: data.ownRoyalEnfield,
          address: data.address,
          // Map timeline dates from progressTracking
          level1InterviewDate: getStageDate('1st Level Interview'),
          level2InterviewDate: getStageDate('2nd Level Interview'),
          level3InterviewDate: getStageDate('3rd Level Interview'),
          fddDate: getStageDate('FDD'),
          loiApprovalDate: getStageDate('LOI Approval'),
          securityDetailsDate: getStageDate('Security Details'),
          loiIssueDate: getStageDate('LOI Issue'),
          dealerCodeDate: getStageDate('Dealer Code Generation'),
          architectureAssignedDate: getStageDate('Architecture Team Assigned'),
          architectureDocumentDate: getStageDate('Architecture Document Upload'),
          architectureCompletionDate: getStageDate('Architecture Team Completion'),
          loaDate: getStageDate('LOA'),
          eorCompleteDate: getStageDate('EOR Complete'),
          inaugurationDate: getStageDate('Inauguration'),
        };
        setApplication(mappedApp);
      } catch (error) {
        console.error('Failed to fetch application details', error);
      } finally {
        setLoading(false);
      }
    };

    if (applicationId) {
      fetchApplication();
    }
  }, [applicationId]);
  const [activeTab, setActiveTab] = useState('questionnaire');
  const [showApproveModal, setShowApproveModal] = useState(false);
  const [showRejectModal, setShowRejectModal] = useState(false);
  const [showWorkNoteModal, setShowWorkNoteModal] = useState(false);
  const [showWorkNotesPage, setShowWorkNotesPage] = useState(false);
  const [showScheduleModal, setShowScheduleModal] = useState(false);
  const [showKTMatrixModal, setShowKTMatrixModal] = useState(false);
  const [showLevel2FeedbackModal, setShowLevel2FeedbackModal] = useState(false);
  const [showLevel3FeedbackModal, setShowLevel3FeedbackModal] = useState(false);
  const [showDocumentsModal, setShowDocumentsModal] = useState(false);
  const [selectedStage, setSelectedStage] = useState<string | null>(null);
  const [interviewMode, setInterviewMode] = useState('virtual');
  const [approvalRemark, setApprovalRemark] = useState('');
  const [rejectionReason, setRejectionReason] = useState('');
  const [workNote, setWorkNote] = useState('');
  const [expandedBranches, setExpandedBranches] = useState<{ [key: string]: boolean }>({
    'architectural-work': true,
    'statutory-documents': true
  });

  if (loading) {
    return <div>Loading application details...</div>;
  }

  if (!application) {
    return <div>Application not found</div>;
  }

  const processStages: ProcessStage[] = [
    {
      id: 1,
      name: 'Submitted',
      status: 'completed',
      date: application.submissionDate,
      description: 'Application submitted',
      documentsUploaded: 3
    },
    {
      id: 2,
      name: 'Questionnaire',
      status: application.questionnaireMarks ? 'completed' : 'pending',
      date: '2025-10-03',
      description: 'Questionnaire completed',
      documentsUploaded: 0
    },
    {
      id: 3,
      name: 'Shortlist',
      status: ['Shortlisted', 'Level 1 Pending', 'Level 1 Approved', 'Level 2 Pending', 'Level 2 Approved', 'Level 3 Pending', 'FDD Verification', 'Payment Pending', 'Dealer Code Generation', 'Architecture Team Assigned', 'Architecture Document Upload', 'Architecture Team Completion', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : 'pending',
      date: '2025-10-04',
      description: 'Application shortlisted by DD',
      documentsUploaded: 2
    },
    {
      id: 4,
      name: '1st Level Interview',
      status: ['Level 1 Approved', 'Level 2 Pending', 'Level 2 Approved', 'Level 3 Pending', 'FDD Verification', 'Payment Pending', 'Dealer Code Generation', 'Architecture Team Assigned', 'Architecture Document Upload', 'Architecture Team Completion', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Level 1 Pending' ? 'active' : 'pending',
      date: application.level1InterviewDate,
      description: 'DD-ZM + RBM evaluation',
      evaluators: ['DD-ZM', 'RBM'],
      documentsUploaded: 1
    },
    {
      id: 5,
      name: '2nd Level Interview',
      status: ['Level 2 Approved', 'Level 2 Recommended', 'Level 3 Pending', 'FDD Verification', 'Payment Pending', 'Dealer Code Generation', 'Architecture Team Assigned', 'Architecture Document Upload', 'Architecture Team Completion', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Level 2 Pending' ? 'active' : 'pending',
      date: application.level2InterviewDate,
      description: 'DD Lead + ZBH evaluation',
      evaluators: ['DD Lead', 'ZBH'],
      documentsUploaded: 1
    },
    {
      id: 6,
      name: '3rd Level Interview',
      status: ['FDD Verification', 'Payment Pending', 'Dealer Code Generation', 'Architecture Team Assigned', 'Architecture Document Upload', 'Architecture Team Completion', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Level 3 Pending' ? 'active' : 'pending',
      date: application.level3InterviewDate,
      description: 'NBH + DD-Head evaluation',
      evaluators: ['NBH', 'DD-Head'],
      documentsUploaded: 2
    },
    {
      id: 7,
      name: 'FDD',
      status: ['Payment Pending', 'Dealer Code Generation', 'Architecture Team Assigned', 'Architecture Document Upload', 'Architecture Team Completion', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'FDD Verification' ? 'active' : 'pending',
      date: application.fddDate,
      description: 'Financial Due Diligence',
      documentsUploaded: 5
    },
    {
      id: 8,
      name: 'LOI Approval',
      status: ['Payment Pending', 'Dealer Code Generation', 'Architecture Team Assigned', 'Architecture Document Upload', 'Architecture Team Completion', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : 'pending',
      date: application.loiApprovalDate,
      description: 'Letter of Intent approval',
      documentsUploaded: 1
    },
    {
      id: 9,
      name: 'Security Details',
      status: ['Payment Pending', 'Dealer Code Generation', 'Architecture Team Assigned', 'Architecture Document Upload', 'Architecture Team Completion', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : 'pending',
      date: application.securityDetailsDate,
      description: 'Security verification',
      documentsUploaded: 3
    },
    {
      id: 10,
      name: 'LOI Issue',
      status: ['Dealer Code Generation', 'Architecture Team Assigned', 'Architecture Document Upload', 'Architecture Team Completion', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Payment Pending' ? 'active' : 'pending',
      date: application.loiIssueDate,
      description: 'Letter of Intent issued',
      documentsUploaded: 1
    },
    {
      id: 11,
      name: 'Dealer Code Generation',
      status: ['Architecture Team Assigned', 'Architecture Document Upload', 'Architecture Team Completion', 'Statutory GST', 'Statutory PAN', 'Statutory Nodal', 'Statutory Check', 'Statutory Partnership', 'Statutory Firm Reg', 'Statutory Rental', 'Statutory Virtual Code', 'Statutory Domain', 'Statutory MSD', 'Statutory LOI Ack', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Dealer Code Generation' ? 'active' : 'pending',
      date: application.dealerCodeDate,
      description: 'Dealer code generated and assigned',
      documentsUploaded: 0,
      isParallel: true,
      branches: [
        {
          name: 'Architectural Work',
          color: 'blue',
          stages: [
            {
              id: '11a-1',
              name: 'Assigned to Architecture Team',
              status: ['Architecture Document Upload', 'Architecture Team Completion', 'Statutory GST', 'Statutory PAN', 'Statutory Nodal', 'Statutory Check', 'Statutory Partnership', 'Statutory Firm Reg', 'Statutory Rental', 'Statutory Virtual Code', 'Statutory Domain', 'Statutory MSD', 'Statutory LOI Ack', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Architecture Team Assigned' ? 'active' : 'pending',
              date: application.architectureAssignedDate,
              description: 'Assigned to architecture team for site planning',
              documentsUploaded: 0
            },
            {
              id: '11a-2',
              name: 'Architectural Document Upload',
              status: ['Architecture Team Completion', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Architecture Document Upload' ? 'active' : 'pending',
              date: application.architectureDocumentDate,
              description: 'Architectural documents and blueprints uploaded',
              documentsUploaded: 8
            },
            {
              id: '11a-3',
              name: 'Architecture Team Completion',
              status: ['LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Architecture Team Completion' ? 'active' : 'pending',
              date: application.architectureCompletionDate,
              description: 'Architecture team work completed',
              documentsUploaded: 4
            }
          ]
        },
        {
          name: 'Statutory Documents',
          color: 'green',
          stages: [
            {
              id: '11b-1',
              name: 'GST',
              status: ['Statutory PAN', 'Statutory Nodal', 'Statutory Check', 'Statutory Partnership', 'Statutory Firm Reg', 'Statutory Rental', 'Statutory Virtual Code', 'Statutory Domain', 'Statutory MSD', 'Statutory LOI Ack', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Statutory GST' ? 'active' : 'pending',
              description: 'GST certificate',
              documentsUploaded: 1
            },
            {
              id: '11b-2',
              name: 'PAN',
              status: ['Statutory Nodal', 'Statutory Check', 'Statutory Partnership', 'Statutory Firm Reg', 'Statutory Rental', 'Statutory Virtual Code', 'Statutory Domain', 'Statutory MSD', 'Statutory LOI Ack', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Statutory PAN' ? 'active' : 'pending',
              description: 'PAN card',
              documentsUploaded: 1
            },
            {
              id: '11b-3',
              name: 'Nodal Agreement',
              status: ['Statutory Check', 'Statutory Partnership', 'Statutory Firm Reg', 'Statutory Rental', 'Statutory Virtual Code', 'Statutory Domain', 'Statutory MSD', 'Statutory LOI Ack', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Statutory Nodal' ? 'active' : 'pending',
              description: 'Nodal agreement document',
              documentsUploaded: 1
            },
            {
              id: '11b-4',
              name: 'Cancelled Check',
              status: ['Statutory Partnership', 'Statutory Firm Reg', 'Statutory Rental', 'Statutory Virtual Code', 'Statutory Domain', 'Statutory MSD', 'Statutory LOI Ack', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Statutory Check' ? 'active' : 'pending',
              description: 'Cancelled check copy',
              documentsUploaded: 1
            },
            {
              id: '11b-5',
              name: 'Partnership Deed/LLP/MOA/AOA/COI',
              status: ['Statutory Firm Reg', 'Statutory Rental', 'Statutory Virtual Code', 'Statutory Domain', 'Statutory MSD', 'Statutory LOI Ack', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Statutory Partnership' ? 'active' : 'pending',
              description: 'Business entity documents',
              documentsUploaded: 2
            },
            {
              id: '11b-6',
              name: 'Firm Registration Certificate',
              status: ['Statutory Rental', 'Statutory Virtual Code', 'Statutory Domain', 'Statutory MSD', 'Statutory LOI Ack', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Statutory Firm Reg' ? 'active' : 'pending',
              description: 'Firm registration certificate',
              documentsUploaded: 1
            },
            {
              id: '11b-7',
              name: 'Rental agreement/ Lease agreement / Own/ Land agreement',
              status: ['Statutory Virtual Code', 'Statutory Domain', 'Statutory MSD', 'Statutory LOI Ack', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Statutory Rental' ? 'active' : 'pending',
              description: 'Property agreement document',
              documentsUploaded: 1
            },
            {
              id: '11b-8',
              name: 'Virtual Code',
              status: ['Statutory Domain', 'Statutory MSD', 'Statutory LOI Ack', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Statutory Virtual Code' ? 'active' : 'pending',
              description: 'Virtual code availability',
              documentsUploaded: 0
            },
            {
              id: '11b-9',
              name: 'Domain ID',
              status: ['Statutory MSD', 'Statutory LOI Ack', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Statutory Domain' ? 'active' : 'pending',
              description: 'Domain ID setup',
              documentsUploaded: 0
            },
            {
              id: '11b-10',
              name: 'MSD Configuration',
              status: ['Statutory LOI Ack', 'LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Statutory MSD' ? 'active' : 'pending',
              description: 'Microsoft Dynamics configuration',
              documentsUploaded: 0
            },
            {
              id: '11b-11',
              name: 'LOI Acknowledgement Copy',
              status: ['LOA Pending', 'EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'Statutory LOI Ack' ? 'active' : 'pending',
              description: 'LOI acknowledgement copy',
              documentsUploaded: 1
            }
          ]
        }
      ]
    },
    {
      id: 12,
      name: 'LOA',
      status: ['EOR In Progress', 'EOR Complete', 'Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'LOA Pending' ? 'active' : 'pending',
      date: application.loaDate,
      description: 'Letter of Authorization',
      documentsUploaded: 1
    },
    {
      id: 13,
      name: 'EOR Complete',
      status: ['Inauguration', 'Approved'].includes(application.status) ? 'completed' : application.status === 'EOR Complete' ? 'active' : 'pending',
      date: application.eorCompleteDate,
      description: 'Essential Operating Requirements completed',
      documentsUploaded: 6
    },
    {
      id: 14,
      name: 'Inauguration',
      status: application.status === 'Approved' ? 'completed' : application.status === 'Inauguration' ? 'active' : 'pending',
      date: application.inaugurationDate,
      description: 'Dealership inauguration ceremony',
      documentsUploaded: 2
    }
  ];

  const eorChecklist = [
    { id: 1, item: 'Sales Standards', completed: true },
    { id: 2, item: 'Service & Spares', completed: true },
    { id: 3, item: 'DMS infra', completed: application.status === 'Approved' },
    { id: 4, item: 'Manpower Training', completed: application.status === 'Approved' },
    { id: 5, item: 'Trade certificate with test ride bikes registration', completed: false },
    { id: 6, item: 'GST certificate including Accessories & Apparels billing', completed: true },
    { id: 7, item: 'Inventory Funding', completed: false },
    { id: 8, item: 'Virtual code availability', completed: true },
    { id: 9, item: 'Vendor payments', completed: false },
    { id: 10, item: 'Details for website submission', completed: true },
    { id: 11, item: 'Infra Insurance both Showroom and Service center', completed: false },
    { id: 12, item: 'Auto ordering', completed: application.status === 'Approved' }
  ];

  const eorProgress = (eorChecklist.filter(item => item.completed).length / eorChecklist.length) * 100;

  // Mock stage-specific documents
  const stageDocuments: { [key: string]: typeof mockDocuments } = {
    'Submitted': [
      { id: 'd1', name: 'Application Form.pdf', type: 'PDF', uploadDate: '2025-10-01', status: 'Verified', uploader: 'Amit Sharma' },
      { id: 'd2', name: 'Aadhaar Card.pdf', type: 'PDF', uploadDate: '2025-10-01', status: 'Verified', uploader: 'Amit Sharma' },
      { id: 'd3', name: 'PAN Card.pdf', type: 'PDF', uploadDate: '2025-10-01', status: 'Verified', uploader: 'Amit Sharma' }
    ],
    'Shortlist': [
      { id: 'd4', name: 'Business Plan.pdf', type: 'PDF', uploadDate: '2025-10-04', status: 'Verified', uploader: 'Amit Sharma' },
      { id: 'd5', name: 'Financial Projections.xlsx', type: 'Excel', uploadDate: '2025-10-04', status: 'Verified', uploader: 'Amit Sharma' }
    ],
    '1st Level Interview': [
      { id: 'd6', name: 'Level 1 Evaluation Sheet.pdf', type: 'PDF', uploadDate: '2025-10-05', status: 'Verified', uploader: 'DD-ZM' }
    ],
    '2nd Level Interview': [
      { id: 'd7', name: 'Level 2 Evaluation Sheet.pdf', type: 'PDF', uploadDate: '2025-10-07', status: 'Verified', uploader: 'DD Lead' }
    ],
    '3rd Level Interview': [
      { id: 'd8', name: 'Level 3 Evaluation Sheet.pdf', type: 'PDF', uploadDate: '2025-10-09', status: 'Verified', uploader: 'NBH' },
      { id: 'd9', name: 'Final Interview Notes.pdf', type: 'PDF', uploadDate: '2025-10-09', status: 'Verified', uploader: 'DD-Head' }
    ],
    'FDD': [
      { id: 'd10', name: 'Bank Statements.pdf', type: 'PDF', uploadDate: '2025-10-10', status: 'Verified', uploader: 'FDD Team' },
      { id: 'd11', name: 'Income Tax Returns.pdf', type: 'PDF', uploadDate: '2025-10-10', status: 'Verified', uploader: 'Amit Sharma' },
      { id: 'd12', name: 'Credit Report.pdf', type: 'PDF', uploadDate: '2025-10-10', status: 'Verified', uploader: 'FDD Team' },
      { id: 'd13', name: 'Property Documents.pdf', type: 'PDF', uploadDate: '2025-10-10', status: 'Pending', uploader: 'Amit Sharma' },
      { id: 'd14', name: 'Business Valuation.pdf', type: 'PDF', uploadDate: '2025-10-10', status: 'Verified', uploader: 'FDD Team' }
    ],
    'LOI Approval': [
      { id: 'd15', name: 'LOI Approval Document.pdf', type: 'PDF', uploadDate: '2025-10-11', status: 'Verified', uploader: 'DD Admin' }
    ],
    'Security Details': [
      { id: 'd16', name: 'Police Verification.pdf', type: 'PDF', uploadDate: '2025-10-12', status: 'Verified', uploader: 'Security Team' },
      { id: 'd17', name: 'Background Check Report.pdf', type: 'PDF', uploadDate: '2025-10-12', status: 'Verified', uploader: 'Security Team' },
      { id: 'd18', name: 'Character Certificate.pdf', type: 'PDF', uploadDate: '2025-10-12', status: 'Verified', uploader: 'Amit Sharma' }
    ],
    'LOI Issue': [
      { id: 'd19', name: 'Letter of Intent.pdf', type: 'PDF', uploadDate: '2025-10-13', status: 'Verified', uploader: 'DD Admin' }
    ],
    'Architectural Document Upload': [
      { id: 'd20', name: 'Site Plan.dwg', type: 'CAD', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Architecture Team' },
      { id: 'd21', name: 'Floor Plan.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Architecture Team' },
      { id: 'd22', name: 'Elevation Design.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Architecture Team' },
      { id: 'd23', name: '3D Renders.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Architecture Team' },
      { id: 'd24', name: 'Structural Design.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Architecture Team' },
      { id: 'd25', name: 'Electrical Layout.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Architecture Team' },
      { id: 'd26', name: 'Plumbing Layout.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Architecture Team' },
      { id: 'd27', name: 'HVAC Design.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Architecture Team' }
    ],
    'Architecture Team Completion': [
      { id: 'd28', name: 'Final Approval Certificate.pdf', type: 'PDF', uploadDate: '2025-10-15', status: 'Verified', uploader: 'Architecture Team' },
      { id: 'd29', name: 'As-Built Drawings.pdf', type: 'PDF', uploadDate: '2025-10-15', status: 'Verified', uploader: 'Architecture Team' },
      { id: 'd30', name: 'Compliance Certificate.pdf', type: 'PDF', uploadDate: '2025-10-15', status: 'Verified', uploader: 'Architecture Team' },
      { id: 'd31', name: 'Quality Assurance Report.pdf', type: 'PDF', uploadDate: '2025-10-15', status: 'Verified', uploader: 'Architecture Team' }
    ],
    'GST': [
      { id: 'd32', name: 'GST Certificate.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Amit Sharma' }
    ],
    'PAN': [
      { id: 'd33', name: 'PAN Card.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Amit Sharma' }
    ],
    'Nodal Agreement': [
      { id: 'd34', name: 'Nodal Agreement.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Amit Sharma' }
    ],
    'Cancelled Check': [
      { id: 'd35', name: 'Cancelled Cheque.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Amit Sharma' }
    ],
    'Partnership Deed/LLP/MOA/AOA/COI': [
      { id: 'd36', name: 'Partnership Deed.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Amit Sharma' },
      { id: 'd37', name: 'MOA.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Amit Sharma' }
    ],
    'Firm Registration Certificate': [
      { id: 'd38', name: 'Firm Registration.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Amit Sharma' }
    ],
    'Rental agreement/ Lease agreement / Own/ Land agreement': [
      { id: 'd39', name: 'Lease Agreement.pdf', type: 'PDF', uploadDate: '2025-10-14', status: 'Verified', uploader: 'Amit Sharma' }
    ],
    'LOI Acknowledgement Copy': [
      { id: 'd40', name: 'LOI Acknowledgement.pdf', type: 'PDF', uploadDate: '2025-10-15', status: 'Verified', uploader: 'Amit Sharma' }
    ],
    'LOA': [
      { id: 'd41', name: 'Letter of Authorization.pdf', type: 'PDF', uploadDate: '2025-10-16', status: 'Verified', uploader: 'DD Admin' }
    ],
    'EOR Complete': [
      { id: 'd42', name: 'EOR Completion Certificate.pdf', type: 'PDF', uploadDate: '2025-10-17', status: 'Verified', uploader: 'DD Admin' },
      { id: 'd43', name: 'Training Completion Certificates.pdf', type: 'PDF', uploadDate: '2025-10-17', status: 'Verified', uploader: 'Training Team' },
      { id: 'd44', name: 'Infrastructure Photos.pdf', type: 'PDF', uploadDate: '2025-10-17', status: 'Verified', uploader: 'Amit Sharma' },
      { id: 'd45', name: 'Trade License.pdf', type: 'PDF', uploadDate: '2025-10-17', status: 'Verified', uploader: 'Amit Sharma' },
      { id: 'd46', name: 'Insurance Policy.pdf', type: 'PDF', uploadDate: '2025-10-17', status: 'Verified', uploader: 'Amit Sharma' },
      { id: 'd47', name: 'Vendor Agreements.pdf', type: 'PDF', uploadDate: '2025-10-17', status: 'Verified', uploader: 'Amit Sharma' }
    ],
    'Inauguration': [
      { id: 'd48', name: 'Inauguration Invitation.pdf', type: 'PDF', uploadDate: '2025-10-18', status: 'Verified', uploader: 'DD Admin' },
      { id: 'd49', name: 'Event Photos.pdf', type: 'PDF', uploadDate: '2025-10-18', status: 'Verified', uploader: 'DD Admin' }
    ]
  };

  const getDocumentsForStage = (stageName: string) => {
    return stageDocuments[stageName] || [];
  };

  const handleApprove = () => {
    if (!approvalRemark.trim()) {
      alert('Please enter a remark');
      return;
    }
    alert(`Application ${application.registrationNumber} approved!\nRemark: ${approvalRemark}`);
    setShowApproveModal(false);
    setApprovalRemark('');
  };

  const handleReject = () => {
    if (!rejectionReason.trim()) {
      alert('Please enter a reason for rejection');
      return;
    }
    alert(`Application ${application.registrationNumber} rejected!\nReason: ${rejectionReason}`);
    setShowRejectModal(false);
    setRejectionReason('');
  };

  const handleWorkNote = () => {
    if (!workNote.trim()) {
      alert('Please enter a note');
      return;
    }
    alert(`Work note added: ${workNote}`);
    setShowWorkNoteModal(false);
    setWorkNote('');
  };

  // If Work Notes page is open, show that instead
  if (showWorkNotesPage) {
    return (
      <WorkNotesPage
        applicationId={applicationId}
        applicationName={application.name}
        registrationNumber={application.registrationNumber}
        onBack={() => setShowWorkNotesPage(false)}
        initialNotes={mockWorkNotes}
      />
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="outline" size="icon" onClick={onBack}>
            <ArrowLeft className="w-4 h-4" />
          </Button>
          <div>
            <h1 className="text-slate-900">{application.name}</h1>
            <p className="text-slate-600">{application.registrationNumber}</p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Core Details Card */}
          <Card>
            <CardHeader>
              <CardTitle>Applicant Information</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="flex items-start gap-3">
                  <User className="w-5 h-5 text-slate-400 mt-1" />
                  <div>
                    <p className="text-slate-600">Full Name</p>
                    <p className="text-slate-900">{application.name}</p>
                  </div>
                </div>

                <div className="flex items-start gap-3">
                  <Mail className="w-5 h-5 text-slate-400 mt-1" />
                  <div>
                    <p className="text-slate-600">Email</p>
                    <p className="text-slate-900">{application.email}</p>
                  </div>
                </div>

                <div className="flex items-start gap-3">
                  <Phone className="w-5 h-5 text-slate-400 mt-1" />
                  <div>
                    <p className="text-slate-600">Phone</p>
                    <p className="text-slate-900">{application.phone}</p>
                  </div>
                </div>

                <div className="flex items-start gap-3">
                  <User className="w-5 h-5 text-slate-400 mt-1" />
                  <div>
                    <p className="text-slate-600">Age</p>
                    <p className="text-slate-900">{application.age ? `${application.age} years` : 'N/A'}</p>
                  </div>
                </div>

                <div className="flex items-start gap-3">
                  <GraduationCap className="w-5 h-5 text-slate-400 mt-1" />
                  <div>
                    <p className="text-slate-600">Education</p>
                    <p className="text-slate-900">{application.education || 'N/A'}</p>
                  </div>
                </div>

                <div className="flex items-start gap-3">
                  <MapPin className="w-5 h-5 text-slate-400 mt-1" />
                  <div>
                    <p className="text-slate-600">Preferred Location</p>
                    <p className="text-slate-900">{application.preferredLocation || 'N/A'}</p>
                  </div>
                </div>

                <div className="flex items-start gap-3">
                  <MapPin className="w-5 h-5 text-slate-400 mt-1" />
                  <div>
                    <p className="text-slate-600">Location Type</p>
                    <p className="text-slate-900">{application.locationType || 'N/A'}</p>
                  </div>
                </div>

                <div className="flex items-start gap-3">
                  <Bike className="w-5 h-5 text-slate-400 mt-1" />
                  <div>
                    <p className="text-slate-600">Owns Bike</p>
                    <p className="text-slate-900">{application.ownRoyalEnfield === 'yes' ? 'Yes' : 'No'}</p>
                  </div>
                </div>

                {application.ownRoyalEnfield === 'yes' && (
                  <div className="flex items-start gap-3">
                    <Bike className="w-5 h-5 text-slate-400 mt-1" />
                    <div>
                      <p className="text-slate-600">Bike Model</p>
                      <p className="text-slate-900">{application.royalEnfieldModel || 'N/A'}</p>
                    </div>
                  </div>
                )}

                <div className="flex items-start gap-3">
                  <User className="w-5 h-5 text-slate-400 mt-1" />
                  <div>
                    <p className="text-slate-600">Existing Dealer</p>
                    <p className="text-slate-900">{application.existingDealer === 'yes' ? 'Yes' : 'No'}</p>
                  </div>
                </div>

                {application.existingDealer === 'yes' && (
                  <div className="flex items-start gap-3">
                    <User className="w-5 h-5 text-slate-400 mt-1" />
                    <div>
                      <p className="text-slate-600">Company Name</p>
                      <p className="text-slate-900">{application.companyName || 'N/A'}</p>
                    </div>
                  </div>
                )}

                <div className="flex items-start gap-3">
                  <ClipboardList className="w-5 h-5 text-slate-400 mt-1" />
                  <div>
                    <p className="text-slate-600">Source</p>
                    <p className="text-slate-900">{application.source || 'N/A'}</p>
                  </div>
                </div>

                {application.questionnaireMarks !== undefined && (
                  <div className="flex items-start gap-3">
                    <Award className="w-5 h-5 text-slate-400 mt-1" />
                    <div>
                      <p className="text-slate-600">Questionnaire Score</p>
                      <p className="text-slate-900">{application.questionnaireMarks}/100</p>
                    </div>
                  </div>
                )}
              </div>

              <Separator />

              <div>
                <p className="text-slate-600 mb-2">Address</p>
                <p className="text-slate-900">{application.address || 'N/A'}</p>
              </div>

              <div>
                <p className="text-slate-600 mb-2">Pincode</p>
                <p className="text-slate-900">{application.pincode || 'N/A'}</p>
              </div>

              <div>
                <p className="text-slate-600 mb-2">Description</p>
                <p className="text-slate-900">{application.description || 'N/A'}</p>
              </div>

              <div>
                <p className="text-slate-600 mb-2">Past Experience</p>
                <p className="text-slate-900">{application.pastExperience || 'N/A'}</p>
              </div>
            </CardContent>
          </Card>

          {/* Tabs Section */}
          {/* Only show tabs for shortlisted applications (opportunity requests and regular dealership requests) */}
          {/* Hide tabs for unopportunity requests (lead generation) */}
          {application.isShortlisted !== false && (
            <Card>
              <Tabs value={activeTab} onValueChange={setActiveTab}>
                <CardHeader className="pb-4">
                  <div className="overflow-x-auto -mx-6 px-6">
                    <TabsList className="w-max min-w-full justify-start">
                      <TabsTrigger value="questionnaire">Questionnaire Response</TabsTrigger>
                      <TabsTrigger value="progress">Progress</TabsTrigger>
                      <TabsTrigger value="documents">Documents</TabsTrigger>
                      <TabsTrigger value="interviews">Interviews</TabsTrigger>
                      <TabsTrigger value="eor">EOR Checklist</TabsTrigger>
                      <TabsTrigger value="payments">Payments</TabsTrigger>
                      <TabsTrigger value="audit">Audit Trail</TabsTrigger>
                    </TabsList>
                  </div>
                </CardHeader>

                <CardContent>
                  {/* Questionnaire Response Tab */}
                  <TabsContent value="questionnaire" className="space-y-6">
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center gap-3">
                        <ClipboardList className="w-5 h-5 text-amber-600" />
                        <h3 className="text-slate-900">Questionnaire Responses</h3>
                      </div>
                      {application.questionnaireMarks !== undefined && (
                        <Badge className="bg-amber-600">Score: {application.questionnaireMarks}/100</Badge>
                      )}
                    </div>

                    <QuestionnaireForm applicationId={application.id} readOnly={true} />
                  </TabsContent>

                  {/* Progress Tab */}
                  <TabsContent value="progress" className="space-y-6">
                    <div>
                      <div className="flex items-center justify-between mb-4">
                        <h3 className="text-slate-900">Application Journey</h3>
                        <Badge className="bg-amber-600">{application.progress}% Complete</Badge>
                      </div>
                      <Progress value={application.progress} className="h-3 mb-6" />
                    </div>

                    <div className="relative">
                      {processStages.map((stage, index) => (
                        <div key={stage.id}>
                          <div className="flex gap-4 pb-8">
                            <div className="relative">
                              <div className={`w-10 h-10 rounded-full flex items-center justify-center border-2 ${stage.status === 'completed'
                                ? 'bg-green-500 border-green-500'
                                : stage.status === 'active'
                                  ? 'bg-amber-500 border-amber-500'
                                  : 'bg-slate-200 border-slate-300'
                                }`}>
                                {stage.isParallel ? (
                                  <GitBranch className="w-5 h-5 text-white" />
                                ) : (
                                  <>
                                    {stage.status === 'completed' && (
                                      <CheckCircle className="w-5 h-5 text-white" />
                                    )}
                                    {stage.status === 'active' && (
                                      <Clock className="w-5 h-5 text-white" />
                                    )}
                                    {stage.status === 'pending' && (
                                      <div className="w-3 h-3 bg-slate-400 rounded-full"></div>
                                    )}
                                  </>
                                )}
                              </div>
                              {index < processStages.length - 1 && !stage.isParallel && (
                                <div className={`absolute top-10 left-1/2 -translate-x-1/2 w-0.5 h-full ${stage.status === 'completed' ? 'bg-green-500' : 'bg-slate-300'
                                  }`}></div>
                              )}
                            </div>
                            <div className="flex-1 pt-1">
                              <p className="text-slate-900">{stage.name}</p>
                              {stage.description && (
                                <p className="text-slate-600 text-sm mt-0.5">{stage.description}</p>
                              )}
                              {stage.evaluators && (
                                <p className="text-amber-600 text-sm mt-0.5">
                                  Evaluators: {stage.evaluators.join(' + ')}
                                </p>
                              )}
                              {stage.documentsUploaded !== undefined && stage.documentsUploaded > 0 && (
                                <p
                                  className="text-blue-600 text-sm mt-0.5 cursor-pointer hover:underline hover:text-blue-700"
                                  onClick={() => {
                                    setSelectedStage(stage.name);
                                    setShowDocumentsModal(true);
                                  }}
                                >
                                  Documents uploaded = {stage.documentsUploaded}
                                </p>
                              )}
                              <p className="text-slate-500 mt-1">
                                {stage.status === 'completed' && stage.date && `Completed: ${new Date(stage.date).toLocaleDateString()}`}
                                {stage.status === 'active' && 'In Progress'}
                                {stage.status === 'pending' && 'Pending'}
                              </p>
                            </div>
                          </div>

                          {/* Parallel Branches */}
                          {stage.isParallel && stage.branches && (
                            <div className="ml-5 mb-8">
                              {stage.branches.map((branch, branchIndex) => {
                                const branchKey = branch.name.toLowerCase().replace(/\s+/g, '-');
                                const isExpanded = expandedBranches[branchKey];
                                const branchColor = branch.color === 'blue' ? 'blue' : 'green';

                                return (
                                  <div key={branchIndex} className="mb-6 last:mb-0">
                                    {/* Branch Header - Clickable */}
                                    <button
                                      onClick={() => setExpandedBranches(prev => ({
                                        ...prev,
                                        [branchKey]: !prev[branchKey]
                                      }))}
                                      className={`w-full flex items-center gap-3 p-4 rounded-lg border-2 transition-all hover:shadow-md ${branchColor === 'blue'
                                        ? 'border-blue-300 bg-blue-50 hover:bg-blue-100'
                                        : 'border-green-300 bg-green-50 hover:bg-green-100'
                                        }`}
                                    >
                                      {isExpanded ? (
                                        <ChevronDown className={`w-5 h-5 ${branchColor === 'blue' ? 'text-blue-600' : 'text-green-600'}`} />
                                      ) : (
                                        <ChevronRight className={`w-5 h-5 ${branchColor === 'blue' ? 'text-blue-600' : 'text-green-600'}`} />
                                      )}
                                      <div className={`w-8 h-8 rounded-full flex items-center justify-center ${branchColor === 'blue' ? 'bg-blue-200' : 'bg-green-200'
                                        }`}>
                                        <GitBranch className={`w-4 h-4 ${branchColor === 'blue' ? 'text-blue-700' : 'text-green-700'}`} />
                                      </div>
                                      <div className="flex-1 text-left">
                                        <p className={`${branchColor === 'blue' ? 'text-blue-900' : 'text-green-900'}`}>
                                          {branch.name}
                                        </p>
                                        <p className={`text-sm ${branchColor === 'blue' ? 'text-blue-700' : 'text-green-700'}`}>
                                          {branch.stages.length} steps
                                        </p>
                                      </div>
                                    </button>

                                    {/* Branch Content - Expandable */}
                                    {isExpanded && (
                                      <div className="mt-4 ml-8 border-l-2 border-slate-200 pl-6 space-y-6">
                                        {branch.stages.map((branchStage, stageIndex) => (
                                          <div key={branchStage.id} className="relative">
                                            <div className="flex gap-4">
                                              <div className="relative">
                                                <div className={`w-8 h-8 rounded-full flex items-center justify-center border-2 ${branchStage.status === 'completed'
                                                  ? `${branchColor === 'blue' ? 'bg-blue-500 border-blue-500' : 'bg-green-500 border-green-500'}`
                                                  : branchStage.status === 'active'
                                                    ? 'bg-amber-500 border-amber-500'
                                                    : 'bg-slate-200 border-slate-300'
                                                  }`}>
                                                  {branchStage.status === 'completed' && (
                                                    <CheckCircle className="w-4 h-4 text-white" />
                                                  )}
                                                  {branchStage.status === 'active' && (
                                                    <Clock className="w-4 h-4 text-white" />
                                                  )}
                                                  {branchStage.status === 'pending' && (
                                                    <div className="w-2 h-2 bg-slate-400 rounded-full"></div>
                                                  )}
                                                </div>
                                              </div>
                                              <div className="flex-1">
                                                <p className="text-slate-900">{branchStage.name}</p>
                                                {branchStage.description && (
                                                  <p className="text-slate-600 text-sm mt-0.5">{branchStage.description}</p>
                                                )}
                                                {branchStage.documentsUploaded !== undefined && branchStage.documentsUploaded > 0 && (
                                                  <p
                                                    className="text-blue-600 text-sm mt-0.5 cursor-pointer hover:underline hover:text-blue-700"
                                                    onClick={() => {
                                                      setSelectedStage(branchStage.name);
                                                      setShowDocumentsModal(true);
                                                    }}
                                                  >
                                                    Documents uploaded = {branchStage.documentsUploaded}
                                                  </p>
                                                )}
                                                <p className="text-slate-500 text-sm mt-1">
                                                  {branchStage.status === 'completed' && branchStage.date && `Completed: ${new Date(branchStage.date).toLocaleDateString()}`}
                                                  {branchStage.status === 'active' && 'In Progress'}
                                                  {branchStage.status === 'pending' && 'Pending'}
                                                </p>
                                              </div>
                                            </div>
                                          </div>
                                        ))}
                                      </div>
                                    )}
                                  </div>
                                );
                              })}

                              {/* Connecting line to next stage */}
                              <div className="h-8 w-0.5 bg-slate-300 ml-5"></div>
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  </TabsContent>

                  {/* Documents Tab */}
                  <TabsContent value="documents" className="space-y-4">
                    <div className="flex items-center justify-between">
                      <h3 className="text-slate-900">Uploaded Documents</h3>
                      <Button size="sm" className="bg-amber-600 hover:bg-amber-700">
                        <Upload className="w-4 h-4 mr-2" />
                        Upload Document
                      </Button>
                    </div>

                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>File Name</TableHead>
                          <TableHead>Type</TableHead>
                          <TableHead>Upload Date</TableHead>
                          <TableHead>Uploader</TableHead>
                          <TableHead>Actions</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {mockDocuments.map((doc) => (
                          <TableRow key={doc.id}>
                            <TableCell className="flex items-center gap-2">
                              <FileText className="w-4 h-4 text-slate-400" />
                              {doc.name}
                            </TableCell>
                            <TableCell>{doc.type}</TableCell>
                            <TableCell>{new Date(doc.uploadDate).toLocaleDateString()}</TableCell>
                            <TableCell>{doc.uploader || '-'}</TableCell>
                            <TableCell>
                              <div className="flex gap-2">
                                <Button size="sm" variant="outline">
                                  <Download className="w-3 h-3" />
                                </Button>
                              </div>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TabsContent>

                  {/* Interviews Tab */}
                  <TabsContent value="interviews" className="space-y-6">
                    <div>
                      <h3 className="text-slate-900 mb-4">Level 1 Interview - KT Matrix</h3>
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Interviewer</TableHead>
                            <TableHead>Role</TableHead>
                            <TableHead>Score</TableHead>
                            <TableHead>Remarks</TableHead>
                            <TableHead>Feedback</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {mockLevel1Scores.map((score, idx) => (
                            <TableRow key={idx}>
                              <TableCell>{score.user}</TableCell>
                              <TableCell>{score.role}</TableCell>
                              <TableCell>{score.score}/50</TableCell>
                              <TableCell>{score.remarks}</TableCell>
                              <TableCell>{score.feedback}</TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>

                    {['Level 2 Approved', 'Level 3 Pending', 'Approved'].includes(application.status) && (
                      <div>
                        <h3 className="text-slate-900 mb-4">Level 2 Interview Summary</h3>
                        <div className="p-4 bg-slate-50 rounded-lg">
                          <p className="text-slate-600">Decision: Approved by both ZBH and DD Lead</p>
                          <p className="text-slate-600 mt-2">Overall Assessment: Strong candidate with excellent business plan</p>
                        </div>
                      </div>
                    )}
                  </TabsContent>

                  {/* EOR Checklist Tab */}
                  <TabsContent value="eor" className="space-y-4">
                    <div className="flex items-center justify-between mb-4">
                      <h3 className="text-slate-900">Essential Operating Requirements</h3>
                      <Badge className="bg-amber-600">{Math.round(eorProgress)}% Complete</Badge>
                    </div>
                    <Progress value={eorProgress} className="h-3 mb-6" />

                    <div className="space-y-3">
                      {eorChecklist.map((item) => (
                        <div key={item.id} className="flex items-center gap-3 p-3 bg-slate-50 rounded-lg">
                          <Checkbox checked={item.completed} />
                          <span className={item.completed ? 'text-slate-900' : 'text-slate-600'}>
                            {item.item}
                          </span>
                          {item.completed && (
                            <CheckCircle className="w-4 h-4 text-green-600 ml-auto" />
                          )}
                        </div>
                      ))}
                    </div>
                  </TabsContent>

                  {/* Payments Tab */}
                  <TabsContent value="payments" className="space-y-4">
                    <h3 className="text-slate-900 mb-4">Payment Information</h3>

                    <div className="space-y-4">
                      <div className="p-4 border border-slate-200 rounded-lg">
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-slate-600">Advance Payment</span>
                          <Badge variant="default">Paid</Badge>
                        </div>
                        <p className="text-slate-900">₹5,00,000</p>
                        <p className="text-slate-500 mt-2">Receipt: RCP-2025-001.pdf</p>
                      </div>

                      <div className="p-4 border border-slate-200 rounded-lg">
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-slate-600">Final Payment</span>
                          <Badge variant="secondary">Pending</Badge>
                        </div>
                        <p className="text-slate-900">₹15,00,000</p>
                      </div>

                      {application.status === 'EOR In Progress' && (
                        <Button className="w-full bg-amber-600 hover:bg-amber-700">
                          Request Payment
                        </Button>
                      )}
                    </div>
                  </TabsContent>

                  {/* Audit Trail Tab */}
                  <TabsContent value="audit">
                    <ScrollArea className="h-96">
                      <div className="space-y-4">
                        {mockAuditLogs.map((log) => (
                          <div key={log.id} className="flex gap-4 p-3 hover:bg-slate-50 rounded-lg">
                            <div className="w-2 h-2 bg-amber-600 rounded-full mt-2 flex-shrink-0"></div>
                            <div className="flex-1">
                              <div className="flex items-start justify-between">
                                <p className="text-slate-900">{log.action}</p>
                                <span className="text-slate-500">{log.timestamp}</span>
                              </div>
                              <p className="text-slate-600 mt-1">by {log.user}</p>
                              <p className="text-slate-500 mt-1">{log.details}</p>
                            </div>
                          </div>
                        ))}
                      </div>
                    </ScrollArea>
                  </TabsContent>
                </CardContent>
              </Tabs>
            </Card>
          )}
        </div>

        {/* Right Sidebar - Summary and Actions */}
        <div className="space-y-6">
          {/* Summary Card */}
          <Card>
            <CardHeader>
              <CardTitle>Summary</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <p className="text-slate-600">Registration ID</p>
                <p className="text-slate-900">{application.registrationNumber}</p>
              </div>
              <div>
                <p className="text-slate-600">Current Status</p>
                <Badge className="mt-1">{application.status}</Badge>
              </div>
              {application.rank && (
                <div>
                  <p className="text-slate-600">Rank</p>
                  <p className="text-slate-900">
                    {application.rank} of {application.totalApplicantsAtLocation}
                    <span className="text-slate-500"> in {application.preferredLocation}</span>
                  </p>
                </div>
              )}
              <div>
                <p className="text-slate-600">Progress</p>
                <div className="flex items-center gap-2 mt-2">
                  <Progress value={application.progress} className="flex-1" />
                  <span className="text-slate-900">{application.progress}%</span>
                </div>
              </div>
              {application.deadline && (
                <div>
                  <p className="text-slate-600">Questionnaire Deadline</p>
                  <p className="text-slate-900">{new Date(application.deadline).toLocaleDateString()}</p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Actions Card */}
          {/* Only show Actions card for shortlisted applications (opportunity requests and regular dealership requests) */}
          {/* Hide Actions for unopportunity requests (lead generation) - these are read-only records */}
          {application.isShortlisted !== false && (
            <Card>
              <CardHeader>
                <CardTitle>Actions</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <Button
                  className="w-full bg-green-600 hover:bg-green-700"
                  onClick={() => setShowApproveModal(true)}
                >
                  <CheckCircle className="w-4 h-4 mr-2" />
                  Approve
                </Button>

                <Button
                  variant="destructive"
                  className="w-full"
                  onClick={() => setShowRejectModal(true)}
                >
                  <XCircle className="w-4 h-4 mr-2" />
                  Reject
                </Button>

                <Separator />

                <Button
                  variant="outline"
                  className="w-full"
                  onClick={() => setShowWorkNotesPage(true)}
                >
                  <MessageSquare className="w-4 h-4 mr-2" />
                  Work Note
                </Button>

                <Button
                  variant="outline"
                  className="w-full"
                  onClick={() => setShowScheduleModal(true)}
                >
                  <Calendar className="w-4 h-4 mr-2" />
                  Schedule Interview
                </Button>

                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="outline" className="w-full">
                      <Star className="w-4 h-4 mr-2" />
                      Interview Feedback
                      <ChevronDown className="w-4 h-4 ml-auto" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent className="w-56">
                    <DropdownMenuItem onClick={() => setShowKTMatrixModal(true)}>
                      Fill KT Matrix
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => setShowLevel2FeedbackModal(true)}>
                      Level 2 Feedback
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => setShowLevel3FeedbackModal(true)}>
                      Level 3 Feedback
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>

                {application.status === 'Questionnaire Pending' && (
                  <>
                    <Button variant="outline" className="w-full">
                      <Mail className="w-4 h-4 mr-2" />
                      Send Reminder
                    </Button>

                    <Button variant="outline" className="w-full">
                      <Clock className="w-4 h-4 mr-2" />
                      Extend Deadline
                    </Button>
                  </>
                )}

                <Button variant="outline" className="w-full">
                  <User className="w-4 h-4 mr-2" />
                  Assign User
                </Button>
              </CardContent>
            </Card>
          )}

          {/* Work Notes Chat */}
          {/* Only show Work Notes card for shortlisted applications (opportunity requests and regular dealership requests) */}
          {/* Hide Work Notes for unopportunity requests (lead generation) - no workflow tracking needed */}
          {application.isShortlisted !== false && (
            <Card>
              <CardHeader>
                <CardTitle>Work Notes</CardTitle>
              </CardHeader>
              <CardContent>
                <ScrollArea className="h-64">
                  <div className="space-y-4">
                    {mockWorkNotes.map((note) => (
                      <div key={note.id} className="flex gap-3">
                        <div className="w-8 h-8 bg-amber-600 rounded-full flex items-center justify-center flex-shrink-0">
                          <span className="text-white">{note.user.charAt(0)}</span>
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <p className="text-slate-900">{note.user}</p>
                            <span className="text-slate-500">{note.timestamp}</span>
                          </div>
                          <p className="text-slate-600 mt-1">{note.message}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </ScrollArea>
              </CardContent>
            </Card>
          )}
        </div>
      </div>

      {/* Approve Modal */}
      <Dialog open={showApproveModal} onOpenChange={setShowApproveModal}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Approve Application</DialogTitle>
            <DialogDescription>
              Provide approval remarks and optionally attach supporting documents.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Remark (Required)</Label>
              <Textarea
                placeholder="Enter approval remarks..."
                value={approvalRemark}
                onChange={(e) => setApprovalRemark(e.target.value)}
                className="mt-2"
                rows={4}
              />
            </div>
            <div>
              <Label>Attach File (Optional)</Label>
              <Input type="file" className="mt-2" />
            </div>
            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => setShowApproveModal(false)}
              >
                Cancel
              </Button>
              <Button
                className="flex-1 bg-green-600 hover:bg-green-700"
                onClick={handleApprove}
              >
                Submit Approval
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Reject Modal */}
      <Dialog open={showRejectModal} onOpenChange={setShowRejectModal}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Reject Application</DialogTitle>
            <DialogDescription>
              Please provide a clear reason for rejecting this application.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Reason for Rejection (Required)</Label>
              <Textarea
                placeholder="Enter rejection reason..."
                value={rejectionReason}
                onChange={(e) => setRejectionReason(e.target.value)}
                className="mt-2"
                rows={4}
              />
            </div>
            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => setShowRejectModal(false)}
              >
                Cancel
              </Button>
              <Button
                variant="destructive"
                className="flex-1"
                onClick={handleReject}
              >
                Confirm Rejection
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Work Note Modal */}
      <Dialog open={showWorkNoteModal} onOpenChange={setShowWorkNoteModal}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Add Work Note</DialogTitle>
            <DialogDescription>
              Add a note to track progress and communicate with team members.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Note</Label>
              <Textarea
                placeholder="Enter your note... Use @username to mention someone"
                value={workNote}
                onChange={(e) => setWorkNote(e.target.value)}
                className="mt-2"
                rows={4}
              />
            </div>
            <div>
              <Label>Attachments (Optional)</Label>
              <Input type="file" className="mt-2" multiple />
            </div>
            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => setShowWorkNoteModal(false)}
              >
                Cancel
              </Button>
              <Button
                className="flex-1 bg-amber-600 hover:bg-amber-700"
                onClick={handleWorkNote}
              >
                Add Note
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Schedule Interview Modal */}
      <Dialog open={showScheduleModal} onOpenChange={setShowScheduleModal}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Schedule Interview</DialogTitle>
            <DialogDescription>
              Set up an interview session with the applicant and relevant team members.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Interview Type</Label>
              <Select>
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="Select interview type" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="level1">Level 1</SelectItem>
                  <SelectItem value="level2">Level 2</SelectItem>
                  <SelectItem value="level3">Level 3</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>Interview Mode</Label>
              <Select value={interviewMode} onValueChange={setInterviewMode}>
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="Select interview mode" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="virtual">Virtual</SelectItem>
                  <SelectItem value="physical">Physical</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>Date & Time</Label>
              <Input type="datetime-local" className="mt-2" />
            </div>
            <div>
              <Label>Participants</Label>
              <Input placeholder="Enter participant emails (comma-separated)" className="mt-2" />
            </div>
            {interviewMode === 'virtual' && (
              <div>
                <Label>Meeting Link</Label>
                <Input placeholder="https://meet.google.com/..." className="mt-2" />
              </div>
            )}
            {interviewMode === 'physical' && (
              <div>
                <Label>Location</Label>
                <Input placeholder="Enter interview location address" className="mt-2" />
              </div>
            )}
            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => setShowScheduleModal(false)}
              >
                Cancel
              </Button>
              <Button
                className="flex-1 bg-amber-600 hover:bg-amber-700"
                onClick={() => {
                  alert('Interview scheduled! Calendar invites will be sent.');
                  setShowScheduleModal(false);
                }}
              >
                Schedule
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* KT Matrix Modal */}
      <Dialog open={showKTMatrixModal} onOpenChange={setShowKTMatrixModal}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Fill KT Matrix</DialogTitle>
            <DialogDescription>
              Complete the Knowledge Transfer Matrix evaluation for the applicant.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>Age (Weightage: 5%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select age range" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="20-40">20 to 40 years old (10 points)</SelectItem>
                    <SelectItem value="40-50">40 to 50 years old (5 points)</SelectItem>
                    <SelectItem value="above-50">Above 50 years old (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Qualification (Weightage: 5%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select qualification" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="post-graduate">Post Graduate (10 points)</SelectItem>
                    <SelectItem value="graduate">Graduate (5 points)</SelectItem>
                    <SelectItem value="sslc">SSLC (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Local Knowledge and Influence (Weightage: 5%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select PR level" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="excellent">Excellent PR (10 points)</SelectItem>
                    <SelectItem value="good">Good PR (5 points)</SelectItem>
                    <SelectItem value="poor">Poor PR (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Base Location vs Applied Location (Weightage: 10%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select location status" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="native">Native of the Applied location (10 points)</SelectItem>
                    <SelectItem value="relocate">Willing to relocate (5 points)</SelectItem>
                    <SelectItem value="remote">Will manage remotely with occasional visits (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Why Interested in Royal Enfield Business? (Weightage: 10%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select reason" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="passion">Passion (10 points)</SelectItem>
                    <SelectItem value="business">Business expansion / Status symbol (5 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Passion for Royal Enfield (Weightage: 10%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select ownership status" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="owns">Currently owns a Royal Enfield (10 points)</SelectItem>
                    <SelectItem value="relative">Owned by Immediate Relative (5 points)</SelectItem>
                    <SelectItem value="none">Does not own Royal Enfield (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Passion For Rides (Weightage: 10%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select riding frequency" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="regular">Goes for long rides regularly (10 points)</SelectItem>
                    <SelectItem value="rarely">Goes for long rides rarely (5 points)</SelectItem>
                    <SelectItem value="never">Doesn't go for rides (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>With Whom Partnering? (Weightage: 5%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select partnership type" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="family">Within family (10 points)</SelectItem>
                    <SelectItem value="outside">Outside family (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Who Will Manage the Firm? (Weightage: 10%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select management model" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="owner">Owner managed (10 points)</SelectItem>
                    <SelectItem value="partly">Partly owner / partly manager model (5 points)</SelectItem>
                    <SelectItem value="manager">Fully manager model (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Business Acumen (Weightage: 5%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select experience level" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="automobile">Has similar automobile experience (10 points)</SelectItem>
                    <SelectItem value="other-business">Has successful business but not automobile (5 points)</SelectItem>
                    <SelectItem value="no-experience">No business experience (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Time Availability (Weightage: 5%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select availability" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="full-time">Full Time Availability for RE Business (10 points)</SelectItem>
                    <SelectItem value="part-time">Part Time Availability for RE Business (5 points)</SelectItem>
                    <SelectItem value="manager">Not Available personally, Manager will handle (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Property Ownership (Weightage: 5%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select property status" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="own">Has own property in proposed location (10 points)</SelectItem>
                    <SelectItem value="rent">Will rent / lease (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Investment in the Business (Weightage: 5%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select funding source" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="own-funds">Full own funds (10 points)</SelectItem>
                    <SelectItem value="partial-bank">Partially from the bank (5 points)</SelectItem>
                    <SelectItem value="full-bank">Completely bank funded (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Will Expand to Other 2W/4W OEMs? (Weightage: 5%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select expansion plan" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="no">No (10 points)</SelectItem>
                    <SelectItem value="yes">Yes (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Plans of Expansion with RE (Weightage: 5%)</Label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="Select expansion plan" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="blood-relation">Immediate blood relation will join & expand (10 points)</SelectItem>
                    <SelectItem value="self-expand">Wants to expand by himself into more clusters (5 points)</SelectItem>
                    <SelectItem value="no-plans">No plans for expansion (0 points)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <Separator />

            <div className="bg-slate-50 p-4 rounded-lg">
              <p className="text-slate-700">
                <span className="font-medium">Total Weightage:</span> 100%
              </p>
              <p className="text-slate-600 text-sm mt-1">
                All parameters will be scored and calculated automatically based on the selected options.
              </p>
            </div>

            <div>
              <Label>Remarks</Label>
              <Textarea
                placeholder="Enter additional remarks, observations, and recommendations..."
                className="mt-2"
                rows={4}
              />
            </div>

            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => setShowKTMatrixModal(false)}
              >
                Cancel
              </Button>
              <Button
                className="flex-1 bg-amber-600 hover:bg-amber-700"
                onClick={() => {
                  alert('KT Matrix submitted successfully!');
                  setShowKTMatrixModal(false);
                }}
              >
                Submit KT Matrix
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Level 2 Feedback Modal */}
      <Dialog open={showLevel2FeedbackModal} onOpenChange={setShowLevel2FeedbackModal}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Level 2 Interview Feedback</DialogTitle>
            <DialogDescription>
              Provide detailed feedback from the Level 2 interview (DD Lead + ZBH evaluation).
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Interview Date</Label>
              <Input type="date" className="mt-2" />
            </div>

            <div>
              <Label>Interviewer Name</Label>
              <Input placeholder="Enter your name" className="mt-2" />
            </div>

            <div>
              <Label>Overall Performance Score</Label>
              <Select>
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="Select score" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="10">Outstanding (9-10)</SelectItem>
                  <SelectItem value="8">Excellent (7-8)</SelectItem>
                  <SelectItem value="6">Good (5-6)</SelectItem>
                  <SelectItem value="4">Average (3-4)</SelectItem>
                  <SelectItem value="2">Below Average (1-2)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <Separator />

            <div>
              <Label>Strategic Vision</Label>
              <Textarea
                placeholder="Evaluate the candidate's strategic thinking and long-term vision..."
                className="mt-2"
                rows={3}
              />
            </div>

            <div>
              <Label>Management Capabilities</Label>
              <Textarea
                placeholder="Assess leadership and team management potential..."
                className="mt-2"
                rows={3}
              />
            </div>

            <div>
              <Label>Operational Understanding</Label>
              <Textarea
                placeholder="Review understanding of dealership operations and processes..."
                className="mt-2"
                rows={3}
              />
            </div>

            <div>
              <Label>Key Strengths</Label>
              <Textarea
                placeholder="List the candidate's key strengths and positive attributes..."
                className="mt-2"
                rows={3}
              />
            </div>

            <div>
              <Label>Areas of Concern</Label>
              <Textarea
                placeholder="Highlight any concerns or areas needing improvement..."
                className="mt-2"
                rows={3}
              />
            </div>

            <div>
              <Label>Final Recommendation</Label>
              <Select>
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="Select recommendation" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="proceed-level3">Proceed to Level 3</SelectItem>
                  <SelectItem value="hold">Hold Decision</SelectItem>
                  <SelectItem value="reject">Reject</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>Additional Comments</Label>
              <Textarea
                placeholder="Any additional observations or comments..."
                className="mt-2"
                rows={3}
              />
            </div>

            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => setShowLevel2FeedbackModal(false)}
              >
                Cancel
              </Button>
              <Button
                className="flex-1 bg-blue-600 hover:bg-blue-700"
                onClick={() => {
                  alert('Level 2 feedback submitted successfully!');
                  setShowLevel2FeedbackModal(false);
                }}
              >
                Submit Feedback
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Level 3 Feedback Modal */}
      <Dialog open={showLevel3FeedbackModal} onOpenChange={setShowLevel3FeedbackModal}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Level 3 Interview Feedback</DialogTitle>
            <DialogDescription>
              Provide detailed feedback from the Level 3 interview (NBH + DD-Head evaluation).
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Interview Date</Label>
              <Input type="date" className="mt-2" />
            </div>

            <div>
              <Label>Interviewer Name</Label>
              <Input placeholder="Enter your name" className="mt-2" />
            </div>

            <div>
              <Label>Overall Performance Score</Label>
              <Select>
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="Select score" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="10">Outstanding (9-10)</SelectItem>
                  <SelectItem value="8">Excellent (7-8)</SelectItem>
                  <SelectItem value="6">Good (5-6)</SelectItem>
                  <SelectItem value="4">Average (3-4)</SelectItem>
                  <SelectItem value="2">Below Average (1-2)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <Separator />

            <div>
              <Label>Business Vision & Strategy</Label>
              <Textarea
                placeholder="Evaluate the candidate's long-term business vision and strategic planning..."
                className="mt-2"
                rows={3}
              />
            </div>

            <div>
              <Label>Leadership & Decision Making</Label>
              <Textarea
                placeholder="Assess leadership qualities and decision-making capabilities..."
                className="mt-2"
                rows={3}
              />
            </div>

            <div>
              <Label>Investment Commitment</Label>
              <Textarea
                placeholder="Review financial commitment and investment readiness..."
                className="mt-2"
                rows={3}
              />
            </div>

            <div>
              <Label>Brand Alignment</Label>
              <Textarea
                placeholder="Evaluate alignment with Royal Enfield brand values and culture..."
                className="mt-2"
                rows={3}
              />
            </div>

            <div>
              <Label>Key Strengths</Label>
              <Textarea
                placeholder="List the candidate's key strengths and exceptional qualities..."
                className="mt-2"
                rows={3}
              />
            </div>

            <div>
              <Label>Risk Factors</Label>
              <Textarea
                placeholder="Identify any potential risks or concerns..."
                className="mt-2"
                rows={3}
              />
            </div>

            <div>
              <Label>Final Decision</Label>
              <Select>
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="Select decision" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="approve">Approve for FDD</SelectItem>
                  <SelectItem value="conditional">Conditional Approval</SelectItem>
                  <SelectItem value="reject">Reject</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>Executive Summary</Label>
              <Textarea
                placeholder="Provide a comprehensive executive summary of the interview and final thoughts..."
                className="mt-2"
                rows={4}
              />
            </div>

            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => setShowLevel3FeedbackModal(false)}
              >
                Cancel
              </Button>
              <Button
                className="flex-1 bg-purple-600 hover:bg-purple-700"
                onClick={() => {
                  alert('Level 3 feedback submitted successfully!');
                  setShowLevel3FeedbackModal(false);
                }}
              >
                Submit Feedback
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Documents Modal */}
      <Dialog open={showDocumentsModal} onOpenChange={setShowDocumentsModal}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Documents - {selectedStage}</DialogTitle>
            <DialogDescription>
              View and manage documents uploaded for this stage.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {selectedStage && getDocumentsForStage(selectedStage).length > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Document Name</TableHead>
                    <TableHead>Type</TableHead>
                    <TableHead>Upload Date</TableHead>
                    <TableHead>Uploaded By</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {getDocumentsForStage(selectedStage).map((doc) => (
                    <TableRow key={doc.id}>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <FileText className="w-4 h-4 text-slate-400" />
                          <span>{doc.name}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{doc.type}</Badge>
                      </TableCell>
                      <TableCell>{new Date(doc.uploadDate).toLocaleDateString()}</TableCell>
                      <TableCell>{doc.uploader}</TableCell>
                      <TableCell className="text-right">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => alert(`Downloading ${doc.name}`)}
                        >
                          <Download className="w-4 h-4 mr-1" />
                          Download
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            ) : (
              <div className="flex flex-col items-center justify-center py-12 text-center">
                <FileText className="w-16 h-16 text-slate-300 mb-4" />
                <h3 className="text-slate-900 mb-2">No Documents</h3>
                <p className="text-slate-600">No documents have been uploaded for this stage yet.</p>
              </div>
            )}

            <Separator />

            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1"
              >
                <Upload className="w-4 h-4 mr-2" />
                Upload Document
              </Button>
              <Button
                variant="outline"
                onClick={() => setShowDocumentsModal(false)}
              >
                Close
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
