import React from "react";
import { Link, router } from "@inertiajs/react";
import {
    ArrowLeft,
    CalendarDays,
    ChevronLeft,
    ChevronRight,
    Download,
} from "lucide-react";
import { 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", {
        weekday: "long",
        day: "2-digit",
        month: "long",
        year: "numeric",
    });
}

export default function DailyTeamSummary({ date, teams = [], stats }: any) {
    const [dateFilter, setDateFilter] = React.useState(date);

    const apply = (nextDate?: string) => {
        router.get(
            "/reports/daily-team-summary",
            { date: nextDate ?? dateFilter },
            { preserveState: true, replace: true },
        );
    };

    const shift = (days: number) => {
        const d = new Date(`${dateFilter}T00:00:00`);
        d.setDate(d.getDate() + days);
        const next = d.toISOString().slice(0, 10);
        setDateFilter(next);
        apply(next);
    };

    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, ...teams.map((t: any) => t.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">
                        Daily Team Summary
                    </h1>
                    <p className="mt-1 text-sm text-slate-500">
                        Performa harian masing-masing 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 gap-2">
                    <button
                        onClick={() => shift(-1)}
                        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={dateFilter}
                            onChange={(e) => {
                                setDateFilter(e.target.value);
                                apply(e.target.value);
                            }}
                            className="h-10 bg-transparent text-sm font-bold outline-none"
                        />
                    </div>
                    <button
                        onClick={() => shift(1)}
                        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="mt-2 px-1 text-[11px] text-slate-400">
                    Tanggal:{" "}
                    <b className="text-slate-600">{dateLabel(dateFilter)}</b>
                </div>
            </Card>

            <div className="mb-5 grid gap-3 md:grid-cols-2 xl:grid-cols-5">
                {[
                    ["Team", stats?.teams ?? 0, "Team dalam monitoring"],
                    ["Total Visit", stats?.visits ?? 0, "Seluruh kunjungan"],
                    [
                        "Selesai",
                        stats?.completed ?? 0,
                        "Visited / Order / Not Order",
                    ],
                    ["Failed Visit", stats?.failed ?? 0, "Kunjungan gagal"],
                    ["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>

            <Card
                className="overflow-hidden print:overflow-visible"
                data-print-target
            >
                <div className="border-b p-5">
                    <div className="font-black text-slate-900">
                        Rekap Performa Per Team
                    </div>
                    <div className="mt-1 text-xs text-slate-400">
                        Perbandingan aktivitas tiap team pada{" "}
                        {dateLabel(dateFilter)}.
                    </div>
                </div>
                <div className="max-h-125 overflow-auto print:max-h-none print:overflow-visible">
                    <table className="w-full min-w-215 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">Visit</th>
                                <th className="px-5 py-3 text-center">
                                    Selesai
                                </th>
                                <th className="px-5 py-3 text-center">
                                    Failed
                                </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">
                            {teams.length === 0 ? (
                                <tr>
                                    <td
                                        colSpan={8}
                                        className="p-12 text-center text-sm text-slate-400"
                                    >
                                        Belum ada data visit pada tanggal ini.
                                    </td>
                                </tr>
                            ) : (
                                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">
                                            <div className="flex items-center gap-2">
                                                <div className="h-2 w-24 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 / maxVisits) * 100)}%`,
                                                        }}
                                                    />
                                                </div>
                                                <span className="text-xs font-black text-slate-800">
                                                    {t.visits}
                                                </span>
                                            </div>
                                        </td>
                                        <td className="px-5 py-3 text-center font-bold text-emerald-600">
                                            {t.completed}
                                        </td>
                                        <td className="px-5 py-3 text-center font-bold text-rose-600">
                                            {t.failed}
                                        </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>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </Card>
        </div>
    );
}
