import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
    Dialog,
    DialogContent,
    DialogTitle,
    DialogDescription,
    DialogClose,
} from "@/components/ui/dialog";
import { StatusBadge } from "@/components/crm-data-table";
import {
    FileText,
    User,
    UserCheck,
    Calendar,
    ShoppingBag,
    Receipt,
    X,
} from "lucide-react";
import { Button } from "../ui/button";

export type OrderDetail = {
    id: number;
    order_number: string;
    order_date: string;
    status: string;
    grand_total: number | string;
    subtotal?: number | string;
    discount?: number | string;
    tax?: number | string;
    notes?: string;
    customer?: { name: string };
    sales?: { name: string };
    items?: Array<{
        id?: number;
        product_name?: string;
        product?: { name: string };
        qty: number;
        price: number | string;
        discount?: number | string;
        subtotal?: number | string;
    }>;
};

interface OrderDetailDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    order: OrderDetail | null;
}

export function OrderDetailDialog({
    open,
    onOpenChange,
    order,
}: OrderDetailDialogProps) {
    if (!order) return null;

    const subtotal =
        Number(order.subtotal) ||
        order.items?.reduce(
            (acc, item) =>
                acc + Number(item.qty || 0) * Number(item.price || 0),
            0,
        ) ||
        0;

    const discount = Number(order.discount) || 0;
    const tax = Number(order.tax) || 0;
    const grandTotal = Number(order.grand_total) || subtotal - discount + tax;

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="w-[95vw] sm:max-w-5xl md:max-w-6xl rounded-3xl border border-border bg-muted p-0 shadow-2xl max-h-[90vh] overflow-hidden flex flex-col [&>button]:hidden">
                {/* Header Banner */}
                <div className="bg-linear-to-r from-slate-900 via-indigo-950 to-slate-900 px-6 py-5 text-white shrink-0 border-b border-slate-800 flex items-center justify-between gap-4">
                    <div className="flex items-center gap-3">
                        <div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-indigo-500/20 text-indigo-300 ring-1 ring-indigo-400/30">
                            <FileText className="h-5 w-5" />
                        </div>
                        <div>
                            <div className="flex items-center gap-2.5">
                                <DialogTitle className="text-xl font-bold tracking-tight text-white">
                                    {order.order_number}
                                </DialogTitle>
                                <StatusBadge status={order.status} />
                            </div>
                            <DialogDescription className="text-xs text-muted-foreground/60 mt-0.5 flex items-center gap-1.5">
                                <Calendar className="w-3.5 h-3.5 text-indigo-400" />
                                Tanggal Order:{" "}
                                {new Date(order.order_date).toLocaleDateString(
                                    "id-ID",
                                    {
                                        day: "2-digit",
                                        month: "long",
                                        year: "numeric",
                                    },
                                )}
                            </DialogDescription>
                        </div>
                    </div>

                    {/* Area Kanan Header */}
                    <div className="flex items-center gap-3">
                        <div className="hidden sm:flex flex-col items-end rounded-2xl bg-card/10 px-4 py-1.5 border border-white/10 backdrop-blur-md">
                            <span className="text-[10px] uppercase tracking-wider text-muted-foreground/60 font-semibold">
                                Total Grand
                            </span>
                            <span className="text-lg font-black text-indigo-300">
                                Rp {grandTotal.toLocaleString("id-ID")}
                            </span>
                        </div>

                        {/* Tombol Close Kustom Putih */}
                        <DialogClose className="rounded-full bg-card/10 p-2 text-muted-foreground/60 hover:bg-card/20 hover:text-white transition-all focus:outline-none ring-1 ring-white/10">
                            <X className="h-4 w-4" />
                            <span className="sr-only">Tutup</span>
                        </DialogClose>
                    </div>
                </div>

                {/* Body Content */}
                <div className="p-6 space-y-6 overflow-y-auto flex-1 bg-muted">
                    {/* Info Cards */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="rounded-2xl border border-border/80 bg-card p-4 shadow-sm flex items-center gap-3">
                            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-indigo-50 text-indigo-600 shrink-0">
                                <User className="w-5 h-5" />
                            </div>
                            <div>
                                <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80">
                                    CUSTOMER
                                </span>
                                <p className="text-sm font-bold text-foreground">
                                    {order.customer?.name || "-"}
                                </p>
                            </div>
                        </div>

                        <div className="rounded-2xl border border-border/80 bg-card p-4 shadow-sm flex items-center gap-3">
                            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-indigo-50 text-indigo-600 shrink-0">
                                <UserCheck className="w-5 h-5" />
                            </div>
                            <div>
                                <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80">
                                    SALES REPRESENTATIVE
                                </span>
                                <p className="text-sm font-bold text-foreground">
                                    {order.sales?.name || "-"}
                                </p>
                            </div>
                        </div>
                    </div>

                    {/* Table Rincian Produk */}
                    <div className="rounded-2xl border border-border/80 bg-card shadow-sm overflow-hidden">
                        <div className="px-5 py-4 border-b border-slate-100 flex items-center justify-between bg-muted/50/50">
                            <div className="flex items-center gap-2">
                                <ShoppingBag className="w-4 h-4 text-indigo-600" />
                                <h3 className="text-xs font-bold uppercase tracking-wider text-foreground/80">
                                    Rincian Produk
                                </h3>
                            </div>
                            <span className="text-xs font-medium text-muted-foreground">
                                {order.items?.length || 0} Item
                            </span>
                        </div>

                        <div className="overflow-x-auto">
                            <Table className="w-full text-xs text-left">
                                <TableHeader className="bg-muted/70 text-muted-foreground font-bold uppercase tracking-wider border-b border-border/60">
                                    <TableRow>
                                        <TableHead className="px-5 py-3 text-left">
                                            Produk
                                        </TableHead>
                                        <TableHead className="px-5 py-3 text-center">
                                            Qty
                                        </TableHead>
                                        <TableHead className="px-5 py-3 text-right">
                                            Harga Satuan
                                        </TableHead>
                                        <TableHead className="px-5 py-3 text-right">
                                            Diskon
                                        </TableHead>
                                        <TableHead className="px-5 py-3 text-right">
                                            Subtotal
                                        </TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody className="divide-y divide-slate-100 text-foreground/80 font-medium">
                                    {order.items && order.items.length > 0 ? (
                                        order.items.map((item, idx) => {
                                            const itemPrice =
                                                Number(item.price) || 0;
                                            const itemQty =
                                                Number(item.qty) || 0;
                                            const itemDisc =
                                                Number(item.discount) || 0;
                                            const itemSubtotal =
                                                Number(item.subtotal) ||
                                                itemQty * itemPrice - itemDisc;

                                            return (
                                                <TableRow
                                                    key={idx}
                                                    className="hover:bg-muted/50 transition-colors"
                                                >
                                                    <TableCell className="px-5 py-3.5 text-foreground font-semibold">
                                                        {item.product_name ||
                                                            item.product
                                                                ?.name ||
                                                            "-"}
                                                    </TableCell>
                                                    <TableCell className="px-5 py-3.5 text-center font-bold">
                                                        {itemQty}
                                                    </TableCell>
                                                    <TableCell className="px-5 py-3.5 text-right">
                                                        Rp{" "}
                                                        {itemPrice.toLocaleString(
                                                            "id-ID",
                                                        )}
                                                    </TableCell>
                                                    <TableCell className="px-5 py-3.5 text-right text-muted-foreground/80">
                                                        Rp{" "}
                                                        {itemDisc.toLocaleString(
                                                            "id-ID",
                                                        )}
                                                    </TableCell>
                                                    <TableCell className="px-5 py-3.5 text-right font-bold text-foreground">
                                                        Rp{" "}
                                                        {itemSubtotal.toLocaleString(
                                                            "id-ID",
                                                        )}
                                                    </TableCell>
                                                </TableRow>
                                            );
                                        })
                                    ) : (
                                        <TableRow>
                                            <TableCell
                                                colSpan={5}
                                                className="px-5 py-8 text-center text-muted-foreground/80 font-medium"
                                            >
                                                Tidak ada data item produk pada
                                                order ini.
                                            </TableCell>
                                        </TableRow>
                                    )}
                                </TableBody>
                            </Table>
                        </div>
                    </div>

                    {/* Notes & Summary */}
                    <div className="grid grid-cols-1 lg:grid-cols-12 gap-5">
                        <div className="lg:col-span-7 rounded-2xl border border-border/80 bg-card p-5 shadow-sm space-y-2">
                            <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80">
                                CATATAN / INTRUKSI
                            </span>
                            <p className="text-xs text-muted-foreground leading-relaxed italic">
                                {order.notes ||
                                    "Tidak ada catatan khusus untuk transaksi ini."}
                            </p>
                        </div>

                        <div className="lg:col-span-5 rounded-2xl border border-border/80 bg-card p-5 shadow-sm space-y-3">
                            <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-muted-foreground border-b border-slate-100 pb-2">
                                <Receipt className="w-4 h-4 text-indigo-600" />
                                <span>Ringkasan Biaya</span>
                            </div>

                            <div className="space-y-2 text-xs font-medium">
                                <div className="flex justify-between items-center text-muted-foreground">
                                    <span>Subtotal</span>
                                    <span className="font-semibold text-foreground">
                                        Rp {subtotal.toLocaleString("id-ID")}
                                    </span>
                                </div>
                                <div className="flex justify-between items-center text-muted-foreground">
                                    <span>Diskon Nota</span>
                                    <span className="font-semibold text-foreground">
                                        Rp {discount.toLocaleString("id-ID")}
                                    </span>
                                </div>
                                <div className="flex justify-between items-center text-muted-foreground">
                                    <span>Pajak</span>
                                    <span className="font-semibold text-foreground">
                                        Rp {tax.toLocaleString("id-ID")}
                                    </span>
                                </div>
                            </div>

                            <div className="pt-3 border-t border-border flex justify-between items-center bg-slate-900 text-white p-3.5 rounded-xl shadow-sm">
                                <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground/60">
                                    Total Tagihan
                                </span>
                                <span className="text-lg font-black text-indigo-300">
                                    Rp {grandTotal.toLocaleString("id-ID")}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Footer Modal */}
                <div className="bg-card border-t border-border px-6 py-4 flex items-center justify-end gap-3 shrink-0">
                    <DialogClose asChild>
                        <Button
                            type="button"
                            variant="outline"
                            className="rounded-xl border-border font-semibold text-xs text-foreground/80 hover:bg-muted"
                        >
                            Tutup
                        </Button>
                    </DialogClose>
                </div>
            </DialogContent>
        </Dialog>
    );
}
