"use client";

import { API_BASE_URL, getAuthHeaders } from "@/lib/api";
import React, { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Progress } from "@/components/ui/progress";
import { AlertCircle, Target, Briefcase, FileText, CheckCircle2, Loader2, Printer, Plus, Trash2, Edit2, ArrowLeft, Clock, ExternalLink } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import Link from "next/link";

export default function ContractsPage() {
    const [contracts, setContracts] = useState<any[]>([]);
    const [installments, setInstallments] = useState<any[]>([]);
    const [clients, setClients] = useState<any[]>([]);
    const [assets, setAssets] = useState<any[]>([]);
    const [users, setUsers] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [deleteTarget, setDeleteTarget] = useState<any>(null);
    const [isDeleting, setIsDeleting] = useState(false);

    // Dialog Form State
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [formData, setFormData] = useState({
        client: "",
        asset: "",
        start_date: new Date().toISOString().split('T')[0],
        end_date: "",
        total_price: "",
        down_payment: "",
        installment_count: "",
        installment_frequency: "monthly",
        status: "active",
        assigned_sales_agent: "",
        terms: "",
        notes: ""
    });

    const fetchData = async () => {
        try {
            setLoading(true);
            const [contractsRes, installmentsRes, clientsRes, assetsRes, usersRes] = await Promise.all([
                fetch(`${API_BASE_URL}/contracts/`, { headers: getAuthHeaders() }),
                fetch(`${API_BASE_URL}/installments/`, { headers: getAuthHeaders() }),
                fetch(`${API_BASE_URL}/clients/`, { headers: getAuthHeaders() }),
                fetch(`${API_BASE_URL}/assets/`, { headers: getAuthHeaders() }),
                fetch(`${API_BASE_URL}/users/`, { headers: getAuthHeaders() })
            ]);

            const cData = await contractsRes.json();
            const iData = await installmentsRes.json();
            const clData = await clientsRes.json();
            const aData = await assetsRes.json();
            const uData = await usersRes.json();

            setContracts(cData.results || cData);
            setInstallments(iData.results || iData);
            setClients(clData.results || clData);
            setAssets(aData.results || aData);
            setUsers(uData.results || uData);

            setLoading(false);
        } catch (err) {
            console.error("Dashboard fetch error:", err);
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    const handleCreateContract = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsSubmitting(true);
        try {
            const res = await fetch(`${API_BASE_URL}/contracts/`, {
                method: "POST",
                headers: getAuthHeaders(),
                body: JSON.stringify({
                    client: formData.client,
                    asset: formData.asset,
                    start_date: formData.start_date,
                    end_date: formData.end_date,
                    total_price: parseFloat(formData.total_price),
                    down_payment: parseFloat(formData.down_payment || "0"),
                    installment_count: parseInt(formData.installment_count),
                    installment_frequency: formData.installment_frequency,
                    status: formData.status,
                    assigned_sales_agent: formData.assigned_sales_agent || null,
                    terms: formData.terms,
                    notes: formData.notes
                })
            });

            if (res.ok) {
                setIsDialogOpen(false);
                setFormData({
                    client: "", asset: "", start_date: "", end_date: "",
                    total_price: "", down_payment: "", installment_count: "",
                    installment_frequency: "monthly", status: "active",
                    assigned_sales_agent: "", terms: "", notes: ""
                });
                await fetchData();
            } else {
                const errorText = await res.text();
                console.error("Creation failed:", errorText);
                alert("Failed: " + errorText);
            }
        } catch (err) {
            console.error(err);
        } finally {
            setIsSubmitting(false);
        }
    };

    const getContractProgress = (contractId: string | number, totalPrice: number) => {
        const contractInstallments = installments.filter(i =>
            i.contract === contractId || (i.contract && i.contract.id === contractId)
        );

        const paidInstallmentsSum = contractInstallments
            .filter(i => i.status === 'paid')
            .reduce((sum, curr) => sum + parseFloat(curr.amount), 0);

        // Note: Backend 'down_payment' should act as paid base technically, but for visual simplicity we just sum paid installments
        const percent = totalPrice > 0 ? (paidInstallmentsSum / totalPrice) * 100 : 0;

        return {
            paidAmount: paidInstallmentsSum,
            percentage: Math.min(percent, 100)
        };
    };

    const getOverdueStatus = (contractId: string | number) => {
        const contractInstallments = installments.filter(i =>
            i.contract === contractId || (i.contract && i.contract.id === contractId)
        );
        const overdues = contractInstallments.filter(i => {
            const due = new Date(i.due_date);
            return i.status !== 'paid' && due < new Date();
        });
        return overdues;
    };

    if (loading) return <div className="p-12 text-center animate-pulse text-slate-500 font-semibold text-lg">Initializing Installment Logic Engine...</div>;

    const delinquentContracts = contracts.filter(c => getOverdueStatus(c.id).length > 0);
    const activeContracts = contracts.filter(c => getOverdueStatus(c.id).length === 0 && c.status !== 'completed');
    const completedContracts = contracts.filter(c => c.status === 'completed');

    const deleteContract = async () => {
        if (!deleteTarget) return;
        setIsDeleting(true);
        try {
            const res = await fetch(`${API_BASE_URL}/contracts/${deleteTarget.id}/`, {
                method: "DELETE",
                headers: getAuthHeaders(),
            });
            if (res.ok || res.status === 204) {
                setContracts(prev => prev.filter(c => c.id !== deleteTarget.id));
                setDeleteTarget(null);
            } else {
                alert("Delete failed: " + (await res.text()));
            }
        } catch (e) {
            alert("Network error");
        } finally {
            setIsDeleting(false);
        }
    };

    return (
        <>
            <div className="flex-1 space-y-6 pb-12">
                <div className="flex flex-col md:flex-row items-start md:items-center justify-between space-y-2 md:space-y-0">
                    <div>
                        <h2 className="text-3xl font-bold tracking-tight">Active Contracts & Collections</h2>
                        <p className="text-muted-foreground mt-1 text-sm">
                            Monitor client payment health, verify installment progress, and draft contracts.
                        </p>
                    </div>

                    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                        <DialogTrigger asChild>
                            <Button className="bg-primary hover:bg-primary/90 shadow-lg text-primary-foreground font-bold rounded-xl px-6 transition-all active:scale-95">
                                <Plus className="w-4 h-4 mr-2" /> Draft New Contract
                            </Button>
                        </DialogTrigger>
                        <DialogContent className="sm:max-w-[600px] overflow-y-auto max-h-[90vh]">
                            <DialogHeader>
                                <DialogTitle>Draft New Contract</DialogTitle>
                                <DialogDescription>Initialize a new installment agreement between a client and an asset plot.</DialogDescription>
                            </DialogHeader>
                            <form onSubmit={handleCreateContract} className="space-y-4 py-4">
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label>Client</Label>
                                        <Select required value={formData.client} onValueChange={v => setFormData({ ...formData, client: v })}>
                                            <SelectTrigger><SelectValue placeholder="Select Client" /></SelectTrigger>
                                            <SelectContent>
                                                {clients.map(c => <SelectItem key={c.id} value={String(c.id)}>{c.first_name} {c.last_name}</SelectItem>)}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                    <div className="space-y-2">
                                        <Label>Asset / Plot</Label>
                                        <Select required value={formData.asset} onValueChange={(v) => {
                                            const selectedAsset = assets.find(a => String(a.id) === v);
                                            setFormData({
                                                ...formData,
                                                asset: v,
                                                total_price: selectedAsset ? selectedAsset.price : formData.total_price
                                            });
                                        }}>
                                            <SelectTrigger><SelectValue placeholder="Select Asset" /></SelectTrigger>
                                            <SelectContent>
                                                {assets.map(a => <SelectItem key={a.id} value={String(a.id)}>{a.name} - {a.formatted_price}</SelectItem>)}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label>Start Date</Label>
                                        <Input type="date" required value={formData.start_date} onChange={e => setFormData({ ...formData, start_date: e.target.value })} />
                                    </div>
                                    <div className="space-y-2">
                                        <Label>End Date</Label>
                                        <Input type="date" required value={formData.end_date} onChange={e => setFormData({ ...formData, end_date: e.target.value })} />
                                    </div>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label>Total Price (₦)</Label>
                                        <Input type="number" step="0.01" required value={formData.total_price} onChange={e => setFormData({ ...formData, total_price: e.target.value })} />
                                    </div>
                                    <div className="space-y-2">
                                        <Label>Down Payment (₦)</Label>
                                        <Input type="number" step="0.01" value={formData.down_payment} onChange={e => setFormData({ ...formData, down_payment: e.target.value })} />
                                    </div>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label>Total Number of Installments</Label>
                                        <Input type="number" min="1" required value={formData.installment_count} onChange={e => setFormData({ ...formData, installment_count: e.target.value })} />
                                    </div>
                                    <div className="space-y-2">
                                        <Label>Payment Frequency</Label>
                                        <Select required value={formData.installment_frequency} onValueChange={v => setFormData({ ...formData, installment_frequency: v })}>
                                            <SelectTrigger><SelectValue placeholder="Frequency" /></SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="monthly">Monthly</SelectItem>
                                                <SelectItem value="biweekly">Bi-weekly</SelectItem>
                                                <SelectItem value="weekly">Weekly</SelectItem>
                                            </SelectContent>
                                        </Select>
                                    </div>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label>Assigned Agent</Label>
                                        <Select value={formData.assigned_sales_agent} onValueChange={v => setFormData({ ...formData, assigned_sales_agent: v })}>
                                            <SelectTrigger><SelectValue placeholder="Internal Agent" /></SelectTrigger>
                                            <SelectContent>
                                                {users.map(u => <SelectItem key={u.id} value={String(u.id)}>{u.first_name} {u.last_name} (@{u.username})</SelectItem>)}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                    <div className="space-y-2">
                                        <Label>Contract Status</Label>
                                        <Select required value={formData.status} onValueChange={v => setFormData({ ...formData, status: v })}>
                                            <SelectTrigger><SelectValue placeholder="Status" /></SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="draft">Draft (Negotiation)</SelectItem>
                                                <SelectItem value="active">Active (Collecting)</SelectItem>
                                                <SelectItem value="completed">Completed (Closed)</SelectItem>
                                            </SelectContent>
                                        </Select>
                                    </div>
                                </div>

                                <div className="space-y-2">
                                    <Label>Terms & Conditions</Label>
                                    <Textarea
                                        placeholder="Enter specific legal terms or riders..."
                                        className="h-20"
                                        value={formData.terms}
                                        onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setFormData({ ...formData, terms: e.target.value })}
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label>Internal Notes</Label>
                                    <Textarea
                                        placeholder="Private staff observations..."
                                        className="h-20"
                                        value={formData.notes}
                                        onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setFormData({ ...formData, notes: e.target.value })}
                                    />
                                </div>

                                <DialogFooter className="pt-4">
                                    <Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>Cancel</Button>
                                    <Button type="submit" disabled={isSubmitting} className="bg-indigo-600 hover:bg-indigo-700 text-white">
                                        {isSubmitting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null} Create & Auto-Generate Invoices
                                    </Button>
                                </DialogFooter>
                            </form>
                        </DialogContent>
                    </Dialog>
                </div>

                {/* KPI Cards */}
                <div className="grid gap-6 md:grid-cols-3">
                    <Card className="rounded-2xl shadow-card border-none bg-card hover:translate-y-[-2px] transition-transform duration-300">
                        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2 border-b border-border/10 bg-muted/5 rounded-t-2xl">
                            <CardTitle className="text-sm font-bold uppercase tracking-wider text-muted-foreground">Healthy Portfolios</CardTitle>
                            <div className="p-2 bg-emerald-500/10 rounded-lg">
                                <Briefcase className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
                            </div>
                        </CardHeader>
                        <CardContent className="pt-6">
                            <div className="text-3xl font-black">{activeContracts.length}</div>
                            <div className="text-[10px] font-bold uppercase text-emerald-600 dark:text-emerald-400 mt-2 flex items-center gap-1.5">
                                <div className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
                                Paying on schedule
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="rounded-2xl shadow-card border-none bg-card relative overflow-hidden group hover:translate-y-[-2px] transition-transform duration-300">
                        <div className="absolute top-0 left-0 w-1.5 h-full bg-red-500"></div>
                        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2 border-b border-border/10 bg-muted/5 rounded-tr-2xl">
                            <CardTitle className="text-sm font-bold uppercase tracking-wider text-red-600 dark:text-red-400">Collections Default Risk</CardTitle>
                            <div className="p-2 bg-red-500/10 rounded-lg">
                                <AlertCircle className="h-4 w-4 text-red-600" />
                            </div>
                        </CardHeader>
                        <CardContent className="pt-6">
                            <div className="text-3xl font-black text-red-600 dark:text-red-400">{delinquentContracts.length}</div>
                            <p className="text-[10px] font-bold uppercase text-muted-foreground mt-2">Contracts requiring intervention</p>
                        </CardContent>
                    </Card>

                    <Card className="rounded-2xl shadow-card border-none bg-card hover:translate-y-[-2px] transition-transform duration-300">
                        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2 border-b border-border/10 bg-muted/5 rounded-t-2xl">
                            <CardTitle className="text-sm font-bold uppercase tracking-wider text-muted-foreground">Assets Fully Vested</CardTitle>
                            <div className="p-2 bg-blue-500/10 rounded-lg">
                                <Target className="h-4 w-4 text-blue-600 dark:text-blue-400" />
                            </div>
                        </CardHeader>
                        <CardContent className="pt-6">
                            <div className="text-3xl font-black">{completedContracts.length}</div>
                            <div className="text-[10px] font-bold uppercase text-blue-600 dark:text-blue-400 mt-2 flex items-center gap-1.5">
                                <div className="h-1.5 w-1.5 rounded-full bg-blue-500" />
                                100% payments completed
                            </div>
                        </CardContent>
                    </Card>
                </div>

                {/* Main Intelligent Display Tabs */}
                <Card className="rounded-3xl shadow-card border-none bg-card overflow-hidden">
                    <Tabs defaultValue="active" className="flex-1 flex flex-col">
                        <div className="bg-muted/10 border-b px-4 mt-2">
                            <TabsList className="bg-transparent h-16 gap-2">
                                <TabsTrigger value="active" className="data-[state=active]:bg-background data-[state=active]:shadow-sm h-11 px-6 rounded-xl text-sm font-bold transition-all flex items-center">
                                    <Briefcase className="w-4 h-4 mr-2" /> Active Health ({activeContracts.length})
                                </TabsTrigger>
                                <TabsTrigger value="collections" className="data-[state=active]:bg-red-500/10 data-[state=active]:text-red-600 h-11 px-6 rounded-xl text-sm font-bold transition-all flex items-center">
                                    <AlertCircle className="w-4 h-4 mr-2" /> Outstanding Collections
                                </TabsTrigger>
                                <TabsTrigger value="completed" className="data-[state=active]:bg-emerald-500/10 data-[state=active]:text-emerald-600 h-11 px-6 rounded-xl text-sm font-bold transition-all flex items-center">
                                    <CheckCircle2 className="w-4 h-4 mr-2" /> Fully Paid Sets
                                </TabsTrigger>
                            </TabsList>
                        </div>

                        <TabsContent value="active" className="p-0 m-0 outline-none">
                            <Table>
                                <TableHeader className="bg-muted/5">
                                    <TableRow className="hover:bg-transparent border-b">
                                        <TableHead className="w-[140px] font-bold uppercase text-[10px] tracking-widest">Ref Number</TableHead>
                                        <TableHead className="font-bold uppercase text-[10px] tracking-widest">Asset &amp; Client</TableHead>
                                        <TableHead className="w-[200px] font-bold uppercase text-[10px] tracking-widest">Vesting Progress</TableHead>
                                        <TableHead className="font-bold uppercase text-[10px] tracking-widest">Financials</TableHead>
                                        <TableHead className="text-right font-bold uppercase text-[10px] tracking-widest">Balance Due</TableHead>
                                        <TableHead className="text-right font-bold uppercase text-[10px] tracking-widest">Action</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {activeContracts.length === 0 ? <TableRow><TableCell colSpan={5} className="h-24 text-center">No active contracts found.</TableCell></TableRow> :
                                        activeContracts.map(c => {
                                            const progress = getContractProgress(c.id, c.total_price);
                                            const asset = typeof c.asset === 'object' ? c.asset : assets.find(a => a.id === c.asset);
                                            const client = typeof c.client === 'object' ? c.client : clients.find(cl => cl.id === c.client);
                                            const nextDue = installments.find(inst => (inst.contract === c.id || inst.contract?.id === c.id) && inst.status !== 'paid');

                                            return (
                                                <TableRow key={c.id} className="border-b">
                                                    <TableCell className="font-bold text-foreground">
                                                        <Link href={`/contracts/${c.id}`} className="hover:text-primary hover:underline">
                                                            {c.contract_number || `#${c.id}`}
                                                        </Link>
                                                    </TableCell>
                                                    <TableCell>
                                                        <div className="font-bold text-foreground">{asset?.name || `Asset ID: ${c.asset}`}</div>
                                                        <div className="text-[11px] text-muted-foreground">{client?.full_name || client?.first_name || `Client ID: ${c.client}`}</div>
                                                    </TableCell>
                                                    <TableCell>
                                                        <div className="space-y-2">
                                                            <div className="flex justify-between text-[11px] font-black text-muted-foreground">
                                                                <span>{progress.percentage.toFixed(0)}% VESTED</span>
                                                            </div>
                                                            <Progress value={progress.percentage} className="h-1.5" style={{ "--tw-progress": "var(--dynamic-primary, #10b981)" } as any} />
                                                            <p className="text-[10px] font-medium text-muted-foreground">Next Payment: {nextDue ? new Date(nextDue.due_date).toLocaleDateString() : 'None'}</p>
                                                        </div>
                                                    </TableCell>
                                                    <TableCell>
                                                        <div className="text-[11px] space-y-1">
                                                            <div className="flex justify-between gap-4"><span>VALUE:</span><span className="font-bold">₦{parseFloat(c.total_price).toLocaleString()}</span></div>
                                                            <div className="flex justify-between gap-4 text-emerald-600 dark:text-emerald-400"><span>PAID:</span><span className="font-bold">₦{parseFloat(c.total_paid || progress.paidAmount).toLocaleString()}</span></div>
                                                        </div>
                                                    </TableCell>
                                                    <TableCell className="text-right font-black text-rose-600 dark:text-rose-400 text-base">
                                                        ₦{(parseFloat(c.total_price) - (parseFloat(c.total_paid || progress.paidAmount))).toLocaleString()}
                                                    </TableCell>
                                                    <TableCell className="text-right">
                                                        <div className="flex items-center justify-end gap-1">
                                                            <Link href={`/contracts/${c.id}`}>
                                                                <Button size="sm" variant="outline" className="rounded-xl font-black uppercase text-[10px] tracking-widest border-primary/20 text-primary hover:bg-primary hover:text-white transition-all">
                                                                    <ExternalLink className="h-3 w-3 mr-1.5" /> View
                                                                </Button>
                                                            </Link>
                                                            <Button size="sm" variant="ghost" className="h-8 w-8 p-0 rounded-lg text-muted-foreground hover:text-rose-500 hover:bg-rose-500/10" onClick={() => setDeleteTarget(c)}>
                                                                <Trash2 className="h-3.5 w-3.5" />
                                                            </Button>
                                                        </div>
                                                    </TableCell>
                                                </TableRow>
                                            )
                                        })}
                                </TableBody>
                            </Table>
                        </TabsContent>

                        <TabsContent value="collections" className="p-0 m-0 outline-none">
                            <Table>
                                <TableHeader className="bg-red-500/10">
                                    <TableRow className="hover:bg-transparent border-b">
                                        <TableHead className="w-[140px] font-bold uppercase text-[10px] tracking-widest text-red-600">Ref Number</TableHead>
                                        <TableHead className="font-bold uppercase text-[10px] tracking-widest text-red-600">Delinquency Status</TableHead>
                                        <TableHead className="font-bold uppercase text-[10px] tracking-widest text-red-600">Recovery Progress</TableHead>
                                        <TableHead className="text-right font-bold uppercase text-[10px] tracking-widest text-red-600">Actions</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {delinquentContracts.length === 0 ? <TableRow><TableCell colSpan={4} className="h-24 text-center text-emerald-600 font-semibold gap-2"><CheckCircle2 className="w-5 h-5 inline mr-2" />Zero delinquencies found! Your portfolio is perfectly healthy.</TableCell></TableRow> :
                                        delinquentContracts.map(c => {
                                            const progress = getContractProgress(c.id, c.total_price);
                                            const overdues = getOverdueStatus(c.id);
                                            const asset = typeof c.asset === 'object' ? c.asset : assets.find(a => a.id === c.asset);
                                            const client = typeof c.client === 'object' ? c.client : clients.find(cl => cl.id === c.client);
                                            return (
                                                <TableRow key={c.id} className="bg-red-500/5 hover:bg-red-500/10 transition-colors border-b">
                                                    <TableCell className="font-black text-foreground">
                                                        <Link href={`/contracts/${c.id}`} className="hover:text-red-600 hover:underline">
                                                            {c.contract_number || `#${c.id}`}
                                                        </Link>
                                                    </TableCell>
                                                    <TableCell>
                                                        <Badge variant="destructive" className="bg-red-500 text-white border-none font-bold text-[10px]">
                                                            {overdues.length} OVERDUE
                                                        </Badge>
                                                        <p className="text-sm font-black text-foreground mt-2">{asset?.name}</p>
                                                        <p className="text-[11px] text-muted-foreground font-medium">{client?.full_name}</p>
                                                        <p className="text-[10px] text-red-500 font-bold mt-2 uppercase">LATEST MISSED: {new Date(overdues[0].due_date).toLocaleDateString()}</p>
                                                    </TableCell>
                                                    <TableCell>
                                                        <div className="space-y-2 max-w-[250px]">
                                                            <div className="flex justify-between text-[10px] font-black text-red-600">
                                                                <span className="uppercase">DELAYED AT {progress.percentage.toFixed(0)}%</span>
                                                            </div>
                                                            <Progress value={progress.percentage} className="h-1.5 bg-red-500/20 [&>div]:bg-red-500" />
                                                        </div>
                                                    </TableCell>
                                                    <TableCell className="text-right space-x-2">
                                                        <Link href={`/contracts/${c.id}`}>
                                                            <Button size="sm" variant="outline" className="rounded-xl font-black uppercase text-[10px] border-primary/20 text-primary hover:bg-primary hover:text-white transition-all">
                                                                <ExternalLink className="h-3 w-3 mr-1" /> View
                                                            </Button>
                                                        </Link>
                                                        <Button size="sm" variant="outline" className="border-red-500/20 text-red-600 hover:bg-red-500/10 rounded-lg text-[11px] font-bold">Issue Warning</Button>
                                                        <Button size="sm" className="bg-red-600 hover:bg-red-700 text-white rounded-lg text-[11px] font-bold">Default Protocol</Button>
                                                    </TableCell>
                                                </TableRow>
                                            )
                                        })}
                                </TableBody>
                            </Table>
                        </TabsContent>

                        <TabsContent value="completed" className="p-0 m-0 outline-none">
                            <Table>
                                <TableHeader className="bg-emerald-500/10">
                                    <TableRow className="hover:bg-transparent border-b">
                                        <TableHead className="w-[140px] font-bold uppercase text-[10px] tracking-widest text-emerald-600">Ref Number</TableHead>
                                        <TableHead className="font-bold uppercase text-[10px] tracking-widest text-emerald-600">Closed Asset &amp; Client</TableHead>
                                        <TableHead className="w-[300px] font-bold uppercase text-[10px] tracking-widest text-emerald-600">Closure Summary</TableHead>
                                        <TableHead className="text-right font-bold uppercase text-[10px] tracking-widest text-emerald-600">Final Value</TableHead>
                                        <TableHead className="text-right font-bold uppercase text-[10px] tracking-widest text-emerald-600">Action</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {completedContracts.length === 0 ? <TableRow><TableCell colSpan={4} className="h-24 text-center text-muted-foreground font-medium">No completed contracts found.</TableCell></TableRow> :
                                        completedContracts.map(c => {
                                            const asset = typeof c.asset === 'object' ? c.asset : assets.find(a => a.id === c.asset);
                                            const client = typeof c.client === 'object' ? c.client : clients.find(cl => cl.id === c.client);
                                            return (
                                                <TableRow key={c.id} className="hover:bg-emerald-500/5 transition-colors border-b">
                                                    <TableCell className="font-black text-foreground">
                                                        <Link href={`/contracts/${c.id}`} className="hover:text-emerald-600 hover:underline">
                                                            {c.contract_number || `#${c.id}`}
                                                        </Link>
                                                    </TableCell>
                                                    <TableCell>
                                                        <div className="font-bold text-foreground">{asset?.name || `Asset ID: ${c.asset}`}</div>
                                                        <div className="text-[11px] text-muted-foreground font-medium">{client?.full_name || client?.first_name || `Client ID: ${c.client}`}</div>
                                                    </TableCell>
                                                    <TableCell>
                                                        <div className="flex items-center text-[10px] font-black text-emerald-600 uppercase bg-emerald-500/10 w-fit px-3 py-1.5 rounded-full">
                                                            <CheckCircle2 className="w-3.5 h-3.5 mr-1.5" />
                                                            100% Fully Paid
                                                        </div>
                                                    </TableCell>
                                                    <TableCell className="text-right font-black text-foreground text-base">₦{Number(c.total_price).toLocaleString()}</TableCell>
                                                    <TableCell className="text-right">
                                                        <Link href={`/contracts/${c.id}`}>
                                                            <Button size="sm" variant="outline" className="rounded-xl font-black uppercase text-[10px] tracking-widest border-emerald-500/20 text-emerald-600 hover:bg-emerald-500 hover:text-white transition-all">
                                                                <ExternalLink className="h-3 w-3 mr-1.5" /> View
                                                            </Button>
                                                        </Link>
                                                    </TableCell>
                                                </TableRow>
                                            )
                                        })}
                                </TableBody>
                            </Table>
                        </TabsContent>

                    </Tabs>
                </Card>
            </div>

            <Dialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
                <DialogContent className="sm:max-w-[400px] rounded-2xl">
                    <DialogHeader>
                        <DialogTitle className="text-rose-600 flex items-center gap-2">
                            <Trash2 className="h-5 w-5" /> Delete Contract
                        </DialogTitle>
                        <DialogDescription>
                            Permanently delete <strong>{deleteTarget?.contract_number}</strong>? All linked installments will also be removed.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter className="gap-2 pt-2">
                        <Button variant="outline" className="rounded-xl" onClick={() => setDeleteTarget(null)}>Cancel</Button>
                        <Button variant="destructive" className="rounded-xl" onClick={deleteContract} disabled={isDeleting}>
                            {isDeleting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Trash2 className="h-4 w-4 mr-2" />}
                            Yes, Delete Contract
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </>
    );
}
