import { useState } from "react";
import { Head } from "@inertiajs/react";
import {
    Plus,
    Sparkles,
    CreditCard,
    Calendar,
    UserCheck,
    Banknote,
    Receipt,
} from "lucide-react";
import AppLayout from "@/layouts/app-layout";
import { Button } from "@/components/ui/button";
import {
    Column,
    DataTable,
    FilterConfig,
} from "@/components/crm/global-datatable";
import {
    DynamicViewDialog,
    ViewDetailSchema,
} from "@/components/crm/global-viewdialog";
import {
    DynamicFormDialog,
    FieldConfig,
} from "@/components/crm/global-formdialog";

// Format Currency
const money = (v: any) =>
    new Intl.NumberFormat("id-ID", {
        style: "currency",
        currency: "IDR",
        maximumFractionDigits: 0,
    }).format(Number(v));

// Format Tanggal Indonesia
const formatDate = (dateString: string) => {
    if (!dateString) return "-";
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return dateString;

    return new Intl.DateTimeFormat("id-ID", {
        day: "numeric",
        month: "short",
        year: "numeric",
    }).format(date);
};

// Ambil Inisial Nama
const getInitials = (name: string) => {
    if (!name) return "C";
    const parts = name.trim().split(" ");
    if (parts.length >= 2) {
        return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
    }
    return name.slice(0, 2).toUpperCase();
};

// Helper Styling Badge Metode Pembayaran
const getMethodBadge = (method: string) => {
    const key = (method || "").toLowerCase();
    switch (key) {
        case "cash":
            return "bg-emerald-50 text-emerald-700 border-emerald-200/80";
        case "transfer":
            return "bg-sky-50 text-sky-700 border-sky-200/80";
        case "cheque":
        case "giro":
            return "bg-amber-50 text-amber-700 border-amber-200/80";
        default:
            return "bg-muted text-foreground/80 border-border";
    }
};

const methodOptions = [
    { label: "Cash", value: "cash" },
    { label: "Transfer", value: "transfer" },
    { label: "Cheque", value: "cheque" },
    { label: "Giro", value: "giro" },
    { label: "Lainnya", value: "other" },
];

export default function Index({
    payments,
    filters,
    invoices = [],
    collectors = [],
}: any) {
    const [method, setMethod] = useState(filters?.method || "");
    const [selectedPayment, setSelectedPayment] = useState<any | null>(null);
    const [isViewOpen, setIsViewOpen] = useState(false);

    // State untuk Modal Form Catat Pembayaran
    const [isFormOpen, setIsFormOpen] = useState(false);

    const handleOpenDetail = (payment: any) => {
        setSelectedPayment(payment);
        setIsViewOpen(true);
    };

    // Konfigurasi Field Form untuk Modal Catat Pembayaran
    const formFields: FieldConfig[] = [
        {
            name: "invoice_id",
            label: "Invoice Pelanggan",
            type: "select",
            placeholder: "-- Pilih Invoice --",
            required: true,
            colSpan: 4,
            options: invoices.map((i: any) => {
                const sisa = Math.max(
                    0,
                    Number(i?.amount || 0) - Number(i?.paid_amount || 0),
                );
                return {
                    label: `${i.invoice_number} — ${i.customer?.name || "Customer"} (Sisa: ${money(sisa)})`,
                    value: String(i.id),
                };
            }),
        },
        {
            name: "amount",
            label: "Nominal Pembayaran (Rp)",
            type: "number",
            placeholder: "Masukkan jumlah bayar...",
            required: true,
            prefix: "Rp",
            colSpan: 2,
        },
        {
            name: "payment_date",
            label: "Tanggal Pembayaran",
            type: "date",
            required: true,
            className: "w-auto",
            colSpan: 2,
        },
        {
            name: "method",
            label: "Metode Pembayaran",
            type: "select",
            required: true,
            colSpan: 2,
            options: methodOptions,
        },
        {
            name: "collector_id",
            label: "Collector / Penagih",
            type: "select",
            placeholder: "-- Pilih Collector --",
            colSpan: 2,
            options: collectors.map((u: any) => ({
                label: u.name,
                value: String(u.id),
            })),
        },
        {
            name: "proof_photo",
            label: "Bukti Pembayaran / Foto Transfer",
            type: "file",
            accept: "image/*",
            colSpan: 4,
        },
        {
            name: "notes",
            label: "Catatan Tambahan",
            type: "textarea",
            placeholder:
                "Tambahkan catatan penagihan atau keterangan transaksi...",
            rows: 3,
            colSpan: 4,
        },
    ];

    // Nilai Default Awal Form
    const initialFormValues = {
        invoice_id: "",
        amount: "",
        payment_date: new Date().toISOString().slice(0, 10),
        method: "transfer",
        collector_id: "",
        proof_photo: null,
        notes: "",
    };

    // Schema Modal Detail Payment
    const detailSchema: ViewDetailSchema<any>[] = [
        {
            label: "Nomor Invoice",
            render: (p) => p.invoice?.invoice_number || "-",
        },
        {
            label: "Customer",
            render: (p) => p.invoice?.customer?.name || "-",
        },
        {
            label: "Tanggal Pembayaran",
            render: (p) => formatDate(p.payment_date),
        },
        {
            label: "Nominal Pembayaran",
            render: (p) => money(p.amount || 0),
        },
        {
            label: "Metode Pembayaran",
            render: (p) => (
                <span className="capitalize font-semibold text-foreground/80">
                    {p.method}
                </span>
            ),
        },
        {
            label: "Collector / Penagih",
            render: (p) => p.collector?.name || "-",
        },
        {
            label: "Catatan",
            render: (p) => p.notes || "-",
        },
    ];

    // Kolom Tabel Utama (Tanpa definisi manual kolom Aksi)
    const columns: Column<any>[] = [
        {
            header: "INVOICE",
            sortable: true,
            sortKey: "invoice_id",
            cell: (p) => (
                <div className="flex items-center gap-3 py-0.5">
                    <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-indigo-50 border border-indigo-100 text-indigo-600 font-bold shadow-2xs">
                        <Receipt className="h-4 w-4" />
                    </div>
                    <div className="flex flex-col min-w-0">
                        <Button
                            type="button"
                            variant="ghost"
                            onClick={() => handleOpenDetail(p)}
                            className="font-bold text-foreground hover:text-indigo-600 text-left transition-colors truncate cursor-pointer"
                        >
                            {p.invoice?.invoice_number || "-"}
                        </Button>
                    </div>
                </div>
            ),
        },
        {
            header: "PELANGGAN / CUSTOMER",
            cell: (p) => {
                const customerName =
                    p.invoice?.customer?.name || "Customer Umum";
                return (
                    <div className="flex items-center gap-2.5">
                        <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground font-bold text-xs border border-border">
                            {getInitials(customerName)}
                        </div>
                        <span className="font-semibold text-foreground text-xs truncate max-w-45">
                            {customerName}
                        </span>
                    </div>
                );
            },
        },
        {
            header: "TANGGAL BAYAR",
            sortable: true,
            sortKey: "payment_date",
            className: "text-center whitespace-nowrap",
            cell: (p) => (
                <div className="inline-flex items-center gap-1.5 text-xs font-medium text-foreground/80 bg-muted/50 px-2.5 py-1 rounded-md border border-border/80">
                    <Calendar className="h-3.5 w-3.5 text-muted-foreground/80" />
                    {formatDate(p.payment_date)}
                </div>
            ),
        },
        {
            header: "NOMINAL TERBAYAR",
            sortable: true,
            sortKey: "amount",
            className: "text-right whitespace-nowrap",
            cell: (p) => (
                <div className="inline-flex items-center gap-1.5 font-bold text-emerald-600 text-xs bg-emerald-50/50 px-2.5 py-1 rounded-lg border border-emerald-100">
                    <Banknote className="h-3.5 w-3.5 text-emerald-500" />
                    {money(p.amount)}
                </div>
            ),
        },
        {
            header: "METODE",
            sortable: true,
            sortKey: "method",
            className: "text-center whitespace-nowrap",
            cell: (p) => (
                <div className="flex justify-center">
                    <span
                        className={`inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-semibold capitalize border shadow-2xs ${getMethodBadge(
                            p.method,
                        )}`}
                    >
                        <CreditCard className="h-3 w-3 opacity-70" />
                        {p.method}
                    </span>
                </div>
            ),
        },
        {
            header: "COLLECTOR / PENAGIH",
            accessor: "collector",
            className: "text-center",
            cell: (p) => (
                <div className="flex items-center justify-center gap-1.5 text-xs font-medium text-muted-foreground">
                    <UserCheck className="h-3.5 w-3.5 text-muted-foreground/80 shrink-0" />
                    <span className="truncate max-w-35">
                        {p.collector?.name || "-"}
                    </span>
                </div>
            ),
        },
    ];

    const filterConfigs: FilterConfig[] = [
        {
            key: "method",
            label: "Metode",
            options: methodOptions,
            value: method,
            onChange: (val) => setMethod(val),
        },
    ];

    return (
        <AppLayout breadcrumbs={[{ title: "Payments", href: "/crm/payments" }]}>
            <Head title="Riwayat Pembayaran" />
            <div className="crm-page space-y-6 pb-10">
                {/* Header Banner */}
                <div className="relative overflow-hidden rounded-2xl bg-linear-to-r from-slate-950 via-slate-900 to-indigo-950 p-8 text-white shadow-xl">
                    <div className="relative z-10 flex flex-col justify-between gap-6 md:flex-row md:items-center">
                        <div className="space-y-2">
                            <div className="inline-flex items-center gap-1.5 rounded-full border border-indigo-500/30 bg-indigo-500/10 px-3 py-1 text-xs font-medium text-indigo-300 backdrop-blur-md">
                                <Sparkles className="h-3.5 w-3.5 text-indigo-400" />
                                CRM PAYMENT ENGINE
                            </div>
                            <h1 className="text-3xl font-extrabold tracking-tight text-white md:text-4xl">
                                Riwayat Pembayaran
                            </h1>
                            <p className="max-w-2xl text-sm text-muted-foreground/60 leading-relaxed">
                                Pantau dan kelola seluruh riwayat transaksi
                                pembayaran invoice serta metode penerimaan kas
                                dari pelanggan secara real-time.
                            </p>
                        </div>

                        {/* Tombol Membuka Modal Form Pembayaran */}
                        <Button
                            onClick={() => setIsFormOpen(true)}
                            className="h-11 rounded-xl bg-indigo-600 px-5 font-medium text-white shadow-lg shadow-indigo-600/30 transition-all hover:bg-indigo-500 gap-2 cursor-pointer self-start md:self-auto"
                        >
                            <Plus className="h-4 w-4" />
                            Catat Pembayaran
                        </Button>
                    </div>
                </div>

                {/* Main Card Wrapper untuk DataTable */}
                <div className="rounded-2xl border border-border/80 bg-card p-6 shadow-sm space-y-4">
                    <DataTable
                        data={payments}
                        columns={columns}
                        searchPlaceholder="Cari nomor invoice atau customer..."
                        searchValue={filters?.search || ""}
                        filters={filterConfigs}
                        baseUrl="/crm/payments"
                        showNumber={true}
                        useSkeleton={true}
                        onView={handleOpenDetail}
                    />
                </div>

                {/* Modal View Detail Reusable */}
                <DynamicViewDialog
                    open={isViewOpen}
                    onOpenChange={setIsViewOpen}
                    title="Pembayaran"
                    data={selectedPayment}
                    schema={detailSchema}
                />

                {/* Global Dynamic Form Dialog untuk Catat Pembayaran */}
                <DynamicFormDialog
                    open={isFormOpen}
                    onOpenChange={setIsFormOpen}
                    title="Pembayaran"
                    endpoint="/crm/payments"
                    fields={formFields}
                    initialValues={initialFormValues}
                    dialogSize="md"
                    submitText="Simpan Pembayaran"
                />
            </div>
        </AppLayout>
    );
}
