import React from "react";
import { Link, router } from "@inertiajs/react";
import {
    ArrowLeft,
    CalendarDays,
    ChevronLeft,
    ChevronRight,
    Download,
    FileBarChart2,
} from "lucide-react";
import { Badge, Button, Card } from "../../components/ui";

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",
    });
}

export default function TeamVisitSummary({
    from,
    to,
    period = [],
    teams = [],
    stats,
}: any) {
    const [fromDate, setFromDate] = React.useState(from);
    const [toDate, setToDate] = React.useState(to);

    const apply = () =>
        router.get(
            "/reports/team-visit-summary",
            { from: fromDate, to: toDate },
            { preserveState: true, replace: true },
        );

    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);
        router.get(
            "/reports/team-visit-summary",
            { from: nextFrom, to: nextTo },
            { preserveState: true, replace: true },
        );
    };

    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 maxVisits = Math.max(1, ...period.map((x: any) => x.visits));
    const maxTeamVisits = Math.max(1, ...teams.map((x: any) => x.visits));

    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">
                        Team Visit Summary
                    </h1>
                    <p className="mt-1 text-sm text-slate-500">
                        Perbandingan kunjungan antar team.
                    </p>
                </div>
                <Button
                    variant="outline"
                    className="gap-2"
                    onClick={printReport}
                >
                    <Download size={15} /> Cetak
                </Button>
            </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) => setFromDate(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) => setToDate(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>
                    <Button onClick={apply} size="sm">
                        Terapkan
                    </Button>
                </div>
                <div className="mt-2 px-1 text-[11px] text-slate-400">
                    Periode:{" "}
                    <b className="text-slate-600">
                        {dateLabel(from)} — {dateLabel(to)}
                    </b>
                </div>
            </Card>

            <div className="mb-5 grid gap-3 md:grid-cols-2 xl:grid-cols-6">
                {[
                    ["Team", stats?.teams ?? 0, "Team dalam monitoring"],
                    [
                        "Customer",
                        stats?.customers ?? 0,
                        "Customer unik dikunjungi",
                    ],
                    ["Total Visit", stats?.visits ?? 0, "Seluruh kunjungan"],
                    [
                        "Selesai",
                        stats?.completed ?? 0,
                        "Visited / Order / Not Order",
                    ],
                    ["Order", stats?.orders ?? 0, "Order pada periode"],
                    ["Omzet", money(stats?.omzet ?? 0), "Total nilai order"],
                ].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>

            <div className="grid gap-5 xl:grid-cols-[1.15fr_.85fr]">
                <Card className="overflow-hidden">
                    <div className="flex items-center justify-between border-b p-5">
                        <div>
                            <div className="flex items-center gap-2 font-black text-slate-900">
                                <FileBarChart2
                                    size={18}
                                    className="text-[#0b7668]"
                                />{" "}
                                Tren Visit Harian
                            </div>
                            <div className="mt-1 text-xs text-slate-400">
                                Jumlah kunjungan seluruh team setiap hari.
                            </div>
                        </div>
                        <Badge tone="green">{period.length} hari aktif</Badge>
                    </div>
                    <div className="p-5">
                        {period.length === 0 ? (
                            <div className="py-16 text-center text-sm text-slate-400">
                                Belum ada data visit pada periode ini.
                            </div>
                        ) : (
                            <div className="space-y-3">
                                {period.map((row: any) => (
                                    <div
                                        key={row.date}
                                        className="grid grid-cols-[72px_1fr_70px_90px] items-center gap-3 rounded-xl"
                                    >
                                        <div>
                                            <div className="text-xs font-bold text-slate-700">
                                                {row.label}
                                            </div>
                                            <div className="text-[9px] text-slate-400">
                                                {row.date.slice(0, 4)}
                                            </div>
                                        </div>
                                        <div className="relative h-8 overflow-hidden rounded-lg bg-slate-100">
                                            <div
                                                className="absolute inset-y-0 left-0 rounded-lg bg-[#18b89a]/20"
                                                style={{
                                                    width: `${Math.max(8, (row.visits / maxVisits) * 100)}%`,
                                                }}
                                            />
                                            <div className="relative flex h-full items-center px-3 text-xs font-black text-[#0b7668]">
                                                {row.visits} visit
                                            </div>
                                        </div>
                                        <div className="text-right">
                                            <div className="text-xs font-black text-slate-800">
                                                {row.orders}
                                            </div>
                                            <div className="text-[9px] text-slate-400">
                                                order
                                            </div>
                                        </div>
                                        <div className="text-right text-xs font-black text-slate-700">
                                            {money(row.omzet)}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </Card>

                <Card className="overflow-hidden">
                    <div className="border-b p-5">
                        <div className="font-black text-slate-900">
                            Ranking Team
                        </div>
                        <div className="mt-1 text-xs text-slate-400">
                            Perbandingan produktivitas team dalam periode.
                        </div>
                    </div>
                    <div className="max-h-125 divide-y overflow-y-auto print:max-h-none print:overflow-visible">
                        {teams.length === 0 ? (
                            <div className="p-12 text-center text-sm text-slate-400">
                                Belum ada team.
                            </div>
                        ) : (
                            teams.map((t: any, i: number) => (
                                <div
                                    key={t.team_id ?? "no-team"}
                                    className="p-4"
                                >
                                    <div className="flex items-center gap-3">
                                        <div className="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-[#e9fbf7] text-xs font-black text-[#0b7668]">
                                            {i + 1}
                                        </div>
                                        <div className="min-w-0 flex-1">
                                            <div className="truncate text-sm font-bold text-slate-800">
                                                {t.name}
                                            </div>
                                            <div className="mt-1 text-[10px] text-slate-400">
                                                {t.sales} sales • {t.customers}{" "}
                                                customer
                                            </div>
                                        </div>
                                        <div className="text-right">
                                            <div className="text-sm font-black text-slate-900">
                                                {t.visits}
                                            </div>
                                            <div className="text-[9px] text-slate-400">
                                                visit
                                            </div>
                                        </div>
                                    </div>
                                    <div className="mt-3 h-2 overflow-hidden rounded-full bg-slate-100">
                                        <div
                                            className="h-full rounded-full bg-[#0b7668]"
                                            style={{
                                                width: `${Math.max(t.visits ? 5 : 0, (t.visits / maxTeamVisits) * 100)}%`,
                                            }}
                                        />
                                    </div>
                                    <div className="mt-2 flex justify-between text-[10px]">
                                        <span className="font-bold text-emerald-600">
                                            {t.completed} selesai
                                        </span>
                                        <span className="font-bold text-slate-600">
                                            {money(t.omzet)}
                                        </span>
                                    </div>
                                </div>
                            ))
                        )}
                    </div>
                </Card>
            </div>

            <Card
                className="mt-5 overflow-hidden print:overflow-visible"
                data-print-target
            >
                <div className="border-b p-5">
                    <div className="font-black text-slate-900">
                        Rekap Visit Per Team
                    </div>
                    <div className="mt-1 text-xs text-slate-400">
                        Ringkasan yang siap digunakan supervisor untuk
                        monitoring dan evaluasi antar team.
                    </div>
                </div>
                <div className="max-h-125 overflow-auto print:max-h-none print:overflow-visible">
                    <table className="w-full min-w-190 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">Team</th>
                                <th className="px-5 py-3 text-center">Sales</th>
                                <th className="px-5 py-3 text-center">
                                    Customer
                                </th>
                                <th className="px-5 py-3 text-center">Visit</th>
                                <th className="px-5 py-3 text-center">
                                    Selesai
                                </th>
                                <th className="px-5 py-3 text-center">Order</th>
                                <th className="px-5 py-3 text-right">Omzet</th>
                                <th className="px-5 py-3 text-right">
                                    Conversion
                                </th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                            {teams.map((t: any) => (
                                <tr
                                    key={t.team_id ?? "no-team"}
                                    className="hover:bg-slate-50"
                                >
                                    <td className="px-5 py-3 font-bold text-slate-800">
                                        {t.name}
                                    </td>
                                    <td className="px-5 py-3 text-center">
                                        {t.sales}
                                    </td>
                                    <td className="px-5 py-3 text-center">
                                        {t.customers}
                                    </td>
                                    <td className="px-5 py-3 text-center font-black">
                                        {t.visits}
                                    </td>
                                    <td className="px-5 py-3 text-center">
                                        {t.completed}
                                    </td>
                                    <td className="px-5 py-3 text-center">
                                        {t.orders}
                                    </td>
                                    <td className="px-5 py-3 text-right font-bold">
                                        {money(t.omzet)}
                                    </td>
                                    <td className="px-5 py-3 text-right">
                                        <span className="font-black text-[#0b7668]">
                                            {t.visits
                                                ? Math.round(
                                                      (t.orders / t.visits) *
                                                          100,
                                                  )
                                                : 0}
                                            %
                                        </span>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </Card>
        </div>
    );
}
