import { Head, router } from "@inertiajs/react";
import { useState } from "react";
import {
    Sparkles,
    Filter,
    TrendingUp,
    Target,
    ShoppingBag,
    Users,
    SearchX,
    Briefcase,
    Download,
    RotateCcw,
    SlidersHorizontal,
} from "lucide-react";
import AppLayout from "@/layouts/app-layout";
import {
    Card,
    CardContent,
    CardHeader,
    CardTitle,
    CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { CrmSelect } from "@/components/crm-select";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";

import { StatChip } from "@/components/crm/global-card";

const months = [
    "Januari",
    "Februari",
    "Maret",
    "April",
    "Mei",
    "Juni",
    "Juli",
    "Agustus",
    "September",
    "Oktober",
    "November",
    "Desember",
];

// Opsi Tahun (Menampilkan 5 tahun ke belakang dan 1 tahun ke depan)
const currentYearNum = new Date().getFullYear();
const yearOptions = Array.from({ length: 7 }, (_, i) => currentYearNum - 5 + i);

const money = (value: number | string | null | undefined) =>
    new Intl.NumberFormat("id-ID", {
        style: "currency",
        currency: "IDR",
        maximumFractionDigits: 0,
    }).format(Number(value) || 0);

const formatNumber = (value: number | string | null | undefined) =>
    new Intl.NumberFormat("id-ID").format(Number(value) || 0);

type Row = {
    sales_id: number;
    sales_name: string;
    target_amount: number;
    actual_amount: number;
    amount_percent: number;
    target_qty: number;
    actual_qty: number;
    qty_percent: number;
    target_visits: number;
    actual_visits: number;
    visit_percent: number;
    target_orders: number;
    actual_orders: number;
    order_percent: number;
};

type Props = {
    rows: Row[];
    sales: { id: number; name: string }[];
    filters: { year: number; month: number; sales_id: number | null };
};

export default function SalesPerformance({ rows, sales, filters }: Props) {
    const [year, setYear] = useState(String(filters.year));
    const [month, setMonth] = useState(String(filters.month));
    const [salesId, setSalesId] = useState(
        filters.sales_id ? String(filters.sales_id) : "",
    );

    const apply = () =>
        router.get(
            "/crm/sales/performance",
            { year, month, sales_id: salesId || undefined },
            { preserveState: true, preserveScroll: true },
        );

    const reset = () => {
        const defaultYear = String(new Date().getFullYear());
        const defaultMonth = String(new Date().getMonth() + 1);
        const defaultSalesId = "";

        setYear(defaultYear);
        setMonth(defaultMonth);
        setSalesId(defaultSalesId);

        router.get(
            "/crm/sales/performance",
            { year: defaultYear, month: defaultMonth },
            { preserveState: true, preserveScroll: true },
        );
    };

    const totalTargetAmount = rows.reduce((n, r) => n + r.target_amount, 0);
    const totalActualAmount = rows.reduce((n, r) => n + r.actual_amount, 0);
    const totalTargetQty = rows.reduce((n, r) => n + r.target_qty, 0);
    const totalActualQty = rows.reduce((n, r) => n + r.actual_qty, 0);

    const overallAchievement =
        totalTargetAmount > 0
            ? Math.round((totalActualAmount / totalTargetAmount) * 100)
            : 0;

    return (
        <AppLayout
            breadcrumbs={[
                { title: "Kinerja Sales", href: "/crm/sales/performance" },
            ]}
        >
            <Head title="Kinerja Sales" />
            <div className="crm-page space-y-6 pb-10">
                {/* Header Top Bar */}
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 pb-2 border-b border-border/60">
                    <div>
                        <div className="flex items-center gap-2">
                            <h1 className="text-2xl font-bold tracking-tight text-foreground">
                                Sales Performance Analytics
                            </h1>
                            <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-indigo-50 text-indigo-700 border border-indigo-200/60">
                                <Sparkles className="w-3 h-3" /> Realtime KPI
                            </span>
                        </div>
                        <p className="text-sm text-muted-foreground mt-1">
                            Evaluasi pencapaian target penjualan, kuantitas
                            produk, kunjungan, dan pesanan tim sales.
                        </p>
                    </div>

                    <div className="flex items-center gap-2">
                        <Button
                            variant="outline"
                            size="sm"
                            className="rounded-xl border-border text-foreground/80 hover:bg-muted font-medium text-xs shadow-2xs"
                            onClick={() => window.print()}
                        >
                            <Download className="w-3.5 h-3.5 mr-1.5 text-muted-foreground" />
                            Eksport Laporan
                        </Button>
                    </div>
                </div>

                {/* 🌟 FILTER CONTROL BAR */}
                <Card className="border border-border/80 shadow-xs bg-card rounded-2xl overflow-hidden">
                    <div className="px-5 py-3 bg-muted/50/80 border-b border-slate-100 flex items-center justify-between">
                        <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-foreground/80">
                            <SlidersHorizontal className="size-3.5 text-indigo-600" />
                            <span>Filter Parameter Analytics</span>
                        </div>
                        <span className="text-[11px] text-muted-foreground/80 font-medium hidden sm:inline">
                            Sesuaikan periode & anggota tim untuk menampilkan
                            data terfilter
                        </span>
                    </div>

                    <CardContent className="px-5">
                        {/* Menggunakan flex-wrap dan justify-center */}
                        <div className="flex flex-wrap items-end justify-start gap-4">
                            {/* Dropdown 1: Tahun */}
                            <div className="w-full sm:w-32 space-y-1.5">
                                <CrmSelect
                                    className="h-10 w-full rounded-xl border border-border bg-muted/50/50 focus:bg-card px-3 text-xs font-medium focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-600 transition-all"
                                    value={year}
                                    onChange={(e) => setYear(e.target.value)}
                                >
                                    {yearOptions.map((y) => (
                                        <option key={y} value={y}>
                                            {y}
                                        </option>
                                    ))}
                                </CrmSelect>
                            </div>

                            {/* Dropdown 2: Bulan */}
                            <div className="w-full sm:w-44 space-y-1.5">
                                <CrmSelect
                                    className="h-10 w-full rounded-xl border border-border bg-muted/50/50 focus:bg-card px-3 text-xs font-medium focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-600 transition-all"
                                    value={month}
                                    onChange={(e) => setMonth(e.target.value)}
                                >
                                    {months.map((m, i) => (
                                        <option key={m} value={i + 1}>
                                            {m}
                                        </option>
                                    ))}
                                </CrmSelect>
                            </div>

                            {/* Dropdown 3: Tim Sales */}
                            <div className="w-full sm:w-60 space-y-1.5">
                                <CrmSelect
                                    className="h-10 w-full rounded-xl border border-border bg-muted/50/50 focus:bg-card px-3 text-xs font-medium focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-600 transition-all"
                                    value={salesId}
                                    onChange={(e) => setSalesId(e.target.value)}
                                >
                                    <option value="">
                                        Semua Personil Sales
                                    </option>
                                    {sales.map((s) => (
                                        <option key={s.id} value={s.id}>
                                            {s.name}
                                        </option>
                                    ))}
                                </CrmSelect>
                            </div>

                            {/* Group Tombol Aksi */}
                            <div className="flex items-center gap-2 pt-2 sm:pt-0">
                                <Button
                                    onClick={reset}
                                    variant="outline"
                                    className="h-10 px-4 border-border text-muted-foreground hover:bg-muted hover:text-foreground font-semibold rounded-xl text-xs transition-all active:scale-95"
                                >
                                    <RotateCcw className="size-3.5 mr-1.5 text-muted-foreground/80" />
                                    Reset
                                </Button>

                                <Button
                                    onClick={apply}
                                    className="h-10 px-5 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold rounded-xl text-xs shadow-md shadow-indigo-100 transition-all active:scale-95"
                                >
                                    <Filter className="size-3.5 mr-1.5 opacity-90" />
                                    Terapkan Filter
                                </Button>
                            </div>
                        </div>
                    </CardContent>
                </Card>

                {/* StatChip Grid */}
                <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                    <StatChip
                        icon={Target}
                        label="Target Penjualan"
                        value={money(totalTargetAmount)}
                        description="Nilai estimasi omset"
                        tone="blue"
                    />
                    <StatChip
                        icon={TrendingUp}
                        label="Realisasi Penjualan"
                        value={money(totalActualAmount)}
                        description={`${overallAchievement}% dari total target`}
                        tone="emerald"
                    />
                    <StatChip
                        icon={ShoppingBag}
                        label="Target Qty Barang"
                        value={formatNumber(totalTargetQty)}
                        description="Kuantitas unit ditargetkan"
                        tone="orange"
                    />
                    <StatChip
                        icon={Users}
                        label="Realisasi Qty Barang"
                        value={formatNumber(totalActualQty)}
                        description="Kuantitas terdistribusi"
                        tone="cyan"
                    />
                </div>

                {/* Table Section */}
                <Card className="shadow-xs border border-border/80 rounded-2xl bg-card overflow-hidden">
                    <CardHeader className="border-b border-slate-100 bg-muted/50/50 py-0! px-6 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
                        <div>
                            <CardTitle className="text-lg font-bold text-foreground flex items-center gap-2">
                                Detail Matriks Kinerja
                            </CardTitle>
                            <CardDescription className="text-xs text-muted-foreground mt-0.5">
                                Periode Analisis:{" "}
                                <span className="font-semibold text-foreground/80">
                                    {months[filters.month - 1] ?? "-"}{" "}
                                    {filters.year}
                                </span>
                            </CardDescription>
                        </div>
                        <div className="flex items-center gap-2">
                            <span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground font-medium bg-card border border-border px-3 py-1.5 rounded-xl shadow-2xs">
                                <Briefcase className="size-3.5 text-indigo-600" />
                                {rows.length} Personil Aktif
                            </span>
                        </div>
                    </CardHeader>
                    <CardContent className="p-0">
                        <div className="overflow-x-auto">
                            <Table className="w-full text-sm">
                                <TableHeader className="bg-muted/50/80">
                                    <TableRow className="hover:bg-transparent border-border/60">
                                        <TableHead className="px-6 py-4 font-bold text-foreground/80">
                                            Sales Person
                                        </TableHead>
                                        <TableHead className="px-6 py-4 font-bold text-foreground/80 min-w-45">
                                            Penjualan (IDR)
                                        </TableHead>
                                        <TableHead className="px-6 py-4 font-bold text-foreground/80 min-w-40">
                                            Kuantitas (Qty)
                                        </TableHead>
                                        <TableHead className="px-6 py-4 font-bold text-foreground/80 min-w-37.5">
                                            Kunjungan (Visit)
                                        </TableHead>
                                        <TableHead className="px-6 py-4 font-bold text-foreground/80 min-w-37.5">
                                            Order Dihasilkan
                                        </TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {rows.length ? (
                                        rows.map((r) => (
                                            <TableRow
                                                key={r.sales_id}
                                                className="border-slate-100 hover:bg-muted/50/70 transition-colors"
                                            >
                                                <TableCell className="px-6 py-4">
                                                    <div className="flex items-center gap-3">
                                                        <div className="size-10 rounded-xl bg-indigo-100/80 text-indigo-700 font-bold flex items-center justify-center text-xs shrink-0 shadow-2xs border border-indigo-200/50">
                                                            {r.sales_name
                                                                .slice(0, 2)
                                                                .toUpperCase()}
                                                        </div>
                                                        <div>
                                                            <div className="font-semibold text-foreground">
                                                                {r.sales_name}
                                                            </div>
                                                            <div className="text-[11px] text-muted-foreground/80 font-mono mt-0.5">
                                                                ID: #
                                                                {r.sales_id}
                                                            </div>
                                                        </div>
                                                    </div>
                                                </TableCell>

                                                {/* Omset / Penjualan */}
                                                <TableCell className="px-6 py-4">
                                                    <div className="space-y-1.5">
                                                        <div className="flex items-baseline justify-between gap-1 text-xs">
                                                            <span className="font-bold text-foreground">
                                                                {money(
                                                                    r.actual_amount,
                                                                )}
                                                            </span>
                                                            <span className="text-[11px] text-muted-foreground/80">
                                                                /{" "}
                                                                {money(
                                                                    r.target_amount,
                                                                )}
                                                            </span>
                                                        </div>
                                                        <ProgressBar
                                                            percent={
                                                                r.amount_percent
                                                            }
                                                        />
                                                    </div>
                                                </TableCell>

                                                {/* Qty */}
                                                <TableCell className="px-6 py-4">
                                                    <div className="space-y-1.5">
                                                        <div className="flex items-baseline justify-between gap-1 text-xs">
                                                            <span className="font-bold text-foreground">
                                                                {formatNumber(
                                                                    r.actual_qty,
                                                                )}
                                                            </span>
                                                            <span className="text-[11px] text-muted-foreground/80">
                                                                /{" "}
                                                                {formatNumber(
                                                                    r.target_qty,
                                                                )}
                                                            </span>
                                                        </div>
                                                        <ProgressBar
                                                            percent={
                                                                r.qty_percent
                                                            }
                                                        />
                                                    </div>
                                                </TableCell>

                                                {/* Visit */}
                                                <TableCell className="px-6 py-4">
                                                    <div className="space-y-1.5">
                                                        <div className="flex items-baseline justify-between gap-1 text-xs">
                                                            <span className="font-bold text-foreground">
                                                                {
                                                                    r.actual_visits
                                                                }{" "}
                                                                Visit
                                                            </span>
                                                            <span className="text-[11px] text-muted-foreground/80">
                                                                /{" "}
                                                                {
                                                                    r.target_visits
                                                                }
                                                            </span>
                                                        </div>
                                                        <ProgressBar
                                                            percent={
                                                                r.visit_percent
                                                            }
                                                        />
                                                    </div>
                                                </TableCell>

                                                {/* Order */}
                                                <TableCell className="px-6 py-4">
                                                    <div className="space-y-1.5">
                                                        <div className="flex items-baseline justify-between gap-1 text-xs">
                                                            <span className="font-bold text-foreground">
                                                                {
                                                                    r.actual_orders
                                                                }{" "}
                                                                Order
                                                            </span>
                                                            <span className="text-[11px] text-muted-foreground/80">
                                                                /{" "}
                                                                {
                                                                    r.target_orders
                                                                }
                                                            </span>
                                                        </div>
                                                        <ProgressBar
                                                            percent={
                                                                r.order_percent
                                                            }
                                                        />
                                                    </div>
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    ) : (
                                        <TableRow>
                                            <TableCell
                                                colSpan={5}
                                                className="py-16 text-center"
                                            >
                                                <div className="mx-auto flex flex-col items-center justify-center max-w-sm space-y-3">
                                                    <div className="p-4 bg-muted rounded-2xl text-muted-foreground/80">
                                                        <SearchX className="size-8" />
                                                    </div>
                                                    <div className="space-y-1">
                                                        <p className="font-bold text-foreground">
                                                            Belum ada data
                                                            ditemukan
                                                        </p>
                                                        <p className="text-xs text-muted-foreground">
                                                            Belum ada rekam
                                                            kinerja sales pada
                                                            periode atau filter
                                                            yang Anda pilih.
                                                        </p>
                                                    </div>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    )}
                                </TableBody>
                            </Table>
                        </div>
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}

function ProgressBar({ percent }: { percent: number }) {
    const isGood = percent >= 80;
    const isMedium = percent >= 50 && percent < 80;

    const barColor = isGood
        ? "bg-emerald-500"
        : isMedium
          ? "bg-amber-500"
          : "bg-rose-500";

    const badgeStyle = isGood
        ? "bg-emerald-50 text-emerald-700"
        : isMedium
          ? "bg-amber-50 text-amber-700"
          : "bg-rose-50 text-rose-700";

    return (
        <div className="flex items-center gap-2">
            <div className="h-1.5 w-full bg-muted rounded-full overflow-hidden">
                <div
                    className={`h-full transition-all duration-500 rounded-full ${barColor}`}
                    style={{ width: `${Math.min(percent, 100)}%` }}
                />
            </div>
            <span
                className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${badgeStyle} shrink-0`}
            >
                {percent}%
            </span>
        </div>
    );
}
