import { useState, useEffect } from 'react'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; import { Textarea } from '@/components/ui/textarea'; import { useSelector } from 'react-redux'; import { RootState } from '@/store'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Avatar, AvatarFallback } from '@/components/ui/avatar'; import { ArrowLeft, ShieldCheck, CheckCircle, XCircle, FileText, User, Clock, Download, Eye, AlertCircle, MessageSquare, FileCheck, RotateCcw, History, Send } from 'lucide-react'; import { toast } from 'sonner'; import { onboardingService } from '@/services/onboarding.service'; import { worknoteService } from '@/services/worknote.service'; import { DocumentPreviewModal } from '@/components/ui/DocumentPreviewModal'; import { formatDateTime } from '@/components/ui/utils'; // Simple helper for class merging const cn = (...classes: any[]) => classes.filter(Boolean).join(' '); interface FinanceFddDetailPageProps { applicationId: string; onBack: () => void; } export function FinanceFddDetailPage({ applicationId, onBack }: FinanceFddDetailPageProps) { const { user: currentUser } = useSelector((state: RootState) => state.auth); const [application, setApplication] = useState(null); const [loading, setLoading] = useState(true); const [isSubmitting, setIsSubmitting] = useState(false); const [approvalRemark, setApprovalRemark] = useState(''); const [newNote, setNewNote] = useState(''); const [isNoteSubmitting, setIsNoteSubmitting] = useState(false); const [showPreviewModal, setShowPreviewModal] = useState(false); const [previewDoc, setPreviewDoc] = useState(null); useEffect(() => { fetchData(); }, [applicationId]); const fetchData = async () => { try { setLoading(true); const appData = await onboardingService.getApplicationById(applicationId); setApplication(appData); } catch (error) { console.error('Fetch error:', error); toast.error('Failed to load application data'); } finally { setLoading(false); } }; const handleDecision = async (decision: 'Approved' | 'Rejected') => { if (!approvalRemark.trim()) { toast.warning('Please enter a remark or justification'); return; } try { setIsSubmitting(true); // Map current status to next status for LOI stage let nextStatus = 'LOI Issued'; // Default if (application.status === 'LOI In Progress') { nextStatus = 'LOI Issued'; } const response = await onboardingService.submitStageDecision({ applicationId: application.id, stageCode: 'LOI_APPROVAL', decision, remarks: approvalRemark, nextStatus }); if (response.data?.statusUpdated) { toast.success(response.message || `Application ${decision.toLowerCase()} successfully`); } else { toast.info(response.message || 'Decision recorded. Waiting for other mandatory approvers.'); } setApprovalRemark(''); await fetchData(); } catch (error) { console.error('Decision error:', error); toast.error('Failed to process decision'); } finally { setIsSubmitting(false); } }; const handlePostNote = async () => { if (!newNote.trim()) return; try { setIsNoteSubmitting(true); await worknoteService.addWorknote({ requestId: application.id, requestType: 'application', noteText: newNote, noteType: 'fdd_query' }); setNewNote(''); toast.success('Work note posted successfully'); await fetchData(); } catch (error) { console.error('Add note error:', error); toast.error('Failed to post work note'); } finally { setIsNoteSubmitting(false); } }; if (loading) { return (
); } if (!application) { return
Application not found
; } const isFinance = currentUser?.role === 'Finance' || currentUser?.role === 'Finance Admin'; const isReadOnly = !isFinance; const assignments = application.fddAssignments || []; const workNotes = application.workNotes || []; const hasMadeDecision = application.stageApprovals?.some( (a: any) => a.stageCode === 'LOI_APPROVAL' && String(a.actorUserId) === String(currentUser?.id) ); const MANDATORY_FINANCIAL_DOCS = [ { type: 'Bank Statement', label: 'Bank Statements' }, { type: 'Income Tax Returns (ITR)', label: 'ITR (Last 3 Years)' }, { type: 'Credit Reports', label: 'CIBIL / Credit Reports' }, { type: 'Property Documents', label: 'Property Documents' }, { type: 'Business Valuation Report', label: 'Valuation Reports' } ]; const getDocByTypeName = (typeName: string) => { return application.uploadedDocuments?.find((d: any) => d.documentType === typeName); }; return (
{/* Header */}

FDD Audit Detail

Review findings and provide finance sign-off for LOI stage

APP ID: {application.applicationId || application.id} {application.status}
Audit Review Work Notes {workNotes.length > 0 && {workNotes.length}} Audit Trail
{/* Main Content Area */}
{/* Applicant Summary Card */} Applicant Summary

{application.name || application.applicantName}

{application.city || application.preferredLocation}, {application.state}

{application.email} {application.phone}

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

{/* Financial Document Checklist Card */}
Financial Artefacts Checklist
Mandatory for FDD Sign-off
{MANDATORY_FINANCIAL_DOCS.map((docType) => { const doc = getDocByTypeName(docType.type); return (
{doc ? : }

{docType.label}

{doc ? `Uploaded: ${formatDateTime(doc.createdAt)}` : 'Missing in Documentation'}

{doc && (
)}
); })}
{/* Audit Reports Section */}

Audit Findings & Reports

{assignments.length} Reports Found
{assignments.length === 0 ? (

No Audit Reports Available

The FDD team has not yet uploaded the audit reports for this application.

) : (
{assignments.map((assignment: any, idx: number) => (

FDD Audit Assignment

Status: {assignment.status}

{assignment.status}
{!assignment.reports || assignment.reports.length === 0 ? (

Waiting for agency report submission...

) : (
{assignment.reports.map((report: any, reportIdx: number) => (
{report.recommendation?.toUpperCase()} SIGNAL

"{report.findings || 'No detail findings provided.'}"

{report.reportDocument ? (

{report.reportDocument.fileName}

SUBMITTED {formatDateTime(report.createdAt)}

) : (
No report file attached
)}
{report.verifiedAt ? (
Audited & Verified
) : (
Pending Verification
)}
))}
)}
))}
)}
{/* Action Sidebar */}
Finance Action