import { useState, useEffect } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; import { API } from '@/api/API'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { useSelector } from 'react-redux'; import { RootState } from '@/store'; import { ArrowLeft, FileText, Upload, Loader2, Eye, CheckCircle2, Clock } from 'lucide-react'; import { WorkNotesPage } from './WorkNotesPage'; import { toast } from 'sonner'; import { DocumentPreviewModal } from '@/components/ui/DocumentPreviewModal'; import { formatDateTime } from '@/components/ui/utils'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; import { AlertTriangle, Info, ShieldCheck } from 'lucide-react'; import { Label } from '@/components/ui/label'; import { Textarea } from '@/components/ui/textarea'; export function FDDApplicationDetails() { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); const [application, setApplication] = useState(null); const [assignment, setAssignment] = useState(null); const [loading, setLoading] = useState(true); const [uploading, setUploading] = useState(false); const [selectedDocType, setSelectedDocType] = useState(''); const [activeTab, setActiveTab] = useState<'details' | 'worknotes'>('details'); const [isPreviewOpen, setIsPreviewOpen] = useState(false); const [selectedPreviewDoc, setSelectedPreviewDoc] = useState(null); const [showFinalizeModal, setShowFinalizeModal] = useState(false); const [showFlagModal, setShowFlagModal] = useState(false); const [fddAuditFindings, setFddAuditFindings] = useState(''); const user = useSelector((state: RootState) => state.auth.user); const isFddRole = user?.role === 'FDD'; useEffect(() => { if (id) fetchApplication(); }, [id]); const fetchApplication = async () => { setLoading(true); try { const [appRes, assRes]: any = await Promise.all([ API.getApplicationById(id!), API.getFddAssignment(id!) ]); if (appRes.data?.success) { setApplication(appRes.data.data); } if (assRes.data?.success) { setAssignment(assRes.data.data); } } catch (error) { console.error('Error fetching application:', error); const errorMsg = (error as any).response?.data?.message || 'Access Denied: Not authorized for FDD access'; toast.error(errorMsg); navigate('/fdd-dashboard'); } finally { setLoading(false); } }; const handleFileUpload = async (event: React.ChangeEvent) => { const file = event.target.files?.[0]; if (!file || !selectedDocType) { if (!selectedDocType) toast.error('Please select a document type first'); return; } setUploading(true); const formData = new FormData(); formData.append('file', file); formData.append('documentType', selectedDocType); formData.append('stage', 'FDD'); formData.append('applicationId', id!); formData.append('requestType', 'application'); try { const response: any = await API.uploadDocument(id!, formData); if (response.data?.success) { // Automatically link if it's the final report category if (selectedDocType === 'FDD Final Audit Report') { const docId = response.data.data?.id || response.data.id; await API.submitFddReport({ assignmentId: assignment?.id, applicationId: id, reportDocumentId: docId, findings: 'Final Audit Report submitted.', recommendation: 'REVIEW_PENDING' }); } toast.success(`${selectedDocType} uploaded successfully`); fetchApplication(); setSelectedDocType(''); } } catch (error) { toast.error('Failed to upload document'); } finally { setUploading(false); } }; const handlePreview = (doc: any) => { if (!doc || !doc.filePath) { toast.error('Document source file not found'); return; } setSelectedPreviewDoc({ fileName: doc.originalName || doc.fileName || 'Document', filePath: doc.filePath, documentType: doc.documentType, createdAt: doc.createdAt, mimeType: doc.mimeType }); setIsPreviewOpen(true); }; if (loading) { return (

Authenticating and loading secure data...

); } if (!application) return null; const isFDDStageActive = application.currentStage === 'FDD_VERIFICATION' || application.currentStage === 'FDD'; // Check if report is already submitted in assignment const isReportSubmitted = assignment?.status === 'Report Submitted'; // Check if the application has already passed the FDD stage const isCompleted = !isFDDStageActive && (application.overallStatus !== 'Active' || application.currentProgress >= 75) || isReportSubmitted; // Check if the application has not yet arrived at the FDD stage const isNotReachedYet = !isFDDStageActive && application.currentProgress < 70 && !isReportSubmitted; return (
{application?.statutoryStatus === 'Flagged' && (

APPLICATION FLAGGED BY YOU

Marked as non-responsive for follow-up by DD Team

)} {/* Action Bar */}
{isNotReachedYet ? (
Awaiting Previous Stages
) : !isCompleted ? ( <> {isFddRole && ( )} ) : (
Final Audit Report Submitted
)}
{/* Header Card */}
{application.applicantName.charAt(0)}

{application.applicantName}

{application.applicationId}
{application.city}, {application.state} {application.businessType || 'Dealership'}

Status

Financial Due Diligence

{/* Navigation Tabs */}
{activeTab === 'details' ? (
{/* Left Column: Financial Data & Uploads */}
{isCompleted ? 'Finalized Financial Reports' : isNotReachedYet ? 'Audit Workspace' : 'Financial Report Submission'} {isNotReachedYet && (

Stage Not Yet Active

This application is still being processed in previous documentation or interview stages. The FDD workspace will activate once the previous stages are approved.

Status: {application.status || 'Pending Review'}
)} {isCompleted && (

Verification Stage Completed

The FDD report has been submitted and the case is now locked for further audits.

)} {!isCompleted && !isNotReachedYet && (

{isFddRole ? 'Select and upload the due diligence report' : 'View Authorized Documents'}

{isFddRole ? 'PDF or JPG formats accepted (Max 10MB)' : 'You are in View-Only mode for this Audit'}

{isFddRole && (
{uploading ? (
Uploading...
) : ( <>
Browse & Upload
)}
)}
)} {/* List of Uploaded Documents */}

Submitted Documentation

{/* SECTION 1: APPLICANT DOCUMENTS */}

Applicant's KYC & Financials

{application.uploadedDocuments?.filter((d: any) => !d.uploader || d.uploader.roleCode !== 'FDD').map((doc: any, i: number) => (

{doc.originalName || doc.fileName}

APPLICANT

{doc.documentType} • {formatDateTime(doc.createdAt)} {doc.uploader?.fullName && ` • by ${doc.uploader.fullName}`}

))} {application.uploadedDocuments?.filter((d: any) => !d.uploader || d.uploader.roleCode !== 'FDD').length === 0 && (

No documents from applicant yet.

)}
{/* SECTION 2: MY SUBMISSIONS */}

My Uploaded Reports

{application.uploadedDocuments?.filter((d: any) => d.uploader?.roleCode === 'FDD').map((doc: any, i: number) => (

{doc.originalName || doc.fileName}

YOUR AUDIT REPORT

{doc.documentType} • {formatDateTime(doc.createdAt)} {doc.uploader?.fullName && ` • by ${doc.uploader.fullName}`}

))} {application.uploadedDocuments?.filter((d: any) => d.uploader?.roleCode === 'FDD').length === 0 && (

No audit reports uploaded yet.

)}
{/* Right Column: Applicant Meta & Guidelines */}
Applicant Profile

Target Location

{application.city}, {application.state}

Education

{application.education || 'N/A'}

Experience

{application.experienceYears || '0'} Years

Investment Cap

{application.investmentCapacity || 'N/A'}

Age

{application.age || 'N/A'}

Communication

{application.email}

{application.phone}

Instructions

  • Bank statements must cover 12 months.
  • GST discrepancies must be noted.
  • Verify property papers with originals.
) : (
setActiveTab('details')} requestId={id} requestType="application" />
)} setIsPreviewOpen(false)} document={selectedPreviewDoc} /> {/* Finalize Confirmation Modal */}
Submit Audit Report You are about to submit your final findings. This action will notify the Admin for review and approval.

Once submitted, you cannot edit the findings. Ensure all documents are uploaded.