import { useState } from "react";
import { Head } from "@inertiajs/react";
import {
    Plus,
    Sparkles,
    FileText,
    Calendar,
    AlertCircle,
    Receipt,
} from "lucide-react";
import AppLayout from "@/layouts/app-layout";
import { Button } from "@/components/ui/button";
import { StatusBadge } from "@/components/crm-data-table";
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";

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

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);
};

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();
};

const statusOptions = [
    { label: "Unpaid", value: "unpaid" },
    { label: "Partial", value: "partial" },
    { label: "Paid", value: "paid" },
    { label: "Overdue", value: "overdue" },
    { label: "Void", value: "void" },
];

export default function Index({ invoices, filters, orders = [] }: any) {
    const [status, setStatus] = useState(filters?.status || "");
    const [selectedInvoice, setSelectedInvoice] = useState<any | null>(null);
    const [isViewOpen, setIsViewOpen] = useState(false);

    // State Form Dialog (Tambah / Edit Invoice)
    const [isFormOpen, setIsFormOpen] = useState(false);

    const handleOpenDetail = (invoice: any) => {
        setSelectedInvoice(invoice);
        setIsViewOpen(true);
    };

    // Konfigurasi Field Form untuk DynamicFormDialog
    const formFields: FieldConfig[] = [
        {
            name: "order_id",
            label: "Order Approved",
            type: "select",
            placeholder: "-- Pilih Order Approved --",
            required: true,
            colSpan: 4,
            options: orders.map((o: any) => ({
                label: `${o.order_number} — ${o.customer?.name || "Customer"} (${money(o.grand_total)})`,
                value: String(o.id),
            })),
        },
        {
            name: "amount",
            label: "Total Tagihan (Rp)",
            type: "number",
            placeholder: "Masukkan total tagihan...",
            required: true,
            prefix: "Rp",
            colSpan: 2,
        },
        {
            name: "paid_amount",
            label: "Pembayaran Awal / DP (Rp)",
            type: "number",
            placeholder: "0",
            prefix: "Rp",
            colSpan: 2,
        },
        {
            name: "invoice_date",
            label: "Tanggal Invoice",
            type: "date",
            required: true,
            colSpan: 2,
            className: "w-auto",
        },
        {
            name: "due_date",
            label: "Jatuh Tempo",
            type: "date",
            required: true,
            colSpan: 2,
            className: "w-auto",
        },
    ];

    // Nilai Default Awal Form
    const initialFormValues = {
        order_id: "",
        customer_id: "",
        amount: "",
        paid_amount: "0",
        invoice_date: new Date().toISOString().slice(0, 10),
        due_date: new Date(Date.now() + 30 * 86400000)
            .toISOString()
            .slice(0, 10),
    };

    // Schema Modal Detail
    const detailSchema: ViewDetailSchema<any>[] = [
        { label: "Nomor Invoice", render: (i) => i.invoice_number || "-" },
        { label: "Nomor Order", render: (i) => i.order?.order_number || "-" },
        { label: "Customer", render: (i) => i.customer?.name || "-" },
        { label: "Tanggal Invoice", render: (i) => formatDate(i.invoice_date) },
        { label: "Jatuh Tempo", render: (i) => formatDate(i.due_date) },
        { label: "Total Tagihan", render: (i) => money(i.amount || 0) },
        { label: "Jumlah Terbayar", render: (i) => money(i.paid_amount || 0) },
        { label: "Status", render: (i) => <StatusBadge status={i.status} /> },
    ];

    // Definisi Kolom Utama (Bersih tanpa kolom 'Aksi' manual)
    const columns: Column<any>[] = [
        {
            header: "INVOICE & ORDER",
            sortable: true,
            sortKey: "invoice_number",
            cell: (i) => (
                <div className="flex items-center gap-3 py-1">
                    <div className="flex h-10 w-10 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-5 w-5" />
                    </div>
                    <div className="flex flex-col min-w-0">
                        <Button
                            type="button"
                            variant="ghost"
                            onClick={() => handleOpenDetail(i)}
                            className="font-bold text-foreground hover:text-indigo-600 text-left transition-colors truncate"
                        >
                            {i.invoice_number}
                        </Button>
                        <div className="flex items-center gap-1 text-xs text-muted-foreground/80 mt-0.5">
                            <FileText className="h-3 w-3 shrink-0 text-muted-foreground/60" />
                            <span className="truncate">
                                Order: {i.order?.order_number || "-"}
                            </span>
                        </div>
                    </div>
                </div>
            ),
        },
        {
            header: "PELANGGAN / CUSTOMER",
            cell: (i) => {
                const customerName = i.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 INVOICE",
            sortable: true,
            sortKey: "invoice_date",
            className: "text-center whitespace-nowrap",
            cell: (i) => (
                <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(i.invoice_date)}
                </div>
            ),
        },
        {
            header: "JATUH TEMPO",
            sortable: true,
            sortKey: "due_date",
            className: "text-center whitespace-nowrap",
            cell: (i) => {
                const isOverdue =
                    i.status === "overdue" ||
                    (i.status !== "paid" && new Date(i.due_date) < new Date());

                return (
                    <div
                        className={`inline-flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-md border ${
                            isOverdue
                                ? "bg-rose-50 text-rose-700 border-rose-200"
                                : "bg-muted/50 text-foreground/80 border-border/80"
                        }`}
                    >
                        {isOverdue && (
                            <AlertCircle className="h-3.5 w-3.5 text-rose-500 shrink-0" />
                        )}
                        {formatDate(i.due_date)}
                    </div>
                );
            },
        },
        {
            header: "TAGIHAN & STATUS BAYAR",
            sortable: true,
            sortKey: "amount",
            className: "text-right min-w-[190px]",
            cell: (i) => {
                const amount = Number(i.amount) || 0;
                const paid = Number(i.paid_amount) || 0;
                const percent =
                    amount > 0
                        ? Math.min(Math.round((paid / amount) * 100), 100)
                        : 0;

                return (
                    <div className="flex flex-col items-end space-y-1">
                        <span className="font-bold text-foreground text-xs">
                            {money(amount)}
                        </span>
                        <div className="w-full max-w-35 space-y-1">
                            <div className="flex justify-between items-center text-[10px] text-muted-foreground">
                                <span>Terbayar:</span>
                                <span className="font-semibold text-emerald-600">
                                    {money(paid)}
                                </span>
                            </div>
                            <div className="w-full bg-muted rounded-full h-1.5 overflow-hidden border border-border/60">
                                <div
                                    className={`h-full rounded-full transition-all duration-300 ${
                                        percent === 100
                                            ? "bg-emerald-500"
                                            : percent > 0
                                              ? "bg-amber-500"
                                              : "bg-slate-300"
                                    }`}
                                    style={{ width: `${percent}%` }}
                                />
                            </div>
                        </div>
                    </div>
                );
            },
        },
        {
            header: "STATUS",
            sortable: true,
            sortKey: "status",
            className: "text-center",
            cell: (i) => (
                <div className="flex justify-center">
                    <StatusBadge status={i.status} />
                </div>
            ),
        },
    ];

    const filterConfigs: FilterConfig[] = [
        {
            key: "status",
            label: "Status",
            options: statusOptions,
            value: status,
            onChange: (val) => setStatus(val),
        },
    ];

    return (
        <AppLayout breadcrumbs={[{ title: "Invoices", href: "/crm/invoices" }]}>
            <Head title="Daftar Invoices" />
            <div className="crm-page space-y-6 pb-10">
                {/* Banner Header */}
                <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" />
                                MINANGA CRM BILLING ENGINE
                            </div>
                            <h1 className="text-3xl font-extrabold tracking-tight text-white md:text-4xl">
                                Daftar Invoice & Penagihan
                            </h1>
                            <p className="max-w-2xl text-sm text-muted-foreground/60 leading-relaxed">
                                Kelola tagihan, pantau tanggal jatuh tempo, dan
                                perbarui status penagihan pembayaran pelanggan
                                secara terpusat.
                            </p>
                        </div>

                        <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" />
                            Buat Invoice Baru
                        </Button>
                    </div>
                </div>

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

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

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