import { ProcessStage } from '@/features/onboarding/components/application-details/applicationDetails.shared';

interface UseApplicationDetailsStageDataParams {
  application: any;
  documents: any[];
  interviews: any[];
  eorData: any;
  getDeposit: (type: string) => any;
  documentConfigs?: any[];
}

export function useApplicationDetailsStageData({
  application,
  documents,
  interviews: _interviews,
  eorData,
  getDeposit,
  documentConfigs = [],
}: UseApplicationDetailsStageDataParams) {
  const normalizeRole = (value: unknown): string =>
    String(value || '')
      .trim()
      .toLowerCase()
      .replace(/[_\s-]+/g, ' ');

  const hasAnyRole = (participant: any, expectedRoles: string[]) => {
    const userRoles = [
      participant?.user?.role,
      participant?.user?.roleCode,
      participant?.metadata?.role,
    ].map(normalizeRole);
    const target = expectedRoles.map(normalizeRole);
    return userRoles.some((r) => target.includes(r));
  };

  const participantLabel = (participant: any) =>
    `${participant?.user?.fullName || participant?.user?.name || 'User'} (${participant?.user?.role || participant?.user?.roleCode || participant?.metadata?.role || participant?.participantType || 'participant'})`;

  const isDocumentUploaded = (docType: string) => {
    return (documents || []).some((d) => d.documentType === docType);
  };

  const getStageStatus = (stageName: string, fallbackStatus: ProcessStage['status'] = 'pending'): ProcessStage['status'] => {
    const backendStage = (application.progressTracking || []).find((ps: any) => ps.stageName === stageName);
    return backendStage?.status ? (backendStage.status as any) : fallbackStatus;
  };

  const processStages: ProcessStage[] = [
    { id: 1, name: 'Submitted', status: 'completed', date: application.submissionDate, description: 'Application submitted', documentsUploaded: 3 },
    {
      id: 2, name: 'Questionnaire', status: getStageStatus('Questionnaire'),
      date: application.questionnaireDate, description: 'Questionnaire completed', documentsUploaded: 0
    },
    {
      id: 3, name: 'Shortlist', status: getStageStatus('Shortlist'),
      date: application.shortlistDate, description: 'Application shortlisted by DD',
      evaluators: Array.from(new Set((application.participants || []).filter((p: any) => p.participantType === 'assignee').map((p: any) => `${p.user?.fullName || p.user?.name || 'User'} (${p.user?.roleCode || p.participantType})`))),
      documentsUploaded: 2
    },
    {
      id: 4, name: '1st Level Interview', status: getStageStatus('1st Level Interview'),
      date: application.level1InterviewDate, description: 'DD-ZM + RBM evaluation',
      evaluators: Array.from(new Set(
        (application.participants || [])
          .filter((p: any) =>
            p.metadata?.interviewLevel === 1 ||
            p.metadata?.interviewLevel === '1' ||
            p.metadata?.allAssignments?.includes(1) ||
            p.metadata?.allAssignments?.includes('1') ||
            hasAnyRole(p, ['DD-ZM', 'RBM'])
          )
          .map(participantLabel)
      )),
      documentsUploaded: 1
    },
    {
      id: 5, name: '2nd Level Interview', status: getStageStatus('2nd Level Interview'),
      date: application.level2InterviewDate, description: 'DD Lead + ZBH evaluation',
      evaluators: Array.from(new Set(
        (application.participants || [])
          .filter((p: any) =>
            p.metadata?.interviewLevel === 2 ||
            p.metadata?.interviewLevel === '2' ||
            p.metadata?.allAssignments?.includes(2) ||
            p.metadata?.allAssignments?.includes('2') ||
            hasAnyRole(p, ['DD Lead', 'ZBH'])
          )
          .map(participantLabel)
      )),
      documentsUploaded: 1
    },
    {
      id: 6, name: '3rd Level Interview', status: getStageStatus('3rd Level Interview'),
      date: application.level3InterviewDate, description: 'NBH + DD Head evaluation',
      evaluators: Array.from(new Set(
        (application.participants || [])
          .filter((p: any) =>
            p.metadata?.interviewLevel === 3 ||
            p.metadata?.interviewLevel === '3' ||
            p.metadata?.allAssignments?.includes(3) ||
            p.metadata?.allAssignments?.includes('3') ||
            hasAnyRole(p, ['NBH', 'DD Head'])
          )
          .map(participantLabel)
      )),
      documentsUploaded: 2
    },
    { id: 7, name: 'FDD', status: getStageStatus('FDD'), date: application.fddDate, description: 'Financial Due Diligence', documentsUploaded: 5 },
    {
      id: 8, name: 'LOI Approval', status: getStageStatus('LOI Approval'),
      date: application.loiApprovalDate, description: 'Letter of Intent approval',
      evaluators: Array.from(new Set((application.participants || []).filter((p: any) => p.metadata?.stageCode === 'LOI_APPROVAL' || p.metadata?.allAssignments?.includes('LOI_APPROVAL')).map(participantLabel))),
      documentsUploaded: 1
    },
    {
      id: 9, name: 'Security Details', status: getStageStatus('Security Details'),
      date: application.securityDetailsDate, description: 'Security verification', documentsUploaded: 3
    },
    {
      id: 10, name: 'LOI Issue', status: getStageStatus('LOI Issue'),
      date: application.loiIssueDate, description: 'Letter of Intent issued', isParallel: true,
      branches: [
        {
          name: 'LOI Documents', color: 'green', stages:
            documentConfigs.some((c: any) => c.stageCode === 'LOI Issue')
              ? documentConfigs.filter((c: any) => c.stageCode === 'LOI Issue').map((c: any, i: number) => ({
                id: `10a-${i}`,
                name: c.documentType,
                status: isDocumentUploaded(c.documentType) ? 'completed' : 'active',
                description: c.isMandatory ? `Upload ${c.documentType} (Mandatory)` : `Upload ${c.documentType}`
              }))
              : [
                { id: '10a-1', name: 'Letter of Intent', status: isDocumentUploaded('Letter of Intent') || isDocumentUploaded('LOI') ? 'completed' : 'active', description: 'Letter of Intent document' },
                { id: '10a-2', name: 'Signed LOI', status: isDocumentUploaded('Signed LOI') || isDocumentUploaded('LOI Signed Copy') ? 'completed' : 'active', description: 'Signed Letter of Intent' },
              ]
        }
      ]
    },
    {
      id: 11, name: 'Dealer Code Generation', status: getStageStatus('Dealer Code Generation'),
      date: application.dealerCodeDate, description: 'Dealer code generated and assigned', isParallel: true,
      branches: [
        {
          name: 'Architectural Work', color: 'green', stages: [
            { id: '11a-1', name: 'Architecture Assignment', status: application.architectureAssignedTo ? 'completed' : application.status === 'Architecture Team Assigned' ? 'active' : 'pending', description: 'Assigned to architecture team' },
            { id: '11a-2', name: 'Site Plan Blueprint', status: isDocumentUploaded('Architecture Blueprint') ? 'completed' : application.architectureAssignedTo ? 'active' : 'pending', description: 'Blueprints and site plans' },
            { id: '11a-3', name: 'Architecture Work', status: application.architectureStatus === 'COMPLETED' ? 'completed' : (application.architectureStatus === 'IN_PROGRESS' || isDocumentUploaded('Architecture Blueprint')) ? 'active' : 'pending', description: 'Final architecture approval' },
          ]
        },
        {
          name: 'Statutory Documents', color: 'green', stages: [
            { id: '11b-1', name: 'GST', status: isDocumentUploaded('GST Certificate') || isDocumentUploaded('GST') ? 'completed' : 'active', description: 'GST certificate' },
            { id: '11b-2', name: 'PAN', status: isDocumentUploaded('PAN Card') || isDocumentUploaded('PAN') ? 'completed' : 'active', description: 'PAN card' },
            { id: '11b-3', name: 'Nodal Agreement', status: isDocumentUploaded('Nodal Agreement') ? 'completed' : 'active', description: 'Nodal agreement document' },
            { id: '11b-4', name: 'Cancelled Check', status: isDocumentUploaded('Cancelled Check') ? 'completed' : 'active', description: 'Cancelled check copy' },
            { id: '11b-5', name: 'Partnership Deed/LLP/MOA/AOA/COI', status: isDocumentUploaded('Partnership Deed/LLP/MOA/AOA/COI') || isDocumentUploaded('Partnership Deed') ? 'completed' : 'active', description: 'Business entity documents' },
            { id: '11b-6', name: 'Firm Registration Certificate', status: isDocumentUploaded('Firm Registration Certificate') || isDocumentUploaded('Firm Registration') ? 'completed' : 'active', description: 'Firm registration certificate' },
            { id: '11b-7', name: 'Rental agreement/ Lease agreement / Own/ Land agreement', status: isDocumentUploaded('Rental agreement/ Lease agreement / Own/ Land agreement') || isDocumentUploaded('Property Document') ? 'completed' : 'active', description: 'Property agreement document' },
            { id: '11b-8', name: 'Virtual Code', status: isDocumentUploaded('Virtual Code') || isDocumentUploaded('Virtual Code Confirmation') ? 'completed' : 'active', description: 'Virtual code availability' },
            { id: '11b-9', name: 'Domain ID', status: isDocumentUploaded('Domain ID') || isDocumentUploaded('Domain ID Setup') ? 'completed' : 'active', description: 'Domain ID setup' },
            { id: '11b-10', name: 'MSD Configuration', status: isDocumentUploaded('MSD Configuration') ? 'completed' : 'active', description: 'Microsoft Dynamics configuration' },
            { id: '11b-11', name: 'LOI Acknowledgement Copy', status: isDocumentUploaded('LOI Acknowledgement Copy') || isDocumentUploaded('LOI Acknowledgement') ? 'completed' : 'active', description: 'LOI acknowledgement copy' },
          ]
        },
      ]
    },
    {
      id: 12, name: 'LOA', status: getStageStatus('LOA'),
      isLocked: application.status === 'LOA Pending' && getDeposit('FIRST_FILL')?.status !== 'Verified',
      lockMessage: 'First Fill (₹15L) must be verified by Finance before LOA Approval.',
      evaluators: Array.from(new Set((application.participants || []).filter((p: any) => p.metadata?.stageCode === 'LOA_APPROVAL' || p.metadata?.allAssignments?.includes('LOA_APPROVAL')).map(participantLabel))),
      description: 'Letter of Authorization'
    },
    { id: 13, name: 'EOR Complete', status: getStageStatus('EOR Complete'), description: 'Essential Operating Requirements' },
    { id: 14, name: 'Inauguration', status: getStageStatus('Inauguration'), description: 'Dealership inauguration' },
    { id: 15, name: 'Dealership Active', status: getStageStatus('Onboarded'), description: 'Dealer profile active' },
  ];

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

  const flattenedStages: any[] = processStages.reduce((acc: any[], stage: any) => {
    acc.push({ name: stage.name });
    if (stage.branches) {
      stage.branches.forEach((branch: any) => branch.stages.forEach((subStage: any) => acc.push({ name: subStage.name, parentBranch: branch.name })));
    }
    if (stage.name === 'EOR In Progress' || stage.name === 'EOR Complete') {
      (eorData?.items || eorChecklist).forEach((item: any) => acc.push({ name: `EOR: ${item.description || item.item}`, parentBranch: 'EOR' }));
    }
    return acc;
  }, []);

  const getDocumentsForStage = (stageName: string) =>
    documents.filter((doc) => doc.stage === stageName || (!doc.stage && doc.documentType?.toLowerCase().includes(stageName.toLowerCase().split(' ')[0])));

  return { processStages, eorChecklist, flattenedStages, getDocumentsForStage };
}
