import React from "react";
import { Link, router } from "@inertiajs/react";
import {
    ArrowLeft,
    CalendarDays,
    Download,
    FileSpreadsheet,
    FileText,
    RotateCcw,
    Truck,
} from "lucide-react";
import { Badge, Button, Card } from "../../components/ui";
import { Combobox, ComboboxOption } from "../../components/ui/combobox";

function money(value: number) {
    return new Intl.NumberFormat("id-ID", {
        style: "currency",
        currency: "IDR",
        maximumFractionDigits: 0,
    }).format(value || 0);
}

function dateLabel(value: string) {
    return new Date(`${value}T00:00:00`).toLocaleDateString("id-ID", {
        day: "2-digit",
        month: "short",
        year: "numeric",
    });
}

const statusLabel: Record<string, string> = {
    Draft: "Draf",
    Submitted: "Diajukan",
    Approved: "Disetujui",
    Delivered: "Terkirim",
    Cancelled: "Dibatalkan",
};

const statusTone: Record<string, string> = {
    Draft: "slate",
    Submitted: "blue",
    Approved: "green",
    Delivered: "purple",
    Cancelled: "red",
};

function defaultFrom() {
    const d = new Date();
    return new Date(d.getFullYear(), d.getMonth(), 1)
        .toISOString()
        .slice(0, 10);
}
function defaultTo() {
    return new Date().toISOString().slice(0, 10);
}

export default function Delivery({
    from,
    to,
    team,
    status,
    salesId,
    rows = [],
    statusSummary = [],
    statuses = [],
    teams = [],
    salesUsers = [],
    stats,
}: any) {
    const [fromDate, setFromDate] = React.useState(from);
    const [toDate, setToDate] = React.useState(to);
    const [teamFilter, setTeamFilter] = React.useState(team || "");
    const [statusFilter, setStatusFilter] = React.useState(status || "");
    const [salesFilter, setSalesFilter] = React.useState(
        salesId ? String(salesId) : "",
    );

    const teamOptions: ComboboxOption[] = [
        { value: "", label: "Semua Team" },
        ...teams.map((t: any) => ({ value: String(t.id), label: t.name })),
    ];
    const salesOptions: ComboboxOption[] = [
        { value: "", label: "Semua Sales" },
        ...salesUsers.map((s: any) => ({
            value: String(s.id),
            label: s.name,
        })),
    ];
    const statusOptions: ComboboxOption[] = [
        { value: "", label: "Semua Status" },
        ...statuses.map((s: string) => ({
            value: s,
            label: statusLabel[s] || s,
        })),
    ];

    const apply = (overrides?: Record<string, any>) => {
        router.get(
            "/reports/delivery",
            {
                from: overrides?.from ?? fromDate,
                to: overrides?.to ?? toDate,
                team: (overrides?.team ?? teamFilter) || undefined,
                status: (overrides?.status ?? statusFilter) || undefined,
                sales_id: (overrides?.sales_id ?? salesFilter) || undefined,
            },
            { preserveState: true, replace: true },
        );
    };

    const handleFromChange = (value: string) => {
        setFromDate(value);
        apply({ from: value });
    };
    const handleToChange = (value: string) => {
        setToDate(value);
        apply({ to: value });
    };
    const handleTeamChange = (value: string) => {
        setTeamFilter(value);
        apply({ team: value });
    };
    const handleSalesChange = (value: string) => {
        setSalesFilter(value);
        apply({ sales_id: value });
    };
    const handleStatusChange = (value: string) => {
        setStatusFilter(value);
        apply({ status: value });
    };
    const resetFilters = () => {
        const f = defaultFrom();
        const t = defaultTo();
        setFromDate(f);
        setToDate(t);
        setTeamFilter("");
        setSalesFilter("");
        setStatusFilter("");
        apply({
            from: f,
            to: t,
            team: "",
            sales_id: "",
            status: "",
        });
    };

    const printReport = () => {
        const target = document.querySelector<HTMLElement>(
            "[data-print-target]",
        );
        if (!target) {
            window.print();
            return;
        }
        const printContainer = document.createElement("div");
        printContainer.id = "print-container";
        printContainer.appendChild(target.cloneNode(true));
        document.body.classList.add("printing-target-only");
        document.body.appendChild(printContainer);
        const cleanup = () => {
            printContainer.remove();
            document.body.classList.remove("printing-target-only");
            window.removeEventListener("afterprint", cleanup);
        };
        window.addEventListener("afterprint", cleanup);
        window.print();
    };

    const exportReport = (format: "xls" | "csv") => {
        const params = new URLSearchParams();
        params.set("format", format);
        params.set("from", fromDate);
        params.set("to", toDate);
        if (teamFilter) params.set("team", teamFilter);
        if (statusFilter) params.set("status", statusFilter);
        if (salesFilter) params.set("sales_id", salesFilter);
        window.location.href = `/reports/delivery/export?${params.toString()}`;
    };

    return (
        <div className="p-7">
            <div className="mb-6 flex flex-wrap items-end justify-between gap-4">
                <div>
                    <Link
                        href="/reports"
                        className="mb-2 inline-flex items-center gap-1 text-xs font-semibold text-slate-500 hover:text-slate-700"
                    >
                        <ArrowLeft size={14} /> Kembali ke Reports
                    </Link>
                    <h1 className="text-2xl font-black tracking-tight text-slate-900">
                        Report Delivery
                    </h1>
                    <p className="mt-1 text-sm text-slate-500">
                        Status pengiriman order: draf, diajukan, disetujui,
                        terkirim, dan dibatalkan.
                    </p>
                </div>
                <div className="flex flex-wrap items-center gap-2">
                    <Button
                        variant="outline"
                        className="gap-2"
                        onClick={printReport}
                    >
                        <Download size={15} /> Cetak
                    </Button>
                    <Button
                        variant="outline"
                        className="gap-2"
                        onClick={() => exportReport("xls")}
                    >
                        <FileSpreadsheet size={15} /> Excel
                    </Button>
                    <Button
                        variant="outline"
                        className="gap-2"
                        onClick={() => exportReport("csv")}
                    >
                        <FileText size={15} /> CSV
                    </Button>
                </div>
            </div>

            <Card className="mb-5 p-3">
                <div className="flex flex-wrap items-center gap-3">
                    <div className="flex h-10 shrink-0 items-center gap-2 rounded-xl border border-slate-200 bg-white px-3">
                        <CalendarDays
                            size={17}
                            className="shrink-0 text-[#18b89a]"
                        />
                        <input
                            type="date"
                            value={fromDate}
                            onChange={(e) => handleFromChange(e.target.value)}
                            className="h-10 bg-transparent text-sm font-bold outline-none"
                        />
                        <span className="text-slate-300">—</span>
                        <input
                            type="date"
                            value={toDate}
                            onChange={(e) => handleToChange(e.target.value)}
                            className="h-10 bg-transparent text-sm font-bold outline-none"
                        />
                    </div>
                    <Combobox
                        options={teamOptions}
                        value={teamFilter}
                        onChange={handleTeamChange}
                        placeholder="Semua Team"
                        searchPlaceholder="Cari team..."
                        className="w-44"
                    />
                    <Combobox
                        options={salesOptions}
                        value={salesFilter}
                        onChange={handleSalesChange}
                        placeholder="Semua Sales"
                        searchPlaceholder="Cari sales..."
                        className="w-44"
                    />
                    <Combobox
                        options={statusOptions}
                        value={statusFilter}
                        onChange={handleStatusChange}
                        placeholder="Semua Status"
                        searchPlaceholder="Cari status..."
                        className="w-44"
                    />
                    <Button
                        variant="outline"
                        className="gap-2"
                        onClick={resetFilters}
                    >
                        <RotateCcw size={14} /> Reset Filter
                    </Button>
                </div>
                <div className="mt-2 px-1 text-[11px] text-slate-400">
                    Periode:{" "}
                    <b className="text-slate-600">
                        {dateLabel(fromDate)} — {dateLabel(toDate)}
                    </b>
                </div>
            </Card>

            <div className="mb-5 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                {[
                    ["Total Order", stats?.orders ?? 0, "Pada periode ini"],
                    [
                        "Terkirim",
                        stats?.delivered ?? 0,
                        money(stats?.delivered_omzet ?? 0),
                    ],
                    [
                        "Menunggu Kirim",
                        stats?.pending ?? 0,
                        "Draf / Diajukan / Disetujui",
                    ],
                    ["Dibatalkan", stats?.cancelled ?? 0, "Order batal"],
                ].map(([label, value, hint]) => (
                    <Card key={label as string} className="p-4">
                        <div className="text-[11px] font-bold uppercase tracking-wider text-slate-400">
                            {label}
                        </div>
                        <div className="mt-1 text-xl font-black text-slate-900">
                            {value}
                        </div>
                        <div className="mt-1 text-[10px] text-slate-400">
                            {hint}
                        </div>
                    </Card>
                ))}
            </div>

            <Card className="mb-5 overflow-hidden">
                <div className="border-b p-5">
                    <div className="flex items-center gap-2 font-black text-slate-900">
                        <Truck size={16} className="text-[#18b89a]" />
                        Breakdown Status Pengiriman
                    </div>
                </div>
                <div className="flex divide-x divide-slate-100 overflow-x-auto">
                    {statusSummary.map((s: any) => (
                        <div key={s.status} className="min-w-37.5 flex-1 p-4">
                            <Badge tone={statusTone[s.status] || "slate"}>
                                {statusLabel[s.status] || s.status}
                            </Badge>
                            <div className="mt-2 text-xl font-black whitespace-nowrap text-slate-900">
                                {s.count}
                            </div>
                            <div className="mt-1 text-[10px] whitespace-nowrap text-slate-400">
                                {money(s.omzet)}
                            </div>
                        </div>
                    ))}
                </div>
            </Card>

            <Card
                className="overflow-hidden print:overflow-visible"
                data-print-target
            >
                <div className="border-b p-5">
                    <div className="font-black text-slate-900">
                        Daftar Order
                    </div>
                    <div className="mt-1 text-xs text-slate-400">
                        Detail order beserta status pengirimannya.
                    </div>
                </div>
                <div className="max-h-150 overflow-auto print:max-h-none print:overflow-visible">
                    <table className="w-full min-w-240 text-sm">
                        <thead className="sticky top-0 z-10">
                            <tr className="bg-slate-50 text-left text-[10px] uppercase tracking-wider text-slate-400">
                                <th className="px-5 py-3">No. Order</th>
                                <th className="px-5 py-3">Tanggal</th>
                                <th className="px-5 py-3">Customer</th>
                                <th className="px-5 py-3">Sales</th>
                                <th className="px-5 py-3 text-center">Item</th>
                                <th className="px-5 py-3 text-center">
                                    Status
                                </th>
                                <th className="px-5 py-3 text-right">Total</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                            {rows.length === 0 ? (
                                <tr>
                                    <td
                                        colSpan={7}
                                        className="p-12 text-center text-sm text-slate-400"
                                    >
                                        Belum ada order pada filter ini.
                                    </td>
                                </tr>
                            ) : (
                                rows.map((r: any) => (
                                    <tr
                                        key={r.id}
                                        className="hover:bg-slate-50"
                                    >
                                        <td className="px-5 py-3 font-bold text-slate-800">
                                            {r.order_no}
                                        </td>
                                        <td className="px-5 py-3 whitespace-nowrap text-slate-600">
                                            {r.date}
                                        </td>
                                        <td className="px-5 py-3">
                                            <div className="font-semibold text-slate-800">
                                                {r.customer_name}
                                            </div>
                                            {r.team_name && (
                                                <div className="text-[10px] text-slate-400">
                                                    {r.team_name}
                                                </div>
                                            )}
                                        </td>
                                        <td className="px-5 py-3 text-slate-600">
                                            {r.sales_name}
                                        </td>
                                        <td className="px-5 py-3 text-center">
                                            {r.items_count}
                                        </td>
                                        <td className="px-5 py-3 text-center">
                                            <Badge
                                                tone={
                                                    statusTone[r.status] ||
                                                    "slate"
                                                }
                                            >
                                                {statusLabel[r.status] ||
                                                    r.status}
                                            </Badge>
                                        </td>
                                        <td className="px-5 py-3 text-right font-bold">
                                            {money(r.total)}
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </Card>
        </div>
    );
}
