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

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

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 NotOrderCustomers({
    from,
    to,
    team,
    productId,
    rows = [],
    products = [],
    teams = [],
    stats,
}: any) {
    const [fromDate, setFromDate] = React.useState(from);
    const [toDate, setToDate] = React.useState(to);
    const [teamFilter, setTeamFilter] = React.useState(team || "");
    const [product, setProduct] = React.useState(
        productId ? String(productId) : "",
    );

    const teamOptions: ComboboxOption[] = [
        { value: "", label: "Semua Team" },
        ...teams.map((t: any) => ({ value: String(t.id), label: t.name })),
    ];
    const productOptions: ComboboxOption[] = [
        { value: "", label: "Tidak Order Sama Sekali" },
        ...products.map((p: any) => ({
            value: String(p.id),
            label: `Belum Order: ${p.name}`,
        })),
    ];

    const apply = (overrides?: Record<string, any>) => {
        router.get(
            "/reports/not-order-customers",
            {
                from: overrides?.from ?? fromDate,
                to: overrides?.to ?? toDate,
                team: (overrides?.team ?? teamFilter) || undefined,
                product_id: (overrides?.product_id ?? product) || 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 handleProductChange = (value: string) => {
        setProduct(value);
        apply({ product_id: value });
    };
    const resetFilters = () => {
        const f = defaultFrom();
        const t = defaultTo();
        setFromDate(f);
        setToDate(t);
        setTeamFilter("");
        setProduct("");
        apply({ from: f, to: t, team: "", product_id: "" });
    };

    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 selectedProductName = products.find(
        (p: any) => String(p.id) === product,
    )?.name;

    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 (product) params.set("product_id", product);
        window.location.href = `/reports/not-order-customers/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">
                        Not Order Customer
                    </h1>
                    <p className="mt-1 text-sm text-slate-500">
                        Customer yang belum memesan (produk tertentu, atau sama
                        sekali) dalam suatu periode.
                    </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={productOptions}
                        value={product}
                        onChange={handleProductChange}
                        placeholder="Tidak Order Sama Sekali"
                        searchPlaceholder="Cari produk..."
                        className="w-56"
                    />
                    <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>{" "}
                    • Filter:{" "}
                    <b className="text-slate-600">
                        {selectedProductName
                            ? `belum order produk "${selectedProductName}"`
                            : "tidak order sama sekali"}
                    </b>
                </div>
            </Card>

            <div className="mb-5 grid gap-3 md:grid-cols-3">
                {[
                    [
                        "Total Customer Aktif",
                        stats?.customers ?? 0,
                        "Dalam cakupan filter team",
                    ],
                    [
                        "Tidak Order",
                        stats?.not_order ?? 0,
                        "Sesuai filter produk & periode",
                    ],
                    [
                        "Sudah Order",
                        stats?.ordered ?? 0,
                        "Sudah memesan pada periode ini",
                    ],
                ].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="overflow-hidden print:overflow-visible"
                data-print-target
            >
                <div className="border-b p-5">
                    <div className="font-black text-slate-900">
                        Daftar Customer
                    </div>
                    <div className="mt-1 text-xs text-slate-400">
                        Customer yang perlu ditindaklanjuti sales/supervisor.
                    </div>
                </div>
                <div className="max-h-150 overflow-auto print:max-h-none print:overflow-visible">
                    <table className="w-full min-w-210 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">Customer</th>
                                <th className="px-5 py-3">Team</th>
                                <th className="px-5 py-3">Kontak</th>
                                <th className="px-5 py-3">Visit Terakhir</th>
                                <th className="px-5 py-3">Order Terakhir</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                            {rows.length === 0 ? (
                                <tr>
                                    <td
                                        colSpan={5}
                                        className="p-12 text-center text-sm text-slate-400"
                                    >
                                        Semua customer sudah memenuhi kriteria
                                        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">
                                            <div className="font-bold text-slate-800">
                                                {r.name}
                                            </div>
                                            <div className="text-[10px] text-slate-400">
                                                {r.code}
                                            </div>
                                        </td>
                                        <td className="px-5 py-3 text-slate-600">
                                            {r.team_name || "-"}
                                        </td>
                                        <td className="px-5 py-3">
                                            <div className="text-slate-600">
                                                {r.phone || "-"}
                                            </div>
                                            <div className="max-w-60 truncate text-[10px] text-slate-400">
                                                {r.address || "-"}
                                            </div>
                                        </td>
                                        <td className="px-5 py-3 text-slate-600">
                                            {r.last_visit || (
                                                <span className="text-slate-300">
                                                    Belum pernah
                                                </span>
                                            )}
                                        </td>
                                        <td className="px-5 py-3 text-slate-600">
                                            {r.last_order || (
                                                <span className="text-slate-300">
                                                    Belum pernah
                                                </span>
                                            )}
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </Card>
        </div>
    );
}
