import {
  ArrowLeft,
  Check,
  FileText,
  Send,
  Clock,
  Users,
  FileCheck,
  MessageSquare,
  CheckCircle2,
  AlertCircle,
  Loader2,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Plus, Pencil, Trash2, Building2, Landmark } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Progress } from "@/components/ui/progress";
import { useState, useEffect } from "react";
import { toast } from "sonner";

import { API } from "@/api/API";
import { useNavigate } from "react-router-dom";
import { DocumentPreviewModal } from "@/components/ui/DocumentPreviewModal";
import { formatDateTime, formatDateOnly } from "@/lib/dateUtils";
import { BankDetailsModal } from "@/features/onboarding/components/BankDetailsModal";

interface FnFDetailsProps {
  fnfId: string;
  onBack: () => void;
  currentUser: any;
}

const ALL_DEPARTMENTS = [
  'Warranty Department', 'Accessories Department', 'Sales Department', 'RTO Department',
  'Service Department', 'Parts Department', 'Finance Department', 'Insurance Department',
  'Inventory Department', 'Marketing Department', 'HR Department', 'IT Department',
  'Legal Department', 'Quality Department', 'Logistics Department', 'Customer Relations Department'
];

const DEPARTMENT_CLAIM_PREFIX = "[DEPARTMENT_CLAIM]";
const FINANCE_VALIDATED_PREFIX = "[FINANCE_VALIDATED]";

export function FnFDetails({ fnfId, onBack, currentUser }: FnFDetailsProps) {
  const navigate = useNavigate();
  const [fnfCase, setFnfCase] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('details');
  const [sendStakeholdersDialog, setSendStakeholdersDialog] = useState(false);
  const [previewDocument, setPreviewDocument] = useState<any>(null);
  const [auditLogs, setAuditLogs] = useState<any[]>([]);
  const [bankDetails, setBankDetails] = useState<any[]>([]);
  const [isBankModalOpen, setIsBankModalOpen] = useState(false);
  const [editingBank, setEditingBank] = useState<any>(null);
  const [isSubmittingBank, setIsSubmittingBank] = useState(false);
  const [showClearanceDialog, setShowClearanceDialog] = useState(false);
  const [selectedDept, setSelectedDept] = useState<any>(null);
  const [isUpdatingClearance, setIsUpdatingClearance] = useState(false);
  const [clearanceForm, setClearanceForm] = useState({
    remarks: "",
    amount: 0,
    type: "Receivable",
  });
  const [clearanceFile, setClearanceFile] = useState<File | null>(null);


  useEffect(() => {
    fetchFnFDetails();
    fetchAuditLogs();
  }, [fnfId]);

  const normalizeDepartment = (name: string) => {
    if (!name) return name;
    let inputName = name.trim();

    // Exact match first
    const exactMatch = ALL_DEPARTMENTS.find(d => d.toLowerCase() === inputName.toLowerCase());
    if (exactMatch) return exactMatch;

    // Smart mapping for shorthands
    const mapping: Record<string, string> = {
      'sales': 'Sales Department',
      'service': 'Service Department',
      'spares': 'Parts Department',
      'parts': 'Parts Department',
      'spares / parts': 'Parts Department',
      'finance': 'Finance Department',
      'accounts': 'Finance Department',
      'warranty': 'Warranty Department',
      'marketing': 'Marketing Department',
      'hr': 'HR Department',
      'it': 'IT Department',
      'legal': 'Legal Department',
      'logistics': 'Logistics Department',
      'quality': 'Quality Department',
      'fdd': 'Finance Department',
      'apparel': 'Accessories Department',
      'accessories': 'Accessories Department',
      'dms': 'IT Department',
      'rto': 'Admin Department',
      'admin': 'Admin Department',
      'admin / dd-admin': 'Admin Department'
    };

    const mapped = mapping[inputName.toLowerCase().replace(' department', '')];
    if (mapped) return mapped;

    return name;
  };

  const isDepartmentClaimLine = (description?: string, sourceType?: string) =>
    sourceType === "DepartmentClaim" ||
    (typeof description === "string" &&
      (description.startsWith(DEPARTMENT_CLAIM_PREFIX) || description.includes('Clearance:')));

  /** Backend seeds FinanceValidated mirrors on fetch; use claims when present to avoid double-counting */
  const isAutoSeededDeptMirror = (li: any) =>
    li?.sourceType === "FinanceValidated" &&
    typeof li?.description === "string" &&
    li.description.includes("Auto-seeded from department claim");

  const isFinanceValidatedLine = (description?: string, sourceType?: string) =>
    sourceType === "FinanceValidated" ||
    (typeof description === "string" && description.startsWith(FINANCE_VALIDATED_PREFIX));

  const getFriendlyActionName = (action: string) => {
    if (!action) return 'Action';
    const mapping: Record<string, string> = {
      'ADD_LINE_ITEM': 'Line Item Added',
      'UPDATE_LINE_ITEM': 'Line Item Updated',
      'REMOVE_LINE_ITEM': 'Line Item Removed',
      'UPDATE_CLEARANCE': 'Clearance Status Updated',
      'SETTLE_CASE': 'Settlement Finalized',
      'FNF_UPDATED': 'F&F Case Updated'
    };
    return mapping[action] || action.split('_').map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(' ');
  };

  const fetchFnFDetails = async (showLoader: boolean = true) => {
    try {
      if (showLoader) setLoading(true);
      const response = await API.getFnFSettlementById(fnfId);
      const data = response.data as any;
      if (data.success) {
        const s = data.fnf;
        // Map backend data to UI format
        const allLineItems = (s.lineItems || []).filter((li: any) => li.isActive !== false);
        const hasFinanceValidatedLines = allLineItems.some((li: any) => isFinanceValidatedLine(li.description, li.sourceType));
        const calculationLineItems = hasFinanceValidatedLines
          ? allLineItems.filter((li: any) => isFinanceValidatedLine(li.description, li.sourceType))
          : allLineItems.filter((li: any) => !isDepartmentClaimLine(li.description, li.sourceType));

        const mappedCase: any = {
          id: s.id,
          caseNumber: s.settlementId || s.resignation?.resignationId || s.terminationRequest?.requestId || s.id.substring(0, 8),
          status: s.status,
          requestType: s.resignationId ? "Resignation" : "Termination",
          dealerName: s.outlet?.dealer?.fullName || s.dealer?.fullName || "N/A",
          dealerCode: s.outlet?.code || s.dealer?.dealerCode?.dealerCode || "N/A",
          dealershipName: s.outlet?.name || s.dealer?.businessName || "N/A",
          location: s.outlet?.city || s.outlet?.location || "N/A",
          originalRequestId:
            s.resignation?.resignationId || s.terminationRequest?.requestId || s.terminationRequest?.id || "N/A",
          submittedOn: formatDateTime(s.createdAt),
          lastOperationalDateSales: s.resignation?.lastOperationalDateSales || s.terminationRequest?.proposedLwd
            ? formatDateOnly(s.resignation?.lastOperationalDateSales || s.terminationRequest?.proposedLwd)
            : "N/A",
          lastOperationalDateServices: s.resignation?.lastOperationalDateServices || s.terminationRequest?.proposedLwd
            ? formatDateOnly(s.resignation?.lastOperationalDateServices || s.terminationRequest?.proposedLwd)
            : "N/A",
          typeOfClosure: s.resignationId ? "Voluntary" : "Involuntary",
          gst: s.outlet?.dealer?.dealerProfile?.gstNumber || s.dealer?.gstNumber || "N/A",
          pan: s.outlet?.dealer?.dealerProfile?.panNumber || s.dealer?.panNumber || "N/A",
          salesCode: s.dealer?.dealerCode?.salesCode || s.outlet?.dealer?.dealerProfile?.dealerCode?.salesCode || 'N/A',
          serviceCode: s.dealer?.dealerCode?.serviceCode || s.outlet?.dealer?.dealerProfile?.dealerCode?.serviceCode || 'N/A',
          gearCode: s.dealer?.dealerCode?.gearCode || s.outlet?.dealer?.dealerProfile?.dealerCode?.gearCode || 'N/A',
          gmaCode: s.dealer?.dealerCode?.gmaCode || s.outlet?.dealer?.dealerProfile?.dealerCode?.gmaCode || 'N/A',
          financeReportStatus:
            s.status === "Finance Approval"
              ? "In Progress"
              : s.status === "Completed"
                ? "Completed"
                : "Pending",
          totalPayableAmount: calculationLineItems.filter((li: any) => li.itemType === 'Payable').reduce((sum: number, li: any) => sum + (parseFloat(li.amount) || 0), 0),
          totalRecoveryAmount: calculationLineItems.filter((li: any) => li.itemType === 'Receivable' || li.itemType === 'Recovery').reduce((sum: number, li: any) => sum + (parseFloat(li.amount) || 0), 0),
          totalDeductions: calculationLineItems.filter((li: any) => li.itemType === 'Deduction').reduce((sum: number, li: any) => sum + (parseFloat(li.amount) || 0), 0),
          allLineItems,
          netAmount: 0,
          departmentResponses: [] as any[]
        };

        mappedCase.netAmount = mappedCase.totalPayableAmount - mappedCase.totalRecoveryAmount - mappedCase.totalDeductions;

        mappedCase.departmentResponses = [
          'Warranty Department', 'Accessories Department', 'Sales Department', 'RTO Department',
          'Service Department', 'Parts Department', 'Finance Department', 'Insurance Department',
          'Inventory Department', 'Marketing Department', 'HR Department', 'IT Department',
          'Legal Department', 'Quality Department', 'Logistics Department', 'Customer Relations Department'
        ].map((deptName: string) => {
          const c = (s.clearances || []).find(
            (clearance: any) => normalizeDepartment(clearance.department) === deptName,
          );
          const claimLines = allLineItems.filter(
            (li: any) =>
              normalizeDepartment(li.department) === deptName &&
              isDepartmentClaimLine(li.description, li.sourceType),
          );
          const seededMirrorLines = allLineItems.filter(
            (li: any) =>
              normalizeDepartment(li.department) === deptName && isAutoSeededDeptMirror(li),
          );
          const relatedItems = claimLines.length > 0 ? claimLines : seededMirrorLines;

          // Calculate departmental net
          let deptPayables = 0;
          let deptRecoveries = 0;
          relatedItems.forEach((li: any) => {
            const amt = Math.abs(parseFloat(li.amount) || 0);
            if (li.itemType === 'Payable') deptPayables += amt;
            else deptRecoveries += amt; // Receivable, Recovery, Deduction
          });

          const netAmount = deptPayables - deptRecoveries;
          const hasDuesAmount = Math.abs(netAmount) > 0;
          const rawStatus = c?.status || "Pending";
          const normalizedStatus = hasDuesAmount
            ? "Dues Pending"
            : (rawStatus === "Cleared" ? "NOC Submitted" : rawStatus);

          const duesFlow =
            netAmount > 0 ? ("payable" as const)
              : netAmount < 0 ? ("recovery" as const)
                : null;

          return {
            id: c?.id || `dept-${deptName}`,
            clearanceId: c?.id || null,
            departmentName: deptName,
            status: normalizedStatus,
            duesFlow,
            amountType: netAmount > 0 ? "Payable to dealer" : netAmount < 0 ? "Receivable from dealer" : null,
            amount: Math.abs(netAmount),
            submittedDate: c?.clearedAt ? formatDateTime(c.clearedAt) : "-",
            remarks: c?.remarks || "-",
            supportingDocument: c?.supportingDocument || null,
          };
        });

        // Add documents and other fields
        const finalMapped = {
          ...mappedCase,
          documents: [
            ...(s.resignation?.uploadedDocuments || []).map((doc: any) => ({
              id: `res-${doc.id}`,
              name: doc.fileName,
              type: "Resignation",
              uploadDate: formatDateTime(doc.createdAt),
              status: "Verified",
              url: doc.filePath,
            })),
            ...(s.clearances || [])
              .filter((c: any) => c.supportingDocument)
              .map((c: any) => ({
                id: `clr-${c.id}`,
                name: c.supportingDocument.split("/").pop(),
                type: `${c.department} Proof`,
                uploadDate: formatDateTime(c.clearedAt),
                status: "Attached",
                url: c.supportingDocument,
              })),
            ...(s.settlementDocs || []).map((doc: any) => ({
              id: `set-${doc.id}`,
              name: doc.fileName,
              type: "Settlement Proof",
              uploadDate: formatDateTime(doc.createdAt),
              status: "Finance",
              url: doc.filePath,
            })),
          ],
          participants: s.participants || []
        };
        setFnfCase(finalMapped);

        // Sync bank details from the pre-fetched data
        const preFetchedBankDetails = s.bankDetails || s.dealer?.bankDetails || s.outlet?.dealer?.dealerProfile?.bankDetails;
        if (preFetchedBankDetails && preFetchedBankDetails.length > 0) {
          setBankDetails(preFetchedBankDetails);
        } else if (s.outlet?.dealer?.id || s.dealerId) {
          fetchBankDetails(s.outlet?.dealer?.id || s.dealerId);
        }
      }
    } catch (error) {
      console.error("Fetch F&F details error:", error);
      toast.error("Failed to fetch settlement details");
    } finally {
      if (showLoader) setLoading(false);
    }
  };

  const fetchAuditLogs = async () => {
    try {
      const response = await API.getAuditLogs("fnf", fnfId);
      const data = response.data as any;
      if (data.success) {
        setAuditLogs(data.data || []);
      }
    } catch (error) {
      console.error("Fetch audit logs error:", error);
    }
  };

  const fetchBankDetails = async (dealerId: string) => {
    try {
      const response = await API.getDealerBankDetails(dealerId);
      const data = response.data as any;
      if (data.success) {
        setBankDetails(data.bankDetails || []);
      }
    } catch (error) {
      console.error("Fetch bank details error:", error);
    }
  };

  const handleUpsertBank = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const data = Object.fromEntries(formData.entries());

    try {
      setIsSubmittingBank(true);
      const dealerId = fnfCase?.outlet?.dealer?.id || fnfCase?.dealerId;
      if (!dealerId) {
        toast.error("Dealer information missing");
        return;
      }

      const response = await API.saveBankDetail(dealerId, {
        ...data,
        id: editingBank?.id,
        isPrimary: formData.get("isPrimary") === "on",
      }) as any;

      if (response.data.success) {
        toast.success("Bank details saved successfully");
        fetchBankDetails(dealerId);
        setIsBankModalOpen(false);
        setEditingBank(null);
      }
    } catch (error) {
      toast.error("Failed to save bank details");
    } finally {
      setIsSubmittingBank(false);
    }
  };

  const handleDeleteBank = async (id: string) => {
    if (!confirm("Are you sure you want to delete this bank account?")) return;
    try {
      const response = await API.deleteBankDetail(id) as any;
      if (response.data.success) {
        toast.success("Bank detail deleted");
        const dealerId = fnfCase?.outlet?.dealer?.id || fnfCase?.dealerId;
        if (dealerId) {
          fetchBankDetails(dealerId);
        }
      }
    } catch (error) {
      toast.error("Failed to delete bank detail");
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center p-12">
        <Loader2 className="w-8 h-8 animate-spin text-amber-600" />
      </div>
    );
  }

  if (!fnfCase) {
    return (
      <div className="text-center py-12">
        <p className="text-slate-600">Case not found</p>
        <Button onClick={onBack} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  // Calculate age in days from F&F submission date
  const calculateAge = (startDate: string) => {
    const start = new Date(startDate);
    const today = new Date(); // Use real current date
    const diffTime = Math.abs(today.getTime() - start.getTime());
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  };

  const fnfAge = calculateAge(fnfCase.submittedOn);

  const canRespondToDepartment = (dept: any) => {
    if (!fnfCase || !dept) return false;
    const role = String(currentUser?.role || "").toLowerCase();
    if (!role) return false;

    // 1. If any user (including Admin) has already responded, hide the button to prevent double-submission
    const hasAlreadyResponded = dept.status !== "Pending";
    if (hasAlreadyResponded) return false;

    // 2. Case Level Closure: Finance Approval or Completed states lock the window
    const isWindowClosed = ["Finance Approval", "Completed"].includes(fnfCase.status);
    const hasOverridePower = role.includes("super admin") || role.includes("finance") || role.includes("dd admin");

    if (isWindowClosed && !hasOverridePower) return false;

    // 3. Normal Role Check
    if (hasOverridePower) return true;

    const deptKeyword = dept.departmentName.replace(" Department", "").toLowerCase();
    return role.includes(deptKeyword);
  };

  const canAnyDepartmentRespond = (fnfCase?.departmentResponses || []).some((dept: any) =>
    canRespondToDepartment(dept),
  );

  const handleUpdateClearance = async () => {
    if (!selectedDept?.clearanceId || !fnfId) {
      toast.error("Clearance record not available for this department");
      return;
    }

    try {
      setIsUpdatingClearance(true);
      const formData = new FormData();
      const derivedStatus = Number(clearanceForm.amount) > 0 ? "Dues Pending" : "NOC Submitted";
      formData.append("status", derivedStatus);
      formData.append("remarks", clearanceForm.remarks);
      formData.append("amount", String(clearanceForm.amount));
      formData.append("type", clearanceForm.type);
      if (clearanceFile) formData.append("file", clearanceFile);

      const response = await API.updateFnFClearance(fnfId, selectedDept.clearanceId, formData) as any;

      if (!response.ok) {
        toast.error(response.data?.message || "Failed to update department clearance");
        setIsUpdatingClearance(false);
        return;
      }

      toast.success(`Clearance updated for ${selectedDept.departmentName}`);
      setShowClearanceDialog(false);
      setClearanceFile(null);
      setActiveTab('departments');
      fetchFnFDetails(false);
    } catch (error) {
      console.error("Update clearance error:", error);
      toast.error("Failed to update department clearance");
    } finally {
      setIsUpdatingClearance(false);
    }
  };

  const handleSendToStakeholders = () => {
    toast.success("Notifications sent to all 16 departments");
    setSendStakeholdersDialog(false);
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "New":
        return "bg-amber-100 text-blue-700 border-blue-300";
      case "In Progress":
        return "bg-yellow-100 text-yellow-700 border-yellow-300";
      case "Under Review":
        return "bg-orange-100 text-orange-700 border-orange-300";
      case "Completed":
        return "bg-green-100 text-green-700 border-green-300";
      default:
        return "bg-slate-100 text-slate-700 border-slate-300";
    }
  };

  const getDepartmentStatusColor = (status: string) => {
    switch (status) {
      case "NOC Submitted":
        return "bg-green-100 text-green-700 border-green-300";
      case "Dues Pending":
        return "bg-red-100 text-red-700 border-red-300";
      case "Pending":
        return "bg-slate-100 text-slate-700 border-slate-300";
      default:
        return "bg-slate-100 text-slate-700 border-slate-300";
    }
  };

  const responsesReceived = fnfCase.departmentResponses.filter(
    (d: any) => d.status !== "Pending",
  ).length;
  const totalDepartments = fnfCase.departmentResponses.length;
  const progressPercentage = (responsesReceived / totalDepartments) * 100;
  const departmentReconciliation = ALL_DEPARTMENTS.map((deptName) => {
    const claim = (fnfCase.departmentResponses || []).find((d: any) => d.departmentName === deptName);
    const claimAmount = Number(claim?.amount) || 0;
    const claimType = claim?.amountType || '-';
    const deptLines = (fnfCase.allLineItems || []).filter((li: any) => normalizeDepartment(li.department) === deptName);
    const payable = deptLines
      .filter((li: any) => li.sourceType === 'FinanceValidated' && li.itemType === 'Payable')
      .reduce((sum: number, li: any) => sum + Math.abs(parseFloat(li.amount) || 0), 0);
    const receivable = deptLines
      .filter((li: any) => li.sourceType === 'FinanceValidated' && (li.itemType === 'Receivable' || li.itemType === 'Recovery'))
      .reduce((sum: number, li: any) => sum + Math.abs(parseFloat(li.amount) || 0), 0);
    const deduction = deptLines
      .filter((li: any) => li.sourceType === 'FinanceValidated' && li.itemType === 'Deduction')
      .reduce((sum: number, li: any) => sum + Math.abs(parseFloat(li.amount) || 0), 0);
    const validatedNet = payable - receivable - deduction;
    const validatedAmount = Math.abs(validatedNet);
    const validatedType = validatedNet > 0 ? 'Payable' : validatedNet < 0 ? 'Receivable' : '-';
    return {
      department: deptName,
      claimAmount,
      claimType,
      validatedAmount,
      validatedType,
      variance: validatedAmount - claimAmount
    };
  });

  return (
    <div className="space-y-6">
      {/* Net Balance Banner */}
      <Card className={`border-none shadow-md bg-gradient-to-r ${(fnfCase.totalRecoveryAmount || 0) > (fnfCase.totalPayableAmount || 0)
          ? "from-red-600 to-red-500"
          : "from-green-600 to-green-500"
        } text-white`}>
        <CardContent className="p-6 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className="p-3 bg-white/20 rounded-full">
              <Landmark className="w-6 h-6" />
            </div>
            <div>
              <p className="text-white/80 text-sm font-medium">Net Settlement Balance</p>
              <h2 className="text-3xl font-bold">
                ₹{Math.abs(fnfCase.netAmount || 0).toLocaleString()}
              </h2>
            </div>
          </div>
          <div className="text-right">
            <Badge className="bg-white/20 hover:bg-white/30 text-white border-none px-4 py-1 mb-2">
              {(fnfCase.totalRecoveryAmount || 0) > (fnfCase.totalPayableAmount || 0)
                ? "Receivable from Dealer"
                : "Payable to Dealer"}
            </Badge>
            <p className="text-xs text-white/70">
              {fnfCase.status === 'Completed' ? 'Settlement Finalized' : 'Draft Calculation'}
            </p>
          </div>
        </CardContent>
      </Card>

      {/* 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-2xl">{fnfCase.caseNumber}</h1>
            <p className="text-slate-600">{fnfCase.dealerName}</p>
          </div>
          <Badge className={getStatusColor(fnfCase.status)}>
            {fnfCase.status}
          </Badge>
          <Badge
            className={
              fnfCase.requestType === "Resignation"
                ? "bg-amber-100 text-amber-700 border-amber-300"
                : "bg-red-100 text-red-700 border-red-300"
            }
          >
            {fnfCase.requestType}
          </Badge>
        </div>
        {/* Action Buttons */}
        <div className="flex items-center gap-3">
          <Button
            variant="outline"
            onClick={() =>
              navigate(`/worknotes/fnf/${fnfId}`, {
                state: {
                  applicationName: fnfCase.dealerName || "F&F Settlement",
                  registrationNumber: fnfCase.caseNumber || "",
                  participants: fnfCase.participants || [],
                },
              })
            }
          >
            <MessageSquare className="w-4 h-4 mr-2" />
            View Work Notes
          </Button>

          {/* {canSendToStakeholders && fnfCase.status === "New" && (
            <Button
              className="bg-amber-600 hover:bg-blue-700"
              onClick={() => setSendStakeholdersDialog(true)}
            >
              <Send className="w-4 h-4 mr-2" />
              Send to Stakeholders
            </Button>
          )} */}
        </div>
      </div>

      {/* Progress Summary */}
      <Card>
        <CardHeader>
          <CardTitle>Overall Progress</CardTitle>
          <CardDescription>
            Department responses: {responsesReceived} / {totalDepartments}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Progress value={progressPercentage} className="h-3" />
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6">
            <div>
              <p className="text-slate-600 text-sm">NOC Submitted</p>
              <p className="text-2xl text-green-600">
                {
                  fnfCase.departmentResponses.filter(
                    (d: any) => d.status === "NOC Submitted",
                  ).length
                }
              </p>
            </div>
            <div>
              <p className="text-slate-600 text-sm">Dues Pending</p>
              <p className="text-2xl text-red-600">
                {
                  fnfCase.departmentResponses.filter(
                    (d: any) => d.status === "Dues Pending",
                  ).length
                }
              </p>
            </div>
            <div>
              <p className="text-slate-600 text-sm">Pending</p>
              <p className="text-2xl text-slate-600">
                {
                  fnfCase.departmentResponses.filter(
                    (d: any) => d.status === "Pending",
                  ).length
                }
              </p>
            </div>
            <div>
              <p className="text-slate-600 text-sm">Finance Status</p>
              <p className="text-lg">{fnfCase.financeReportStatus}</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList>
          <TabsTrigger value="progress">Progress</TabsTrigger>
          <TabsTrigger value="details">Case Details</TabsTrigger>
          <TabsTrigger value="departments">Department Responses</TabsTrigger>
          <TabsTrigger value="financial">Financial Summary</TabsTrigger>
          <TabsTrigger value="documents">Documents</TabsTrigger>
          <TabsTrigger value="bank">Bank Details</TabsTrigger>
          <TabsTrigger value="audit">Audit Trail</TabsTrigger>
        </TabsList>

        {/* Progress Tab */}
        <TabsContent value="progress">
          <Card>
            <CardHeader>
              <CardTitle>F&F Settlement Progress</CardTitle>
              <CardDescription>
                Track the complete journey from initiation to completion
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="relative">
                {/* Progress Steps */}
                <div className="space-y-8">
                  {/* Step 1: F&F Initiated */}
                  <div className="flex gap-4 items-start">
                    <div className="flex shrink-0 flex-col items-center">
                      <div className="size-12 shrink-0 aspect-square rounded-full bg-green-100 border-2 border-green-600 flex items-center justify-center">
                        <Check className="w-6 h-6 text-green-600" />
                      </div>
                      <div className="w-0.5 h-full bg-green-300 mt-2"></div>
                    </div>
                    <div className="flex-1 pb-8">
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-3">
                          <h3 className="text-slate-900">F&F Initiated</h3>
                          <Badge className="bg-green-600">Completed</Badge>
                        </div>
                        <span className="text-sm text-slate-600">
                          {fnfCase.submittedOn}
                        </span>
                      </div>
                      <p className="text-slate-600 text-sm mb-3">
                        Full & Final settlement process has been initiated. Case
                        created and basic information collected.
                      </p>
                      <Card className="bg-green-50 border-green-200">
                        <CardContent className="p-4">
                          <div className="grid grid-cols-2 gap-4 text-sm">
                            <div>
                              <p className="text-slate-600">Case Number</p>
                              <p className="text-slate-900">
                                {fnfCase.caseNumber}
                              </p>
                            </div>
                            <div>
                              <p className="text-slate-600">Request Type</p>
                              <p className="text-slate-900">
                                {fnfCase.requestType}
                              </p>
                            </div>
                            <div>
                              <p className="text-slate-600">Dealer</p>
                              <p className="text-slate-900">
                                {fnfCase.dealerName}
                              </p>
                            </div>
                            <div>
                              <p className="text-slate-600">Location</p>
                              <p className="text-slate-900">
                                {fnfCase.location}
                              </p>
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    </div>
                  </div>

                  {/* Step 2: Department Responses Received */}
                  <div className="flex gap-4 items-start">
                    <div className="flex shrink-0 flex-col items-center">
                      <div
                        className={`size-12 shrink-0 aspect-square rounded-full flex items-center justify-center border-2 ${responsesReceived === totalDepartments ||
                            ["Finance Approval", "Completed"].includes(
                              fnfCase.status,
                            )
                            ? "bg-green-100 border-green-600"
                            : responsesReceived > 0
                              ? "bg-amber-100 border-amber-600"
                              : "bg-slate-100 border-slate-300"
                          }`}
                      >
                        {responsesReceived === totalDepartments ||
                          ["Finance Approval", "Completed"].includes(
                            fnfCase.status,
                          ) ? (
                          <Check className="w-6 h-6 text-green-600" />
                        ) : responsesReceived > 0 ? (
                          <Users className="w-6 h-6 text-amber-600" />
                        ) : (
                          <Clock className="w-6 h-6 text-slate-400" />
                        )}
                      </div>
                      <div
                        className={`w-0.5 h-full mt-2 ${responsesReceived === totalDepartments ||
                            ["Finance Approval", "Completed"].includes(
                              fnfCase.status,
                            )
                            ? "bg-green-300"
                            : "bg-slate-200"
                          }`}
                      ></div>
                    </div>
                    <div className="flex-1 pb-8">
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-3">
                          <h3 className="text-slate-900">
                            Department Responses Received
                          </h3>
                          <Badge
                            className={
                              responsesReceived === totalDepartments ||
                                ["Finance Approval", "Completed"].includes(
                                  fnfCase.status,
                                )
                                ? "bg-green-600"
                                : responsesReceived > 0
                                  ? "bg-amber-600"
                                  : "bg-slate-400"
                            }
                          >
                            {responsesReceived === totalDepartments ||
                              ["Finance Approval", "Completed"].includes(
                                fnfCase.status,
                              )
                              ? "Completed"
                              : responsesReceived > 0
                                ? "In Progress"
                                : "Pending"}
                          </Badge>
                        </div>
                      </div>
                      <p className="text-slate-600 text-sm mb-3">
                        All stakeholder departments submit their NOC or dues
                        information.
                        {responsesReceived > 0 &&
                          ` (${responsesReceived}/${totalDepartments} responses received)`}
                      </p>
                      {responsesReceived > 0 && (
                        <Card
                          className={
                            responsesReceived === totalDepartments ||
                              ["Finance Approval", "Completed"].includes(
                                fnfCase.status,
                              )
                              ? "bg-green-50 border-green-200"
                              : "bg-blue-50 border-amber-200"
                          }
                        >
                          <CardContent className="p-4">
                            <div className="space-y-3">
                              <div className="flex items-center justify-between">
                                <span className="text-sm text-slate-600">
                                  Progress
                                </span>
                                <span className="text-sm">
                                  {responsesReceived} / {totalDepartments}{" "}
                                  departments
                                </span>
                              </div>
                              <Progress
                                value={progressPercentage}
                                className="h-2"
                              />
                              <div className="grid grid-cols-3 gap-3 text-sm">
                                <div className="text-center p-2 bg-green-100 rounded">
                                  <p className="text-green-700">
                                    NOC Submitted
                                  </p>
                                  <p className="text-green-900">
                                    {
                                      fnfCase.departmentResponses.filter(
                                        (d: any) =>
                                          d.status === "NOC Submitted",
                                      ).length
                                    }
                                  </p>
                                </div>
                                <div className="text-center p-2 bg-red-100 rounded">
                                  <p className="text-red-700">Dues Pending</p>
                                  <p className="text-red-900">
                                    {
                                      fnfCase.departmentResponses.filter(
                                        (d: any) => d.status === "Dues Pending",
                                      ).length
                                    }
                                  </p>
                                </div>
                                <div className="text-center p-2 bg-slate-100 rounded">
                                  <p className="text-slate-700">Pending</p>
                                  <p className="text-slate-900">
                                    {
                                      fnfCase.departmentResponses.filter(
                                        (d: any) => d.status === "Pending",
                                      ).length
                                    }
                                  </p>
                                </div>
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      )}
                    </div>
                  </div>

                  {/* Step 3: Finance Final Summary */}
                  <div className="flex gap-4 items-start">
                    <div className="flex shrink-0 flex-col items-center">
                      <div
                        className={`size-12 shrink-0 aspect-square rounded-full flex items-center justify-center border-2 ${fnfCase.status === "Completed"
                            ? "bg-green-100 border-green-600"
                            : fnfCase.status === "Finance Approval"
                              ? "bg-amber-100 border-amber-600"
                              : "bg-slate-100 border-slate-300"
                          }`}
                      >
                        {fnfCase.status === "Completed" ? (
                          <Check className="w-6 h-6 text-green-600" />
                        ) : fnfCase.status === "Finance Approval" ? (
                          <FileCheck className="w-6 h-6 text-amber-600" />
                        ) : (
                          <Clock className="w-6 h-6 text-slate-400" />
                        )}
                      </div>
                      <div
                        className={`w-0.5 h-full mt-2 ${fnfCase.status === "Completed"
                            ? "bg-green-300"
                            : "bg-slate-200"
                          }`}
                      ></div>
                    </div>
                    <div className="flex-1 pb-8">
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-3">
                          <h3 className="text-slate-900">
                            Finance Final Summary
                          </h3>
                          <Badge
                            className={
                              fnfCase.status === "Completed"
                                ? "bg-green-600"
                                : fnfCase.status === "Finance Approval"
                                  ? "bg-amber-600"
                                  : "bg-slate-400"
                            }
                          >
                            {fnfCase.status === "Completed"
                              ? "Completed"
                              : fnfCase.status === "Finance Approval"
                                ? "In Progress"
                                : "Pending"}
                          </Badge>
                        </div>
                      </div>
                      <p className="text-slate-600 text-sm mb-3">
                        Finance department consolidates all department responses
                        and prepares final settlement summary with total payable
                        and recovery amounts.
                      </p>
                      {["Finance Approval", "Completed"].includes(
                        fnfCase.status,
                      ) && (
                          <Card
                            className={
                              fnfCase.status === "Completed"
                                ? "bg-green-50 border-green-200"
                                : "bg-blue-50 border-amber-200"
                            }
                          >
                            <CardContent className="p-4">
                              <div className="grid grid-cols-3 gap-4">
                                <div className="text-center p-3 bg-green-100 rounded-lg">
                                  <p className="text-xs text-green-700 mb-1">
                                    Payable Amount
                                  </p>
                                  <p className="text-green-900">
                                    ₹
                                    {fnfCase.totalPayableAmount?.toLocaleString() ||
                                      "0"}
                                  </p>
                                </div>
                                <div className="text-center p-3 bg-red-100 rounded-lg">
                                  <p className="text-xs text-red-700 mb-1">
                                    Receivable amount
                                  </p>
                                  <p className="text-red-900">
                                    ₹
                                    {fnfCase.totalRecoveryAmount?.toLocaleString() ||
                                      "0"}
                                  </p>
                                </div>
                                <div className="text-center p-3 bg-amber-100 rounded-lg">
                                  <p className="text-xs text-blue-700 mb-1">
                                    Net Amount
                                  </p>
                                  <p
                                    className={
                                      (fnfCase.totalRecoveryAmount || 0) >
                                        (fnfCase.totalPayableAmount || 0)
                                        ? "text-red-900"
                                        : "text-green-900"
                                    }
                                  >
                                    ₹
                                    {Math.abs(
                                      (fnfCase.totalRecoveryAmount || 0) -
                                      (fnfCase.totalPayableAmount || 0),
                                    ).toLocaleString()}
                                  </p>
                                </div>
                              </div>
                            </CardContent>
                          </Card>
                        )}
                    </div>
                  </div>

                  {/* Step 4: Financial Discussion with Dealer */}
                  <div className="flex gap-4 items-start">
                    <div className="flex shrink-0 flex-col items-center">
                      <div
                        className={`size-12 shrink-0 aspect-square rounded-full flex items-center justify-center border-2 ${fnfCase.status === "Completed"
                            ? "bg-green-100 border-green-600"
                            : fnfCase.status === "Finance Approval"
                              ? "bg-amber-100 border-amber-600"
                              : "bg-slate-100 border-slate-300"
                          }`}
                      >
                        {fnfCase.status === "Completed" ? (
                          <Check className="w-6 h-6 text-green-600" />
                        ) : fnfCase.status === "Finance Approval" ? (
                          <MessageSquare className="w-6 h-6 text-amber-600" />
                        ) : (
                          <Clock className="w-6 h-6 text-slate-400" />
                        )}
                      </div>
                      <div
                        className={`w-0.5 h-full mt-2 ${fnfCase.status === "Completed"
                            ? "bg-green-300"
                            : "bg-slate-200"
                          }`}
                      ></div>
                    </div>
                    <div className="flex-1 pb-8">
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-3">
                          <h3 className="text-slate-900">
                            Financial Discussion with Dealer
                          </h3>
                          <Badge
                            className={
                              fnfCase.status === "Completed"
                                ? "bg-green-600"
                                : fnfCase.status === "Finance Approval"
                                  ? "bg-amber-600"
                                  : "bg-slate-400"
                            }
                          >
                            {fnfCase.status === "Completed"
                              ? "Completed"
                              : fnfCase.status === "Finance Approval"
                                ? "In Progress"
                                : "Pending"}
                          </Badge>
                        </div>
                      </div>
                      <p className="text-slate-600 text-sm mb-3">
                        Finance team, legal team, and relevant departments
                        discuss final settlement with the dealer. Dealer reviews
                        and agrees to the financial terms.
                      </p>
                      {fnfCase.status === "Finance Approval" && (
                        <Card className="bg-orange-50 border-orange-200">
                          <CardContent className="p-4">
                            <div className="flex items-start gap-3">
                              <AlertCircle className="w-5 h-5 text-orange-600 mt-0.5" />
                              <div>
                                <p className="text-sm text-orange-900 mb-1">
                                  Ongoing Discussions
                                </p>
                                <p className="text-xs text-orange-700">
                                  Negotiations in progress regarding
                                  recovery/payable amounts. Finance team is
                                  working with departments and dealer to resolve
                                  discrepancies.
                                </p>
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      )}
                    </div>
                  </div>

                  {/* Step 5: Full and Final Settlement */}
                  <div className="flex gap-4 items-start">
                    <div className="flex shrink-0 flex-col items-center">
                      <div
                        className={`size-12 shrink-0 aspect-square rounded-full flex items-center justify-center border-2 ${fnfCase.status === "Completed"
                            ? "bg-green-100 border-green-600"
                            : "bg-slate-100 border-slate-300"
                          }`}
                      >
                        {fnfCase.status === "Completed" ? (
                          <Check className="w-6 h-6 text-green-600" />
                        ) : (
                          <Clock className="w-6 h-6 text-slate-400" />
                        )}
                      </div>
                      <div
                        className={`w-0.5 h-full mt-2 ${fnfCase.status === "Completed"
                            ? "bg-green-300"
                            : "bg-slate-200"
                          }`}
                      ></div>
                    </div>
                    <div className="flex-1 pb-8">
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-3">
                          <h3 className="text-slate-900">
                            Full and Final Settlement
                          </h3>
                          <Badge
                            className={
                              fnfCase.status === "Completed"
                                ? "bg-green-600"
                                : "bg-slate-400"
                            }
                          >
                            {fnfCase.status === "Completed"
                              ? "Completed"
                              : "Pending"}
                          </Badge>
                        </div>
                      </div>
                      <p className="text-slate-600 text-sm mb-3">
                        All financial settlements are processed. Payments made
                        or recoveries completed as per agreed terms. All
                        documentation finalized.
                      </p>
                    </div>
                  </div>

                  {/* Step 6: F&F Complete */}
                  <div className="flex gap-4 items-start">
                    <div className="flex shrink-0 flex-col items-center">
                      <div
                        className={`size-12 shrink-0 aspect-square rounded-full flex items-center justify-center border-2 ${fnfCase.status === "Completed"
                            ? "bg-green-100 border-green-600"
                            : "bg-slate-100 border-slate-300"
                          }`}
                      >
                        {fnfCase.status === "Completed" ? (
                          <CheckCircle2 className="w-6 h-6 text-green-600" />
                        ) : (
                          <Clock className="w-6 h-6 text-slate-400" />
                        )}
                      </div>
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-3">
                          <h3 className="text-slate-900">F&F Complete</h3>
                          <Badge
                            className={
                              fnfCase.status === "Completed"
                                ? "bg-green-600"
                                : "bg-slate-400"
                            }
                          >
                            {fnfCase.status === "Completed"
                              ? "Completed"
                              : "Pending"}
                          </Badge>
                        </div>
                        {fnfCase.status === "Completed" && (
                          <span className="text-sm text-slate-600">
                            {fnfCase.settlementDate || "Oct 15, 2025"}
                          </span>
                        )}
                      </div>
                      <p className="text-slate-600 text-sm mb-3">
                        Full & Final settlement process completed successfully.
                        Case closed. All obligations fulfilled.
                      </p>
                      {fnfCase.status === "Completed" && (
                        <Card className="bg-gradient-to-r from-green-50 to-blue-50 border-green-300">
                          <CardContent className="p-4">
                            <div className="flex items-center gap-3">
                              <div className="size-12 shrink-0 aspect-square rounded-full bg-green-600 flex items-center justify-center">
                                <CheckCircle2 className="w-7 h-7 text-white" />
                              </div>
                              <div>
                                <p className="text-green-900">
                                  Settlement Successfully Completed
                                </p>
                                <p className="text-xs text-green-700 mt-1">
                                  All processes completed. Case Number:{" "}
                                  {fnfCase.caseNumber}
                                </p>
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Case Details Tab */}
        <TabsContent value="details" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Basic Information</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-6">
                <div>
                  <Label className="text-slate-600">Case Number</Label>
                  <p>{fnfCase.caseNumber}</p>
                </div>
                <div>
                  <Label className="text-slate-600">Dealer Code</Label>
                  <p>{fnfCase.dealerCode}</p>
                </div>
                <div>
                  <Label className="text-slate-600">Dealer Name</Label>
                  <p>{fnfCase.dealerName}</p>
                </div>
                <div>
                  <Label className="text-slate-600">Dealership Name</Label>
                  <p>{fnfCase.dealershipName}</p>
                </div>
                <div>
                  <Label className="text-slate-600">Location</Label>
                  <p>{fnfCase.location}</p>
                </div>
                <div>
                  <Label className="text-slate-600">Request Type</Label>
                  <p>{fnfCase.requestType}</p>
                </div>
                <div>
                  <Label className="text-slate-600">Original Request ID</Label>
                  <p>{fnfCase.originalRequestId}</p>
                </div>
                <div>
                  <Label className="text-slate-600">Submitted On</Label>
                  <p>{fnfCase.submittedOn}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="border-amber-200 bg-blue-50/30">
            <CardHeader>
              <CardTitle className="text-blue-900">
                F&F Settlement Information
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-6">
                <div>
                  <Label className="text-slate-600">
                    Last Operational Date (Sales)
                  </Label>
                  <p>{fnfCase.lastOperationalDateSales}</p>
                </div>
                <div>
                  <Label className="text-slate-600">
                    Last Operational Date (Services)
                  </Label>
                  <p>{fnfCase.lastOperationalDateServices}</p>
                </div>
                <div>
                  <Label className="text-slate-600">
                    Submitted Date (F&F Start)
                  </Label>
                  <p>{fnfCase.submittedOn}</p>
                </div>
                <div>
                  <Label className="text-slate-600">Days Elapsed since Submission</Label>
                  <div className="flex items-center gap-2">
                    <p>{fnfAge} days</p>
                    <Badge
                      variant="outline"
                      className={
                        fnfAge < 30
                          ? "bg-green-100 text-green-700 border-green-300"
                          : fnfAge < 60
                            ? "bg-yellow-100 text-yellow-700 border-yellow-300"
                            : "bg-red-100 text-red-700 border-red-300"
                      }
                    >
                      {fnfAge < 30
                        ? "Recent"
                        : fnfAge < 60
                          ? "In Progress"
                          : "Overdue"}
                    </Badge>
                  </div>
                </div>
                <div>
                  <Label className="text-slate-600">Type of Closure</Label>
                  <p>{fnfCase.typeOfClosure}</p>
                </div>
                <div>
                  <Label className="text-slate-600">GST</Label>
                  <p>{fnfCase.gst}</p>
                </div>
                <div>
                  <Label className="text-slate-600">Sales Code</Label>
                  <p>{fnfCase.salesCode}</p>
                </div>
                <div>
                  <Label className="text-slate-600">Service Code</Label>
                  <p>{fnfCase.serviceCode}</p>
                </div>
                <div>
                  <Label className="text-slate-600">Gear Code</Label>
                  <p>{fnfCase.gearCode}</p>
                </div>
                <div>
                  <Label className="text-slate-600">GMA Code</Label>
                  <p>{fnfCase.gmaCode}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          {fnfCase.status === "Under Review" && (
            <Card className="border-orange-200 bg-orange-50">
              <CardHeader>
                <CardTitle className="text-orange-900">Under Review</CardTitle>
                <CardDescription className="text-orange-700">
                  This case is under negotiation/discussion with the dealer,
                  finance team, legal team, and relevant departments
                </CardDescription>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-orange-800">
                  Discussions ongoing regarding recovery/payable amounts.
                  Finance team is working with departments to resolve
                  discrepancies.
                </p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        {/* Department Responses Tab */}
        <TabsContent value="departments">
          <Card>
            <CardHeader>
              <CardTitle>
                Department Responses ({responsesReceived} / {totalDepartments})
              </CardTitle>
              <CardDescription>
                Status of NOC and dues from all departments
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Department</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Amount Type</TableHead>
                    <TableHead>Amount</TableHead>
                    <TableHead>Submitted Date</TableHead>
                    <TableHead>Remarks</TableHead>
                    {canAnyDepartmentRespond && <TableHead>Actions</TableHead>}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {fnfCase.departmentResponses.map((dept: any) => (
                    <TableRow key={dept.id}>
                      <TableCell>{dept.departmentName}</TableCell>
                      <TableCell>
                        <Badge
                          className={getDepartmentStatusColor(dept.status)}
                        >
                          {dept.status}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {dept.amountType ? (
                          <Badge
                            variant="outline"
                            className={
                              dept.duesFlow === "recovery"
                                ? "bg-red-100 text-red-900 border-red-400 font-semibold"
                                : "bg-emerald-100 text-emerald-900 border-emerald-400 font-semibold"
                            }
                          >
                            {dept.amountType}
                          </Badge>
                        ) : (
                          "-"
                        )}
                      </TableCell>
                      <TableCell>
                        {dept.amount ? (
                          <span
                            className={`font-semibold tabular-nums ${dept.duesFlow === "recovery"
                                ? "text-red-700"
                                : "text-emerald-700"
                              }`}
                          >
                            ₹{dept.amount.toLocaleString()}
                          </span>
                        ) : (
                          "-"
                        )}
                      </TableCell>
                      <TableCell>{dept.submittedDate || "-"}</TableCell>
                      <TableCell className="max-w-xs truncate">
                        {dept.remarks || "-"}
                      </TableCell>
                      {canAnyDepartmentRespond && (
                        <TableCell>
                          {canRespondToDepartment(dept) ? (
                            <Button
                              variant="ghost"
                              size="sm"
                              className="text-amber-600 hover:text-blue-700"
                              onClick={() => {
                                setSelectedDept(dept);
                                setClearanceForm({
                                  remarks: dept.remarks === "-" ? "" : dept.remarks,
                                  amount: dept.amount || 0,
                                  type: dept.duesFlow === "payable" ? "Payable" : "Receivable",
                                });
                                setClearanceFile(null);
                                setShowClearanceDialog(true);
                              }}
                            >
                              Action
                            </Button>
                          ) : (
                            <span className="text-slate-400 text-sm">-</span>
                          )}
                        </TableCell>
                      )}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Financial Summary Tab */}
        <TabsContent value="financial">
          <div className="space-y-6">
            <Card className="border-blue-200 bg-blue-50">
              <CardHeader>
                <CardTitle>Department Claim vs Finance Validation</CardTitle>
                <CardDescription>
                  Final settlement totals are based on finance validated values.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Department</TableHead>
                      <TableHead>Department Claim</TableHead>
                      <TableHead>Finance Validated</TableHead>
                      <TableHead>Variance</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {departmentReconciliation.map((row) => (
                      <TableRow key={row.department}>
                        <TableCell>{row.department}</TableCell>
                        <TableCell>{row.claimAmount > 0 ? `${row.claimType} ₹${row.claimAmount.toLocaleString()}` : '-'}</TableCell>
                        <TableCell>{row.validatedAmount > 0 ? `${row.validatedType} ₹${row.validatedAmount.toLocaleString()}` : '-'}</TableCell>
                        <TableCell className={row.variance === 0 ? 'text-slate-600' : row.variance > 0 ? 'text-red-600' : 'text-green-600'}>
                          {row.claimAmount === 0 && row.validatedAmount === 0 ? '-' : `₹${row.variance.toLocaleString()}`}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Financial Summary</CardTitle>
                <CardDescription>
                  Consolidated view of all payable and receivable amounts
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div className="p-6 bg-green-50 rounded-lg border border-green-200">
                    <p className="text-sm text-green-700 mb-2">
                      Total Payable Amount
                    </p>
                    <p className="text-3xl text-green-600">
                      ₹{fnfCase.totalPayableAmount?.toLocaleString() || "0"}
                    </p>
                    <p className="text-xs text-green-600 mt-1">
                      Amount to be paid to dealer
                    </p>
                  </div>
                  <div className="p-6 bg-red-50 rounded-lg border border-red-200">
                    <p className="text-sm text-red-700 mb-2">
                      Total receivable amount
                    </p>
                    <p className="text-3xl text-red-600">
                      ₹{fnfCase.totalRecoveryAmount?.toLocaleString() || "0"}
                    </p>
                    <p className="text-xs text-red-600 mt-1">
                      Amount receivable from dealer
                    </p>
                  </div>
                  <div className="p-6 bg-amber-50 rounded-lg border border-amber-200">
                    <p className="text-sm text-amber-700 mb-2">
                      Total Deductions
                    </p>
                    <p className="text-3xl text-amber-600 font-bold">
                      ₹{fnfCase.totalDeductions?.toLocaleString() || "0"}
                    </p>
                    <p className="text-xs text-amber-600 mt-1">
                      Warranty holdbacks / Policy penalties
                    </p>
                  </div>
                  <div className="p-6 bg-blue-50 rounded-lg border border-blue-200">
                    <p className="text-sm text-blue-700 mb-2">Net Settlement Amount</p>
                    <p
                      className={`text-3xl font-extrabold ${(fnfCase.netAmount || 0) < 0
                          ? "text-red-600"
                          : "text-green-600"
                        }`}
                    >
                      ₹{Math.abs(fnfCase.netAmount || 0).toLocaleString()}
                    </p>
                    <p className="text-xs text-blue-600 mt-1">
                      {(fnfCase.netAmount || 0) < 0
                        ? "Receivable from dealer"
                        : "Payment to dealer"}
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Finance Report Status</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-4">
                  <Badge
                    className={
                      fnfCase.financeReportStatus === "Completed"
                        ? "bg-green-100 text-green-700 border-green-300"
                        : fnfCase.financeReportStatus === "In Progress"
                          ? "bg-yellow-100 text-yellow-700 border-yellow-300"
                          : "bg-slate-100 text-slate-700 border-slate-300"
                    }
                  >
                    {fnfCase.financeReportStatus}
                  </Badge>
                  {fnfCase.financeReportStatus === "Pending" && (
                    <p className="text-slate-600 text-sm">
                      Waiting for all department responses before finance can
                      prepare final report
                    </p>
                  )}
                  {fnfCase.financeReportStatus === "In Progress" && (
                    <p className="text-slate-600 text-sm">
                      Finance team is reviewing department responses and
                      preparing final settlement report
                    </p>
                  )}
                </div>
                {fnfCase.financeRemarks && (
                  <div className="mt-4 p-4 bg-slate-50 rounded-lg">
                    <Label className="text-slate-600">Finance Remarks</Label>
                    <p className="mt-1">{fnfCase.financeRemarks}</p>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* Documents Tab */}
        <TabsContent value="documents">
          <Card>
            <CardHeader>
              <CardTitle>Documents</CardTitle>
              <CardDescription>
                All NOC documents and due statements from departments
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Document Name</TableHead>
                    <TableHead>Type</TableHead>
                    <TableHead>Upload Date</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {fnfCase.documents.map((doc: any) => (
                    <TableRow key={doc.id}>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <FileText className="w-4 h-4 text-slate-500" />
                          <span>{doc.name}</span>
                        </div>
                      </TableCell>
                      <TableCell>{doc.type}</TableCell>
                      <TableCell>{doc.uploadDate}</TableCell>
                      <TableCell>
                        <Badge
                          variant={
                            doc.status === "Verified" ? "default" : "secondary"
                          }
                        >
                          {doc.status}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            const path = doc.url;
                            const fullPath =
                              path.startsWith("/uploads/") &&
                                !path.startsWith("/uploads/documents/")
                                ? path.replace(
                                  "/uploads/",
                                  "/uploads/documents/",
                                )
                                : path;
                            setPreviewDocument({
                              fileName: doc.name,
                              filePath: fullPath,
                              documentType: doc.type,
                            });
                          }}
                        >
                          View
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Bank Details Tab */}
        <TabsContent value="bank">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <div>
                <CardTitle>Bank Details</CardTitle>
                <CardDescription>
                  Dealer bank accounts for settlement disbursement
                </CardDescription>
              </div>
              <Button
                onClick={() => {
                  setEditingBank(null);
                  setIsBankModalOpen(true);
                }}
                className="bg-amber-600"
              >
                <Plus className="w-4 h-4 mr-2" />
                Add Account
              </Button>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {bankDetails.length > 0 ? (
                  bankDetails.map((bank: any) => (
                    <Card key={bank.id} className={`relative overflow-hidden ${bank.isPrimary ? 'border-amber-500 bg-blue-50/30' : ''}`}>
                      {bank.isPrimary && (
                        <div className="absolute top-0 right-0 p-1 bg-amber-600 text-white text-[10px] uppercase font-bold px-2 rounded-bl">
                          Primary
                        </div>
                      )}
                      <CardContent className="p-5">
                        <div className="flex items-center gap-3 mb-4">
                          <div className="p-2 bg-amber-100 rounded-lg">
                            <Building2 className="w-5 h-5 text-amber-600" />
                          </div>
                          <div>
                            <p className="font-bold text-slate-900">{bank.bankName}</p>
                            <p className="text-xs text-slate-500">{bank.branchName}</p>
                          </div>
                        </div>

                        <div className="space-y-3 mb-4">
                          <div>
                            <p className="text-[10px] text-slate-500 uppercase font-bold">Account Holder</p>
                            <p className="text-sm font-medium">{bank.accountHolderName}</p>
                          </div>
                          <div className="flex justify-between">
                            <div>
                              <p className="text-[10px] text-slate-500 uppercase font-bold">Account Number</p>
                              <p className="text-sm font-mono tracking-wider">
                                {bank.accountNumber.replace(/.(?=.{4})/g, '*')}
                              </p>
                            </div>
                            <div>
                              <p className="text-[10px] text-slate-500 uppercase font-bold">IFSC</p>
                              <p className="text-sm font-mono">{bank.ifscCode}</p>
                            </div>
                          </div>
                        </div>

                        <div className="flex items-center justify-end gap-2 pt-2 border-t border-slate-100">
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-8 text-amber-600"
                            onClick={() => {
                              setEditingBank(bank);
                              setIsBankModalOpen(true);
                            }}
                          >
                            <Pencil className="w-3 h-3 mr-1" />
                            Edit
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-8 text-red-600"
                            onClick={() => handleDeleteBank(bank.id)}
                          >
                            <Trash2 className="w-3 h-3 mr-1" />
                            Delete
                          </Button>
                        </div>
                      </CardContent>
                    </Card>
                  ))
                ) : (
                  <div className="col-span-full py-12 text-center border-2 border-dashed rounded-lg bg-slate-50">
                    <Building2 className="w-12 h-12 text-slate-300 mx-auto mb-3" />
                    <p className="text-slate-600">No bank details found</p>
                    <Button
                      variant="link"
                      onClick={() => setIsBankModalOpen(true)}
                    >
                      Add first bank account
                    </Button>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Audit Trail Tab */}
        <TabsContent value="audit">
          <Card>
            <CardHeader>
              <CardTitle>Audit Trail</CardTitle>
              <CardDescription>
                Complete history of actions on this F&F case
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {auditLogs.length > 0 ? (
                  auditLogs.map((log: any) => (
                    <div
                      key={log.id}
                      className="flex gap-3 pb-4 border-b border-slate-100 last:border-0"
                    >
                      <div className="w-2 h-2 rounded-full bg-slate-400 mt-2" />
                      <div className="flex-1">
                        <div className="flex items-center justify-between mb-1">
                          <p className="font-semibold text-slate-900 flex items-center gap-2">
                            {log.action === 'FNF_CREATED' && <Badge className="bg-amber-600 h-2 w-2 p-0 rounded-full" />}
                            {(log.description && !log.newData?.action) ? log.description : (
                              <>
                                {getFriendlyActionName(log.newData?.action || log.action)}
                                {log.newData?.department && (
                                  <span className="text-amber-600 ml-1 font-bold">
                                    - {log.newData.department}
                                  </span>
                                )}
                              </>
                            )}
                          </p>
                          <span className="text-xs text-slate-500">
                            {formatDateTime(log.createdAt || log.timestamp)}
                          </span>
                        </div>
                        <div className="flex items-center gap-2 text-sm text-slate-600 mb-2">
                          <Badge variant="outline" className="text-[10px] uppercase">{log.actor?.name || log.userName || 'System'}</Badge>
                        </div>

                        {(log.newData?.remarks || log.remarks) && (
                          <div className="mt-2 p-3 bg-slate-50 border border-slate-200 rounded text-sm text-slate-700">
                            {log.newData?.remarks || log.remarks}
                          </div>
                        )}

                        {log.newData && Object.keys(log.newData).filter(k => k !== 'remarks' && k !== 'status' && k !== 'action' && k !== 'department').length > 0 && (
                          <div className="mt-2 space-y-1">
                            <p className="text-[10px] text-slate-500 uppercase font-bold px-1">Changes:</p>
                            <div className="flex flex-wrap gap-2">
                              {Object.entries(log.newData).filter(([k]) => k !== 'remarks' && k !== 'action' && k !== 'department').map(([key, val]: any) => (
                                <div key={key} className="text-[11px] bg-slate-100 border rounded px-2 py-0.5 flex items-center gap-1">
                                  <span className="text-slate-500">{key}:</span>
                                  <span className="text-slate-900 font-medium">{String(val)}</span>
                                </div>
                              ))}
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  ))
                ) : (
                  <div className="text-center py-8 text-slate-500">
                    <p>No activity logs found for this case.</p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Send to Stakeholders Dialog */}
      <Dialog
        open={sendStakeholdersDialog}
        onOpenChange={setSendStakeholdersDialog}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Send to All Stakeholders</DialogTitle>
            <DialogDescription>
              This will send notifications to all 16 departments to submit their
              NOC or dues information
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="p-4 bg-blue-50 rounded-lg border border-amber-200">
              <p className="text-sm text-blue-900 mb-2">
                Notifications will be sent to:
              </p>
              <ul className="text-sm text-blue-800 space-y-1 ml-4">
                <li>• All 16 departments</li>
                <li>• Case Number: {fnfCase.caseNumber}</li>
                <li>• Dealer: {fnfCase.dealerName}</li>
                <li>• Type: {fnfCase.requestType}</li>
              </ul>
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setSendStakeholdersDialog(false)}
            >
              Cancel
            </Button>
            <Button
              onClick={handleSendToStakeholders}
              className="bg-amber-600 hover:bg-blue-700"
            >
              <Send className="w-4 h-4 mr-2" />
              Send Notifications
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showClearanceDialog} onOpenChange={setShowClearanceDialog}>
        <DialogContent className="sm:max-w-[460px]">
          <DialogHeader>
            <DialogTitle>Update {selectedDept?.departmentName} Response</DialogTitle>
            <DialogDescription>
              Provide dues/NOC response with remarks and optional supporting proof.
            </DialogDescription>
          </DialogHeader>

          <div className="grid gap-4 py-2">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="type" className="text-right">Type</Label>
              <select
                id="type"
                className="col-span-3 flex h-10 w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm"
                value={clearanceForm.type}
                onChange={(e) => setClearanceForm({ ...clearanceForm, type: e.target.value })}
              >
                <option value="Receivable">Receivable (from dealer)</option>
                <option value="Payable">Payable (to dealer)</option>
                <option value="Deduction">Deduction</option>
              </select>
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="amount" className="text-right">Amount</Label>
              <div className="col-span-3 relative">
                <span className="absolute left-3 top-2.5 text-slate-500 font-medium">₹</span>
                <input
                  id="amount"
                  type="number"
                  className="flex h-10 w-full rounded-md border border-slate-200 bg-white pl-7 pr-3 py-2 text-sm"
                  value={clearanceForm.amount}
                  onChange={(e) => setClearanceForm({ ...clearanceForm, amount: Number(e.target.value) })}
                />
              </div>
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="remarks" className="text-right">Remarks</Label>
              <textarea
                id="remarks"
                className="col-span-3 flex min-h-[80px] w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm"
                placeholder="Add response details..."
                value={clearanceForm.remarks}
                onChange={(e) => setClearanceForm({ ...clearanceForm, remarks: e.target.value })}
              />
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="proof" className="text-right">Proof</Label>
              <input
                id="proof"
                type="file"
                className="col-span-3 text-sm"
                onChange={(e) => setClearanceFile(e.target.files?.[0] || null)}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowClearanceDialog(false)}>
              Cancel
            </Button>
            <Button
              className="bg-amber-600 hover:bg-blue-700"
              onClick={handleUpdateClearance}
              disabled={isUpdatingClearance}
            >
              {isUpdatingClearance ? "Saving..." : "Submit Response"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Bank Details Modal */}
      <BankDetailsModal
        isOpen={isBankModalOpen}
        onClose={() => {
          setIsBankModalOpen(false);
          setEditingBank(null);
        }}
        onSubmit={handleUpsertBank}
        editingBank={editingBank}
        isSubmitting={isSubmittingBank}
      />

      <DocumentPreviewModal
        isOpen={!!previewDocument}
        onClose={() => setPreviewDocument(null)}
        document={previewDocument}
      />
    </div>
  );
}
