import React from "react";
import { Link, router } from "@inertiajs/react";
import {
    ArrowLeft,
    CalendarDays,
    ChevronLeft,
    ChevronRight,
    Download,
    FileSpreadsheet,
    FileText,
    RotateCcw,
} 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 statusTone: Record<string, string> = {
    Scheduled: "slate",
    "On Process": "blue",
    Visited: "green",
    Order: "orange",
    "Not Order": "slate",
    "Failed Visit": "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 SalesVisit({
    from,
    to,
    salesId,
    productId,
    rows = [],
    summary = [],
    salesUsers = [],
    products = [],
    stats,
}: any) {
    const [fromDate, setFromDate] = React.useState(from);
    const [toDate, setToDate] = React.useState(to);
    const [sales, setSales] = React.useState(salesId ? String(salesId) : "");
    const [product, setProduct] = React.useState(
        productId ? String(productId) : "",
    );

    const salesOptions: ComboboxOption[] = [
        { value: "", label: "Semua Sales" },
        ...salesUsers.map((s: any) => ({
            value: String(s.id),
            label: s.name,
        })),
    ];
    const productOptions: ComboboxOption[] = [
        { value: "", label: "Semua Produk" },
        ...products.map((p: any) => ({
            value: String(p.id),
            label: p.name,
        })),
    ];

    const apply = (overrides?: Record<string, any>) => {
        router.get(
            "/reports/sales-visit",
            {
                from: overrides?.from ?? fromDate,
                to: overrides?.to ?? toDate,
                sales_id: (overrides?.sales_id ?? sales) || 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 handleSalesChange = (value: string) => {
        setSales(value);
        apply({ sales_id: value });
    };
    const handleProductChange = (value: string) => {
        setProduct(value);
        apply({ product_id: value });
    };
    const resetFilters = () => {
        const f = defaultFrom();
        const t = defaultTo();
        setFromDate(f);
        setToDate(t);
        setSales("");
        setProduct("");
        apply({ from: f, to: t, sales_id: "", product_id: "" });
    };

    const shift = (days: number) => {
        const a = new Date(`${fromDate}T00:00:00`);
        const b = new Date(`${toDate}T00:00:00`);
        a.setDate(a.getDate() + days);
        b.setDate(b.getDate() + days);
        const nextFrom = a.toISOString().slice(0, 10);
        const nextTo = b.toISOString().slice(0, 10);
        setFromDate(nextFrom);
        setToDate(nextTo);
        apply({ from: nextFrom, to: nextTo });
    };

    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 (sales) params.set("sales_id", sales);
        if (product) params.set("product_id", product);
        window.location.href = `/reports/sales-visit/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">
                        Kunjungan Sales
                    </h1>
                    <p className="mt-1 text-sm text-slate-500">
                        Daftar kunjungan sales dengan filter sales, produk, dan
                        tanggal.
                    </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 justify-between gap-3">
                    <div className="flex shrink-0 items-center gap-2">
                        <button
                            onClick={() => shift(-7)}
                            className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-slate-100 hover:bg-slate-200"
                        >
                            <ChevronLeft size={18} />
                        </button>
                        <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>
                        <button
                            onClick={() => shift(7)}
                            className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-slate-100 hover:bg-slate-200"
                        >
                            <ChevronRight size={18} />
                        </button>
                    </div>
                    <div className="flex flex-wrap items-center justify-end gap-3">
                        <Combobox
                            options={salesOptions}
                            value={sales}
                            onChange={handleSalesChange}
                            placeholder="Semua Sales"
                            searchPlaceholder="Cari sales..."
                            className="w-44"
                        />
                        <Combobox
                            options={productOptions}
                            value={product}
                            onChange={handleProductChange}
                            placeholder="Semua Produk"
                            searchPlaceholder="Cari produk..."
                            className="w-44"
                        />
                        <Button
                            variant="outline"
                            className="gap-2"
                            onClick={resetFilters}
                        >
                            <RotateCcw size={14} /> Reset Filter
                        </Button>
                    </div>
                </div>
                <div className="mt-2 px-1 text-[11px] text-slate-400">
                    Periode:{" "}
                    <b className="text-slate-600">
                        {dateLabel(fromDate)} — {dateLabel(toDate)}
                    </b>
                    {product && (
                        <>
                            {" "}
                            • Produk:{" "}
                            <b className="text-slate-600">
                                {products.find(
                                    (p: any) => String(p.id) === product,
                                )?.name || "-"}
                            </b>
                        </>
                    )}
                </div>
            </Card>

            <div className="mb-5 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                {[
                    [
                        "Total Visit",
                        stats?.visits ?? 0,
                        "Kunjungan pada filter ini",
                    ],
                    [
                        "Order",
                        stats?.orders ?? 0,
                        "Visit yang menghasilkan order",
                    ],
                    ["Omzet", money(stats?.omzet ?? 0), "Total nilai order"],
                    [
                        "Customer",
                        stats?.customers ?? 0,
                        "Customer unik dikunjungi",
                    ],
                ].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="font-black text-slate-900">
                        Rekap Per Sales
                    </div>
                    <div className="mt-1 text-xs text-slate-400">
                        Ringkasan jumlah visit, order, dan omzet tiap sales pada
                        periode ini.
                    </div>
                </div>
                <div className="max-h-75 overflow-auto">
                    <table className="w-full min-w-150 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">Sales</th>
                                <th className="px-5 py-3 text-center">Visit</th>
                                <th className="px-5 py-3 text-center">Order</th>
                                <th className="px-5 py-3 text-right">Omzet</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                            {summary.length === 0 ? (
                                <tr>
                                    <td
                                        colSpan={4}
                                        className="p-8 text-center text-sm text-slate-400"
                                    >
                                        Belum ada data pada filter ini.
                                    </td>
                                </tr>
                            ) : (
                                summary.map((s: any) => (
                                    <tr
                                        key={s.name}
                                        className="hover:bg-slate-50"
                                    >
                                        <td className="px-5 py-3 font-bold text-slate-800">
                                            {s.name}
                                        </td>
                                        <td className="px-5 py-3 text-center font-black">
                                            {s.visits}
                                        </td>
                                        <td className="px-5 py-3 text-center">
                                            {s.orders}
                                        </td>
                                        <td className="px-5 py-3 text-right font-bold">
                                            {money(s.omzet)}
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </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">
                        Detail Kunjungan
                    </div>
                    <div className="mt-1 text-xs text-slate-400">
                        Seluruh kunjungan sales pada {dateLabel(fromDate)} —{" "}
                        {dateLabel(toDate)}.
                    </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">Tanggal</th>
                                <th className="px-5 py-3">Sales</th>
                                <th className="px-5 py-3">Customer</th>
                                <th className="px-5 py-3 text-center">
                                    Status
                                </th>
                                <th className="px-5 py-3">Produk Dipesan</th>
                                <th className="px-5 py-3 text-right">Omzet</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                            {rows.length === 0 ? (
                                <tr>
                                    <td
                                        colSpan={6}
                                        className="p-12 text-center text-sm text-slate-400"
                                    >
                                        Belum ada kunjungan pada filter ini.
                                    </td>
                                </tr>
                            ) : (
                                rows.map((r: any) => (
                                    <tr
                                        key={r.id}
                                        className="hover:bg-slate-50"
                                    >
                                        <td className="px-5 py-3 whitespace-nowrap text-slate-600">
                                            {r.date}
                                            <span className="ml-1 text-[10px] text-slate-400">
                                                {r.time}
                                            </span>
                                        </td>
                                        <td className="px-5 py-3 font-semibold text-slate-800">
                                            {r.sales_name}
                                        </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-center">
                                            <Badge
                                                tone={
                                                    statusTone[r.status] ||
                                                    "slate"
                                                }
                                            >
                                                {r.status}
                                            </Badge>
                                        </td>
                                        <td className="px-5 py-3">
                                            {r.products.length === 0 ? (
                                                <span className="text-slate-300">
                                                    -
                                                </span>
                                            ) : (
                                                <span className="text-xs text-slate-600">
                                                    {r.products
                                                        .map(
                                                            (p: any) =>
                                                                `${p.name} (${p.qty})`,
                                                        )
                                                        .join(", ")}
                                                </span>
                                            )}
                                        </td>
                                        <td className="px-5 py-3 text-right font-bold">
                                            {r.order_total
                                                ? money(r.order_total)
                                                : "-"}
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </Card>
        </div>
    );
}
