import { useState, useEffect } from 'react';
import { API } from '@/api/API';
import { Loader2 } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { 
  CheckCircle, 
  AlertCircle,
  FileText,
  User,
  Calendar,
  Wallet,
  Receipt,
  Calculator,
  TrendingUp,
  TrendingDown,
  MapPin
} from 'lucide-react';
import { formatDateTime } from '@/components/ui/utils';
import { toast } from 'sonner';

// Using live data from API instead of mockFnFCases
interface FinanceFnFPageProps {
  onViewFnFDetails?: (fnfId: string) => void;
}

export function FinanceFnFPage({ onViewFnFDetails }: FinanceFnFPageProps = {}) {
  const [settlements, setSettlements] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedCase, setSelectedCase] = useState<any>(null);
  const [showReviewDialog, setShowReviewDialog] = useState(false);
  const [showDetailsDialog, setShowDetailsDialog] = useState(false);
  const [adjustments, setAdjustments] = useState('');
  const [finalNotes, setFinalNotes] = useState('');
  const [filterStatus, setFilterStatus] = useState<'all' | 'pending' | 'approved'>('all');

  useEffect(() => {
    fetchSettlements();
  }, []);

  const fetchSettlements = async () => {
    try {
      setLoading(true);
      const response = await API.getFnFSettlements();
      const data = response.data as any;
      if (data.success) {
        setSettlements(data.settlements || []);
      }
    } catch (error) {
      console.error('Fetch settlements error:', error);
      toast.error('Failed to fetch settlement cases');
    } finally {
      setLoading(false);
    }
  };

  const getMappedData = (s: any) => ({
    id: s.id,
    caseId: s.settlementId || s.resignation?.resignationId || s.terminationRequest?.requestId || s.id.substring(0, 8),
    dealerCode: s.outlet?.code || s.dealer?.dealerCode?.dealerCode || 'N/A',
    dealerName: s.outlet?.dealer?.fullName || s.dealer?.legalName || s.dealer?.businessName || s.dealer?.fullName || 'N/A',
    location: s.outlet?.city || s.outlet?.location || 'N/A',
    terminationType: s.resignationId ? 'Resignation' : 'Termination',
    submittedDate: formatDateTime(s.createdAt),
    status: s.status === 'Calculated' ? 'Pending Finance Review' : (s.status === 'Settled' ? 'Settled' : s.status),
    financialData: {
      totalPayables: parseFloat(s.totalPayables) || 0,
      totalReceivables: parseFloat(s.totalReceivables) || 0,
      netAmount: parseFloat(s.netAmount) || 0,
    },
    settlementAmount: Math.abs(parseFloat(s.netAmount) || 0),
    settlementType: parseFloat(s.netAmount) > 0 ? 'Payable to Dealer' : 'Receivable from Dealer',
    approvedDate: s.settlementDate ? formatDateTime(s.settlementDate) : null
  });

  const displaySettlements = settlements.map(getMappedData);

  const filteredCases = displaySettlements.filter(fnf => {
    if (filterStatus === 'all') return true;
    if (filterStatus === 'pending') return fnf.status === 'Pending Finance Review' || fnf.status === 'Calculated' || fnf.status === 'Initiated' || fnf.status === 'Under Review';
    if (filterStatus === 'approved') return fnf.status === 'Settled' || fnf.status === 'Completed';
    return true;
  });

  const calculateSettlement = (data: any) => {
    // Backend already provides these, but keep for UI consistency
    return {
      receivables: data.totalReceivables || 0,
      payables: data.totalPayables || 0,
      deductions: 0, // Backend sums deductions into receivables or payables
      netSettlement: data.netAmount || 0,
      settlementType: (data.netAmount || 0) > 0 ? 'Payable to Dealer' : 'Receivable from Dealer',
      settlementAmount: Math.abs(data.netAmount || 0),
    };
  };

  const handleReviewCase = (fnfCase: any) => {
    if (onViewFnFDetails) {
      onViewFnFDetails(fnfCase.id);
    } else {
      setSelectedCase(fnfCase);
      setShowReviewDialog(true);
    }
  };

  const handleViewDetails = (fnfCase: any) => {
    if (onViewFnFDetails) {
      onViewFnFDetails(fnfCase.id);
    } else {
      setSelectedCase(fnfCase);
      setShowDetailsDialog(true);
    }
  };

  const confirmSettlement = () => {
    const settlement = calculateSettlement(selectedCase.financialData);
    toast.success(
      `Settlement approved: ${settlement.settlementType} - ₹${settlement.settlementAmount.toLocaleString()}`
    );
    setShowReviewDialog(false);
    setAdjustments('');
    setFinalNotes('');
    setSelectedCase(null);
  };

  const pendingCount = displaySettlements.filter(fnf => fnf.status === 'Pending Finance Review' || fnf.status === 'Calculated' || fnf.status === 'Initiated' || fnf.status === 'Under Review').length;
  const approvedCount = displaySettlements.filter(fnf => fnf.status === 'Settled' || fnf.status === 'Completed').length;

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

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-slate-900 mb-2">F&F Financial Settlement</h1>
        <p className="text-slate-600">Review and process full & final settlements for dealerships</p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm text-slate-600">Pending Review</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="text-slate-900 text-2xl">{pendingCount}</div>
              <Calculator className="w-8 h-8 text-amber-600" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm text-slate-600">Approved Settlements</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="text-slate-900 text-2xl">{approvedCount}</div>
              <CheckCircle className="w-8 h-8 text-green-600" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm text-slate-600">Total Cases</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="text-slate-900 text-2xl">{displaySettlements.length}</div>
              <FileText className="w-8 h-8 text-blue-600" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm text-slate-600">Net Financial Position</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className={`text-2xl ${displaySettlements.reduce((sum, s) => sum + (s.financialData.netAmount || 0), 0) < 0 ? 'text-green-600' : 'text-red-600'}`}>
                ₹{Math.abs(displaySettlements.reduce((sum, s) => sum + (s.financialData.netAmount || 0), 0)).toLocaleString('en-IN')}
              </div>
              <TrendingUp className="w-8 h-8 text-purple-600" />
            </div>
            <p className="text-[10px] text-slate-500 mt-1">
              {displaySettlements.reduce((sum, s) => sum + (s.financialData.netAmount || 0), 0) < 0 ? 'Net Receivable' : 'Net Payable'}
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Filter Tabs */}
      <div className="flex gap-2">
        <Button
          variant={filterStatus === 'all' ? 'default' : 'outline'}
          onClick={() => setFilterStatus('all')}
          className={filterStatus === 'all' ? 'bg-amber-600 hover:bg-amber-700' : ''}
        >
          All Cases ({displaySettlements.length})
        </Button>
        <Button
          variant={filterStatus === 'pending' ? 'default' : 'outline'}
          onClick={() => setFilterStatus('pending')}
          className={filterStatus === 'pending' ? 'bg-amber-600 hover:bg-amber-700' : ''}
        >
          Pending Review ({pendingCount})
        </Button>
        <Button
          variant={filterStatus === 'approved' ? 'default' : 'outline'}
          onClick={() => setFilterStatus('approved')}
          className={filterStatus === 'approved' ? 'bg-amber-600 hover:bg-amber-700' : ''}
        >
          Approved ({approvedCount})
        </Button>
      </div>

      {/* F&F Cases Table */}
      <Card>
        <CardHeader>
          <CardTitle>F&F Settlement Queue</CardTitle>
          <CardDescription>Review financial status and calculate settlements</CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Case ID</TableHead>
                <TableHead>Dealer Details</TableHead>
                <TableHead>Location</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Submitted Date</TableHead>
                <TableHead>Net Settlement</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredCases.map((fnfCase) => {
                const settlement = calculateSettlement(fnfCase.financialData);
                return (
                  <TableRow key={fnfCase.id}>
                    <TableCell>
                      <div>
                        <div className="text-slate-900">{fnfCase.caseId}</div>
                        <div className="text-sm text-slate-500">{fnfCase.dealerCode}</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <User className="w-4 h-4 text-slate-400" />
                        <span className="text-slate-900">{fnfCase.dealerName}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <MapPin className="w-4 h-4 text-slate-400" />
                        <span className="text-slate-900">{fnfCase.location}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant={fnfCase.terminationType === 'Resignation' ? 'default' : 'secondary'}>
                        {fnfCase.terminationType}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Calendar className="w-4 h-4 text-slate-400" />
                        <span className="text-slate-900">{fnfCase.submittedDate}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        {settlement.settlementType === 'Payable to Dealer' ? (
                          <TrendingDown className="w-4 h-4 text-red-600" />
                        ) : (
                          <TrendingUp className="w-4 h-4 text-green-600" />
                        )}
                        <div>
                          <div className="text-slate-900">₹{settlement.settlementAmount.toLocaleString()}</div>
                          <div className="text-xs text-slate-500">{settlement.settlementType}</div>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant={fnfCase.status === 'Settlement Approved' ? 'default' : 'secondary'}
                        className={fnfCase.status === 'Settlement Approved' ? 'bg-green-600 text-white' : 'bg-amber-600 text-white'}
                      >
                        {fnfCase.status}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Button 
                        size="sm" 
                        variant={fnfCase.status === 'Pending Finance Review' ? 'default' : 'outline'}
                        className={fnfCase.status === 'Pending Finance Review' ? 'bg-amber-600 hover:bg-amber-700' : ''}
                        onClick={() => handleViewDetails(fnfCase)}
                      >
                        <FileText className="w-4 h-4 mr-2" />
                        View Details
                      </Button>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Review Dialog */}
      <Dialog open={showReviewDialog} onOpenChange={setShowReviewDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Financial Settlement Review</DialogTitle>
            <DialogDescription>
              Review financial details and calculate final settlement for {selectedCase?.dealerName}
            </DialogDescription>
          </DialogHeader>

          {selectedCase && (
            <Tabs defaultValue="breakdown" className="w-full">
              <TabsList className="grid w-full grid-cols-3">
                <TabsTrigger value="breakdown">Financial Breakdown</TabsTrigger>
                <TabsTrigger value="calculation">Settlement Calculation</TabsTrigger>
                <TabsTrigger value="summary">Final Summary</TabsTrigger>
              </TabsList>

              <TabsContent value="breakdown" className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  {/* Payables (Company owes dealer) */}
                  <Card className="border-green-200 bg-green-50">
                    <CardHeader>
                      <CardTitle className="text-base flex items-center gap-2">
                        <Wallet className="w-5 h-5 text-green-600" />
                        Payables to Dealer
                      </CardTitle>
                      <CardDescription>Amounts company owes to dealer</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      <div className="flex justify-between items-center">
                        <span className="text-slate-600">Security Deposit</span>
                        <span className="text-slate-900">₹{selectedCase.financialData.securityDeposit.toLocaleString()}</span>
                      </div>
                      <div className="flex justify-between items-center">
                        <span className="text-slate-600">Inventory Value</span>
                        <span className="text-slate-900">₹{selectedCase.financialData.inventoryValue.toLocaleString()}</span>
                      </div>
                      <div className="flex justify-between items-center">
                        <span className="text-slate-600">Equipment Value</span>
                        <span className="text-slate-900">₹{selectedCase.financialData.equipmentValue.toLocaleString()}</span>
                      </div>
                      <div className="pt-3 border-t border-green-300">
                        <div className="flex justify-between items-center">
                          <span className="text-slate-900">Total Payables</span>
                          <span className="text-slate-900 text-lg">
                            ₹{(
                              selectedCase.financialData.securityDeposit +
                              selectedCase.financialData.inventoryValue +
                              selectedCase.financialData.equipmentValue
                            ).toLocaleString()}
                          </span>
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* Receivables (Dealer owes company) */}
                  <Card className="border-red-200 bg-red-50">
                    <CardHeader>
                      <CardTitle className="text-base flex items-center gap-2">
                        <Receipt className="w-5 h-5 text-red-600" />
                        Receivables from Dealer
                      </CardTitle>
                      <CardDescription>Amounts dealer owes to company</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      <div className="flex justify-between items-center">
                        <span className="text-slate-600">Outstanding Invoices</span>
                        <span className="text-slate-900">₹{selectedCase.financialData.outstandingInvoices.toLocaleString()}</span>
                      </div>
                      <div className="flex justify-between items-center">
                        <span className="text-slate-600">Service Dues</span>
                        <span className="text-slate-900">₹{selectedCase.financialData.serviceDues.toLocaleString()}</span>
                      </div>
                      <div className="flex justify-between items-center">
                        <span className="text-slate-600">Parts Dues</span>
                        <span className="text-slate-900">₹{selectedCase.financialData.partsDues.toLocaleString()}</span>
                      </div>
                      <div className="flex justify-between items-center">
                        <span className="text-slate-600">Advances Given</span>
                        <span className="text-slate-900">₹{selectedCase.financialData.advancesGiven.toLocaleString()}</span>
                      </div>
                      <div className="flex justify-between items-center">
                        <span className="text-slate-600">Penalties</span>
                        <span className="text-slate-900">₹{selectedCase.financialData.penalties.toLocaleString()}</span>
                      </div>
                      <div className="flex justify-between items-center">
                        <span className="text-slate-600">Other Charges</span>
                        <span className="text-slate-900">₹{selectedCase.financialData.otherCharges.toLocaleString()}</span>
                      </div>
                      <div className="pt-3 border-t border-red-300">
                        <div className="flex justify-between items-center">
                          <span className="text-slate-900">Total Receivables</span>
                          <span className="text-slate-900 text-lg">
                            ₹{calculateSettlement(selectedCase.financialData).receivables.toLocaleString()}
                          </span>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </div>

                {/* Deductions */}
                <Card className="border-amber-200 bg-amber-50">
                  <CardHeader>
                    <CardTitle className="text-base flex items-center gap-2">
                      <AlertCircle className="w-5 h-5 text-amber-600" />
                      Deductions
                    </CardTitle>
                    <CardDescription>Pending claims and deductions</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="flex justify-between items-center">
                      <span className="text-slate-600">Warranty Claims Pending</span>
                      <span className="text-slate-900 text-lg">₹{selectedCase.financialData.warrantyPending.toLocaleString()}</span>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="calculation" className="space-y-4">
                <Card>
                  <CardHeader>
                    <CardTitle>Settlement Calculation</CardTitle>
                    <CardDescription>Step-by-step calculation of final settlement amount</CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {(() => {
                      const settlement = calculateSettlement(selectedCase.financialData);
                      return (
                        <>
                          <div className="space-y-3">
                            <div className="flex justify-between items-center p-3 bg-green-50 rounded">
                              <span className="text-slate-900">Total Payables (to Dealer)</span>
                              <span className="text-green-600 text-lg">+ ₹{settlement.payables.toLocaleString()}</span>
                            </div>
                            <div className="flex justify-between items-center p-3 bg-red-50 rounded">
                              <span className="text-slate-900">Total Receivables (from Dealer)</span>
                              <span className="text-red-600 text-lg">- ₹{settlement.receivables.toLocaleString()}</span>
                            </div>
                            <div className="flex justify-between items-center p-3 bg-amber-50 rounded">
                              <span className="text-slate-900">Total Deductions</span>
                              <span className="text-amber-600 text-lg">- ₹{settlement.deductions.toLocaleString()}</span>
                            </div>
                          </div>

                          <div className="h-px bg-slate-300"></div>

                          <div className={`p-4 rounded-lg ${
                            settlement.netSettlement > 0 
                              ? 'bg-red-100 border-2 border-red-300' 
                              : 'bg-green-100 border-2 border-green-300'
                          }`}>
                            <div className="flex items-center justify-between mb-2">
                              <span className="text-slate-900">Net Settlement</span>
                              <span className="text-2xl text-slate-900">
                                ₹{settlement.settlementAmount.toLocaleString()}
                              </span>
                            </div>
                            <div className="flex items-center gap-2">
                              {settlement.settlementType === 'Payable to Dealer' ? (
                                <>
                                  <TrendingDown className="w-5 h-5 text-red-600" />
                                  <span className="text-red-700">Company needs to pay dealer</span>
                                </>
                              ) : (
                                <>
                                  <TrendingUp className="w-5 h-5 text-green-600" />
                                  <span className="text-green-700">Dealer needs to pay company</span>
                                </>
                              )}
                            </div>
                          </div>

                          <div className="flex items-start gap-3 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                            <AlertCircle className="w-5 h-5 text-blue-600 mt-0.5" />
                            <div>
                              <p className="text-sm text-slate-900 mb-1">Calculation Formula</p>
                              <p className="text-sm text-slate-600">
                                Net Settlement = Total Payables - Total Receivables - Total Deductions
                              </p>
                              <p className="text-sm text-slate-600 mt-2">
                                = ₹{settlement.payables.toLocaleString()} - ₹{settlement.receivables.toLocaleString()} - ₹{settlement.deductions.toLocaleString()}
                              </p>
                            </div>
                          </div>
                        </>
                      );
                    })()}
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="summary" className="space-y-4">
                <Card>
                  <CardHeader>
                    <CardTitle>Case Summary</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <p className="text-sm text-slate-500">Case ID</p>
                        <p className="text-slate-900">{selectedCase.id}</p>
                      </div>
                      <div>
                        <p className="text-sm text-slate-500">Dealer Name</p>
                        <p className="text-slate-900">{selectedCase.dealerName}</p>
                      </div>
                      <div>
                        <p className="text-sm text-slate-500">Dealer Code</p>
                        <p className="text-slate-900">{selectedCase.dealerCode}</p>
                      </div>
                      <div>
                        <p className="text-sm text-slate-500">Location</p>
                        <p className="text-slate-900">{selectedCase.location}</p>
                      </div>
                      <div>
                        <p className="text-sm text-slate-500">Termination Type</p>
                        <p className="text-slate-900">{selectedCase.terminationType}</p>
                      </div>
                      <div>
                        <p className="text-sm text-slate-500">Submitted Date</p>
                        <p className="text-slate-900">{selectedCase.submittedDate}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>Final Settlement</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {(() => {
                      const settlement = calculateSettlement(selectedCase.financialData);
                      return (
                        <div className={`p-6 rounded-lg text-center ${
                          settlement.settlementType === 'Payable to Dealer'
                            ? 'bg-red-100 border-2 border-red-300'
                            : 'bg-green-100 border-2 border-green-300'
                        }`}>
                          <div className="flex items-center justify-center gap-3 mb-3">
                            {settlement.settlementType === 'Payable to Dealer' ? (
                              <TrendingDown className="w-8 h-8 text-red-600" />
                            ) : (
                              <TrendingUp className="w-8 h-8 text-green-600" />
                            )}
                            <span className={`text-lg ${
                              settlement.settlementType === 'Payable to Dealer' ? 'text-red-700' : 'text-green-700'
                            }`}>
                              {settlement.settlementType}
                            </span>
                          </div>
                          <div className="text-4xl text-slate-900 mb-2">
                            ₹{settlement.settlementAmount.toLocaleString()}
                          </div>
                          <p className="text-slate-600">
                            {settlement.settlementType === 'Payable to Dealer'
                              ? 'Company will pay this amount to the dealer'
                              : 'Dealer must pay this amount to the company'}
                          </p>
                        </div>
                      );
                    })()}

                    <div className="space-y-2">
                      <Label htmlFor="adjustments">Adjustments (if any)</Label>
                      <Input
                        id="adjustments"
                        value={adjustments}
                        onChange={(e) => setAdjustments(e.target.value)}
                        placeholder="Enter any adjustments to the settlement amount"
                      />
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="finalNotes">Final Notes</Label>
                      <Textarea
                        id="finalNotes"
                        value={finalNotes}
                        onChange={(e) => setFinalNotes(e.target.value)}
                        placeholder="Enter any final notes or remarks for this settlement..."
                        rows={4}
                      />
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowReviewDialog(false)}>
              Cancel
            </Button>
            <Button
              className="bg-green-600 hover:bg-green-700"
              onClick={confirmSettlement}
            >
              <CheckCircle className="w-4 h-4 mr-2" />
              Approve Settlement
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* View Details Dialog */}
      <Dialog open={showDetailsDialog} onOpenChange={setShowDetailsDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Settlement Details</DialogTitle>
            <DialogDescription>
              Complete settlement information for {selectedCase?.dealerName}
            </DialogDescription>
          </DialogHeader>

          {selectedCase && (
            <Tabs defaultValue="info" className="w-full">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="info">Case Information</TabsTrigger>
                <TabsTrigger value="financial">Financial Breakdown</TabsTrigger>
              </TabsList>

              <TabsContent value="info" className="space-y-4 mt-4">
                <Card>
                  <CardHeader>
                    <CardTitle className="text-base">Case Details</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <p className="text-sm text-slate-500">Case ID</p>
                        <p className="text-slate-900">{selectedCase.id}</p>
                      </div>
                      <div>
                        <p className="text-sm text-slate-500">Dealer Code</p>
                        <p className="text-slate-900">{selectedCase.dealerCode}</p>
                      </div>
                      <div>
                        <p className="text-sm text-slate-500">Dealer Name</p>
                        <p className="text-slate-900">{selectedCase.dealerName}</p>
                      </div>
                      <div>
                        <p className="text-sm text-slate-500">Location</p>
                        <p className="text-slate-900">{selectedCase.location}</p>
                      </div>
                      <div>
                        <p className="text-sm text-slate-500">Termination Type</p>
                        <Badge variant={selectedCase.terminationType === 'Resignation' ? 'default' : 'secondary'}>
                          {selectedCase.terminationType}
                        </Badge>
                      </div>
                      <div>
                        <p className="text-sm text-slate-500">Status</p>
                        <Badge
                          variant={selectedCase.status === 'Settlement Approved' ? 'default' : 'secondary'}
                          className={selectedCase.status === 'Settlement Approved' ? 'bg-green-600 text-white' : 'bg-amber-600 text-white'}
                        >
                          {selectedCase.status}
                        </Badge>
                      </div>
                      <div>
                        <p className="text-sm text-slate-500">Submitted Date</p>
                        <p className="text-slate-900">{selectedCase.submittedDate}</p>
                      </div>
                      {selectedCase.approvedDate && (
                        <div>
                          <p className="text-sm text-slate-500">Approved Date</p>
                          <p className="text-slate-900">{selectedCase.approvedDate}</p>
                        </div>
                      )}
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="financial" className="space-y-4 mt-4">
                {(() => {
                  const settlement = calculateSettlement(selectedCase.financialData);
                  return (
                    <>
                      {/* Payables */}
                      <Card className="border-green-200 bg-green-50">
                        <CardHeader>
                          <CardTitle className="text-base flex items-center gap-2">
                            <Wallet className="w-5 h-5 text-green-600" />
                            Payables to Dealer
                          </CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-2">
                          <div className="flex justify-between">
                            <span className="text-slate-600">Security Deposit</span>
                            <span className="text-slate-900">₹{selectedCase.financialData.securityDeposit.toLocaleString()}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-600">Inventory Value</span>
                            <span className="text-slate-900">₹{selectedCase.financialData.inventoryValue.toLocaleString()}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-600">Equipment Value</span>
                            <span className="text-slate-900">₹{selectedCase.financialData.equipmentValue.toLocaleString()}</span>
                          </div>
                          <div className="pt-2 border-t border-green-300">
                            <div className="flex justify-between">
                              <span className="text-slate-900">Total Payables</span>
                              <span className="text-slate-900 text-lg">₹{settlement.payables.toLocaleString()}</span>
                            </div>
                          </div>
                        </CardContent>
                      </Card>

                      {/* Receivables */}
                      <Card className="border-red-200 bg-red-50">
                        <CardHeader>
                          <CardTitle className="text-base flex items-center gap-2">
                            <Receipt className="w-5 h-5 text-red-600" />
                            Receivables from Dealer
                          </CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-2">
                          <div className="flex justify-between">
                            <span className="text-slate-600">Outstanding Invoices</span>
                            <span className="text-slate-900">₹{selectedCase.financialData.outstandingInvoices.toLocaleString()}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-600">Service Dues</span>
                            <span className="text-slate-900">₹{selectedCase.financialData.serviceDues.toLocaleString()}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-600">Parts Dues</span>
                            <span className="text-slate-900">₹{selectedCase.financialData.partsDues.toLocaleString()}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-600">Advances Given</span>
                            <span className="text-slate-900">₹{selectedCase.financialData.advancesGiven.toLocaleString()}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-600">Penalties</span>
                            <span className="text-slate-900">₹{selectedCase.financialData.penalties.toLocaleString()}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-600">Other Charges</span>
                            <span className="text-slate-900">₹{selectedCase.financialData.otherCharges.toLocaleString()}</span>
                          </div>
                          <div className="pt-2 border-t border-red-300">
                            <div className="flex justify-between">
                              <span className="text-slate-900">Total Receivables</span>
                              <span className="text-slate-900 text-lg">₹{settlement.receivables.toLocaleString()}</span>
                            </div>
                          </div>
                        </CardContent>
                      </Card>

                      {/* Deductions */}
                      <Card className="border-amber-200 bg-amber-50">
                        <CardHeader>
                          <CardTitle className="text-base flex items-center gap-2">
                            <AlertCircle className="w-5 h-5 text-amber-600" />
                            Deductions
                          </CardTitle>
                        </CardHeader>
                        <CardContent>
                          <div className="flex justify-between">
                            <span className="text-slate-600">Warranty Claims Pending</span>
                            <span className="text-slate-900 text-lg">₹{selectedCase.financialData.warrantyPending.toLocaleString()}</span>
                          </div>
                        </CardContent>
                      </Card>

                      {/* Net Settlement */}
                      <Card className={`${
                        settlement.settlementType === 'Payable to Dealer'
                          ? 'border-red-300 bg-red-100'
                          : 'border-green-300 bg-green-100'
                      }`}>
                        <CardHeader>
                          <CardTitle className="text-base">Net Settlement</CardTitle>
                        </CardHeader>
                        <CardContent>
                          <div className="text-center py-4">
                            <div className="flex items-center justify-center gap-3 mb-2">
                              {settlement.settlementType === 'Payable to Dealer' ? (
                                <TrendingDown className="w-6 h-6 text-red-600" />
                              ) : (
                                <TrendingUp className="w-6 h-6 text-green-600" />
                              )}
                              <span className={`text-lg ${
                                settlement.settlementType === 'Payable to Dealer' ? 'text-red-700' : 'text-green-700'
                              }`}>
                                {settlement.settlementType}
                              </span>
                            </div>
                            <div className="text-3xl text-slate-900">
                              ₹{settlement.settlementAmount.toLocaleString()}
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    </>
                  );
                })()}
              </TabsContent>
            </Tabs>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailsDialog(false)}>
              Close
            </Button>
            {selectedCase?.status === 'Pending Finance Review' && (
              <Button
                className="bg-amber-600 hover:bg-amber-700"
                onClick={() => {
                  setShowDetailsDialog(false);
                  handleReviewCase(selectedCase);
                }}
              >
                Review & Settle
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

