/**
 * ItemsTrash — Masters → Trash / Restore page for soft-deleted items.
 *
 * Mirror of the Items list with:
 *   • Same checkbox + Select All + sticky action bar mechanics.
 *   • Two destructive actions instead of one: Restore Selected + Permanent Delete Selected.
 *   • Permanent Delete requires DOUBLE confirmation.
 *   • Search + Category filter + Deleted-Date filter.
 */
import React, { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import {
    AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
    AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
    ArrowLeft, Archive, ArchiveRestore, Trash2, X, RefreshCw, Search, CheckSquare,
} from "lucide-react";
import { toast } from "sonner";
import { api, formatApiError } from "@/lib/api";
import { useCompany } from "@/context/CompanyContext";
import { formatINR } from "@/lib/format";

export default function ItemsTrash() {
    const { activeId } = useCompany();
    const [items, setItems] = useState([]);
    const [loading, setLoading] = useState(false);
    const [q, setQ] = useState("");
    const [cat, setCat] = useState("__all__");
    const [days, setDays] = useState("all");
    const [selectedIds, setSelectedIds] = useState(() => new Set());
    const [confirmRestoreOpen, setConfirmRestoreOpen] = useState(false);
    const [confirmPurgeOpen, setConfirmPurgeOpen] = useState(false);
    const [confirmPurgeStage2, setConfirmPurgeStage2] = useState(false);

    const load = async () => {
        if (!activeId) return;
        setLoading(true);
        try {
            const { data } = await api.get("/items-trash", { params: { company_id: activeId } });
            setItems(data || []);
            setSelectedIds(new Set());
        } catch (e) { toast.error(formatApiError(e.response?.data?.detail) || "Failed to load trash"); }
        finally { setLoading(false); }
    };
    useEffect(() => { load(); }, [activeId]); // eslint-disable-line react-hooks/exhaustive-deps

    const categories = useMemo(() => {
        const set = new Set(items.map((i) => i.category || "").filter(Boolean));
        return Array.from(set).sort();
    }, [items]);

    const filtered = useMemo(() => {
        const Q = q.toLowerCase().trim();
        const nowMs = Date.now();
        return items.filter((i) => {
            if (cat && cat !== "__all__" && (i.category || "") !== cat) return false;
            if (Q) {
                const hay = `${i.name || ""} ${i.code || ""} ${i.barcode || ""} ${i.hsn || ""}`.toLowerCase();
                if (!hay.includes(Q)) return false;
            }
            if (days !== "all" && i.deleted_at) {
                const d = new Date(i.deleted_at).getTime();
                const cutoff = nowMs - parseInt(days, 10) * 86400000;
                if (d < cutoff) return false;
            }
            return true;
        });
    }, [items, q, cat, days]);

    const toggleId = (id) => setSelectedIds((s) => {
        const n = new Set(s);
        if (n.has(id)) n.delete(id); else n.add(id);
        return n;
    });
    const allSelected = filtered.length > 0 && filtered.every((it) => selectedIds.has(it.id));
    const toggleAll = (v) => {
        if (v) setSelectedIds(new Set([...selectedIds, ...filtered.map((it) => it.id)]));
        else setSelectedIds(new Set([...selectedIds].filter((id) => !filtered.find((it) => it.id === id))));
    };
    const clearSelection = () => setSelectedIds(new Set());

    const restoreSelected = async () => {
        setConfirmRestoreOpen(false);
        const ids = Array.from(selectedIds);
        if (!ids.length) return;
        try {
            const { data } = await api.post("/items/bulk-restore", { ids });
            toast.success(`${data.restored} item${data.restored === 1 ? "" : "s"} restored`);
            clearSelection();
            load();
        } catch (e) { toast.error(formatApiError(e.response?.data?.detail) || "Bulk restore failed"); }
    };

    const restoreOne = async (id) => {
        try {
            await api.post(`/items/${id}/restore`);
            toast.success("Item restored");
            load();
        } catch (e) { toast.error(formatApiError(e.response?.data?.detail) || "Restore failed"); }
    };

    const purgeSelected = async () => {
        setConfirmPurgeStage2(false);
        const ids = Array.from(selectedIds);
        if (!ids.length) return;
        try {
            const { data } = await api.post("/items-trash/bulk-purge", { ids });
            toast.success(`${data.purged} item${data.purged === 1 ? "" : "s"} permanently deleted`);
            clearSelection();
            load();
        } catch (e) { toast.error(formatApiError(e.response?.data?.detail) || "Permanent delete failed"); }
    };

    const purgeOne = async (id) => {
        if (!window.confirm("Permanently delete this item? This cannot be undone.")) return;
        try {
            await api.delete(`/items-trash/${id}`);
            toast.success("Permanently deleted");
            load();
        } catch (e) { toast.error(formatApiError(e.response?.data?.detail) || "Delete failed"); }
    };

    return (
        <div className="space-y-4" data-testid="items-trash-page">
            <div className="flex flex-wrap items-center justify-between gap-3">
                <div className="flex items-center gap-3">
                    <Button asChild size="sm" variant="ghost"><Link to="/items"><ArrowLeft className="h-4 w-4 mr-1" /> Back to Items</Link></Button>
                    <div>
                        <div className="label-cap flex items-center gap-1.5"><Archive className="h-3.5 w-3.5" /> Masters · Trash</div>
                        <h1 className="font-display text-2xl md:text-3xl font-bold tracking-tight">Items Trash / Restore</h1>
                        <p className="text-sm text-muted-foreground mt-1">Soft-deleted items. Restore karne se woh wapas Items list mein aa jayenge with full data intact.</p>
                    </div>
                </div>
                <Button size="sm" variant="outline" onClick={load}><RefreshCw className="h-4 w-4 mr-1.5" /> Refresh</Button>
            </div>

            <Card>
                <CardContent className="p-0">
                    {/* Sticky bulk-action bar */}
                    {selectedIds.size > 0 && (
                        <div
                            className="sticky top-0 z-20 border-b border-amber-500/30 bg-amber-50 dark:bg-amber-950/40 px-4 py-2.5 flex items-center justify-between gap-3"
                            data-testid="trash-bulk-actionbar"
                        >
                            <div className="text-sm font-medium text-amber-700 dark:text-amber-300 flex items-center gap-2">
                                <CheckSquare className="h-4 w-4" /> {selectedIds.size} selected
                            </div>
                            <div className="flex items-center gap-2">
                                <Button size="sm" onClick={() => setConfirmRestoreOpen(true)} className="bg-emerald-600 hover:bg-emerald-700" data-testid="trash-bulk-restore-btn">
                                    <ArchiveRestore className="h-3.5 w-3.5 mr-1.5" /> Restore Selected
                                </Button>
                                <Button size="sm" variant="destructive" onClick={() => setConfirmPurgeOpen(true)} data-testid="trash-bulk-purge-btn">
                                    <Trash2 className="h-3.5 w-3.5 mr-1.5" /> Permanently Delete
                                </Button>
                                <Button size="sm" variant="outline" onClick={clearSelection} data-testid="trash-bulk-cancel-btn">
                                    <X className="h-3.5 w-3.5 mr-1.5" /> Cancel
                                </Button>
                            </div>
                        </div>
                    )}

                    {/* Toolbar */}
                    <div className="flex flex-wrap items-center justify-between gap-3 p-4 border-b border-border">
                        <div className="text-sm text-muted-foreground">
                            Showing {filtered.length} of {items.length} trashed item{items.length === 1 ? "" : "s"}
                        </div>
                        <div className="flex items-center gap-2 flex-wrap">
                            <Select value={cat} onValueChange={setCat}>
                                <SelectTrigger className="h-8 w-40 text-xs" data-testid="trash-category-filter"><SelectValue placeholder="All categories" /></SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="__all__">All categories</SelectItem>
                                    {categories.map((c) => <SelectItem key={c} value={c}>{c}</SelectItem>)}
                                </SelectContent>
                            </Select>
                            <Select value={days} onValueChange={setDays}>
                                <SelectTrigger className="h-8 w-36 text-xs" data-testid="trash-days-filter"><SelectValue /></SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">Any time</SelectItem>
                                    <SelectItem value="1">Last 24h</SelectItem>
                                    <SelectItem value="7">Last 7 days</SelectItem>
                                    <SelectItem value="30">Last 30 days</SelectItem>
                                    <SelectItem value="90">Last 90 days</SelectItem>
                                </SelectContent>
                            </Select>
                            <div className="relative">
                                <Search className="h-4 w-4 absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground" />
                                <Input
                                    placeholder="Search name / code / barcode / HSN…"
                                    value={q}
                                    onChange={(e) => setQ(e.target.value)}
                                    className="pl-8 h-8 text-xs w-64"
                                    data-testid="trash-search"
                                />
                            </div>
                        </div>
                    </div>

                    <div className="overflow-x-auto">
                        <table className="w-full dense-table text-sm" data-testid="trash-table">
                            <thead className="bg-muted/40">
                                <tr className="text-left text-[10px] tracking-wider uppercase text-muted-foreground">
                                    <th className="pl-5 py-2.5 w-10">
                                        <Checkbox checked={allSelected} onCheckedChange={toggleAll} aria-label="Select all" data-testid="trash-select-all" />
                                    </th>
                                    <th>Item Name</th>
                                    <th>Code / Barcode</th>
                                    <th>Category</th>
                                    <th>HSN · GST</th>
                                    <th className="text-right">Sale Price</th>
                                    <th>Deleted Date</th>
                                    <th>Deleted By</th>
                                    <th className="text-right pr-5">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {loading ? (
                                    <tr><td colSpan={9} className="p-8 text-center text-muted-foreground">Loading trash…</td></tr>
                                ) : filtered.length === 0 ? (
                                    <tr><td colSpan={9} className="p-12 text-center text-muted-foreground">
                                        {items.length === 0 ? "Trash is empty — koi deleted item nahi hai." : "No items match your filter."}
                                    </td></tr>
                                ) : filtered.map((i) => {
                                    const isSel = selectedIds.has(i.id);
                                    return (
                                        <tr key={i.id} className={`border-t border-border hover:bg-muted/20 ${isSel ? "bg-amber-50/50 dark:bg-amber-950/30" : ""}`}>
                                            <td className="pl-5 py-1.5" onClick={(e) => e.stopPropagation()}>
                                                <Checkbox checked={isSel} onCheckedChange={() => toggleId(i.id)} data-testid={`select-trash-${i.id}`} />
                                            </td>
                                            <td className="font-medium">{i.name}</td>
                                            <td className="font-mono text-xs">
                                                <div>{i.code || "—"}</div>
                                                {i.barcode && <div className="text-[10px] text-muted-foreground">{i.barcode}</div>}
                                            </td>
                                            <td className="text-xs">{i.category || "—"}</td>
                                            <td className="text-xs">
                                                <span className="font-mono">{i.hsn || "—"}</span>
                                                <Badge variant="secondary" className="ml-1.5 text-[9px]">{i.gst_rate || 0}%</Badge>
                                            </td>
                                            <td className="text-right num">{formatINR(i.sale_price || 0)}</td>
                                            <td className="text-xs text-muted-foreground">
                                                {i.deleted_at ? new Date(i.deleted_at).toLocaleString() : "—"}
                                            </td>
                                            <td className="text-xs text-muted-foreground">{i.deleted_by || "—"}</td>
                                            <td className="pr-5 text-right">
                                                <Button size="sm" variant="ghost" className="h-7 text-emerald-700 dark:text-emerald-400 hover:bg-emerald-500/10" onClick={() => restoreOne(i.id)} data-testid={`restore-${i.id}`}>
                                                    <ArchiveRestore className="h-3.5 w-3.5 mr-1" /> Restore
                                                </Button>
                                                <Button size="sm" variant="ghost" className="h-7 text-destructive hover:bg-destructive/10" onClick={() => purgeOne(i.id)} data-testid={`purge-${i.id}`}>
                                                    <Trash2 className="h-3.5 w-3.5" />
                                                </Button>
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                </CardContent>
            </Card>

            {/* Restore confirmation */}
            <AlertDialog open={confirmRestoreOpen} onOpenChange={setConfirmRestoreOpen}>
                <AlertDialogContent data-testid="confirm-bulk-restore-dialog">
                    <AlertDialogHeader>
                        <AlertDialogTitle>Restore {selectedIds.size} item{selectedIds.size === 1 ? "" : "s"}?</AlertDialogTitle>
                        <AlertDialogDescription>
                            Selected items will move back to Items & Stock with full data intact (stock, price, GST, HSN preserved).
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction onClick={restoreSelected} className="bg-emerald-600 hover:bg-emerald-700">
                            <ArchiveRestore className="h-4 w-4 mr-1.5" /> Yes, Restore
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            {/* Permanent delete — double confirmation */}
            <AlertDialog open={confirmPurgeOpen} onOpenChange={setConfirmPurgeOpen}>
                <AlertDialogContent data-testid="confirm-bulk-purge-dialog">
                    <AlertDialogHeader>
                        <AlertDialogTitle className="text-destructive">⚠ Permanently delete {selectedIds.size} item{selectedIds.size === 1 ? "" : "s"}?</AlertDialogTitle>
                        <AlertDialogDescription>
                            <strong>This cannot be undone.</strong> Items will be removed from the database forever. Linked invoice line items will still reference the item by name/HSN but the master record will be gone.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction onClick={() => { setConfirmPurgeOpen(false); setConfirmPurgeStage2(true); }} className="bg-destructive hover:bg-destructive/90">
                            Continue
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            <AlertDialog open={confirmPurgeStage2} onOpenChange={setConfirmPurgeStage2}>
                <AlertDialogContent data-testid="confirm-bulk-purge-stage2-dialog">
                    <AlertDialogHeader>
                        <AlertDialogTitle className="text-destructive">Final confirmation — really delete forever?</AlertDialogTitle>
                        <AlertDialogDescription>
                            Type-less double confirmation: clicking Yes will permanently destroy {selectedIds.size} item{selectedIds.size === 1 ? "" : "s"}. There is no way to recover them after this.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction onClick={purgeSelected} className="bg-destructive hover:bg-destructive/90" data-testid="confirm-bulk-purge-stage2-ok">
                            <Trash2 className="h-4 w-4 mr-1.5" /> Yes, Delete Forever
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}
