import { Head, router, usePage } from "@inertiajs/react";
import { useState } from "react";
import AppLayout from "@/layouts/app-layout";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { StatChip } from "@/components/crm/global-card";
import {
    CheckCircle2,
    Clock3,
    CreditCard,
    XCircle,
    WalletCards,
    ExternalLink,
    Eye,
    Download,
    Send,
} from "lucide-react";
import {
    DataTable,
    Column,
    FilterConfig,
} from "@/components/crm/global-datatable";

type Invoice = {
    id: number;
    invoice_number: string;
    amount: string | number;
    status: "pending" | "paid" | "failed";
    issued_at?: string | null;
    due_at?: string | null;
    paid_at?: string | null;
    payment_provider?: string | null;
    external_reference?: string | null;
    payment_url?: string | null;
    perusahaan?: {
        id: number;
        nama: string;
        kode_perusahaan: string;
        email?: string | null;
    } | null;
    subscription_plan?: {
        id: number;
        name: string;
        monthly_price: string | number;
    } | null;
};

type Props = {
    invoices: {
        data: Invoice[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
        from: number;
        to: number;
        links: { url: string | null; label: string; active: boolean }[];
    };
    filters: { search: string; status: string; provider: string };
    providers: string[];
    summary: {
        total: number;
        pending: number;
        paid: number;
        failed: number;
        paid_amount: number;
        pending_amount: number;
        paid_this_month: number;
    };
};

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

const date = (value?: string | null) =>
    value
        ? new Intl.DateTimeFormat("id-ID", { dateStyle: "medium" }).format(
              new Date(value),
          )
        : "-";

const statusLabel: Record<string, string> = {
    pending: "Menunggu",
    paid: "Lunas",
    failed: "Gagal",
};

const statusClass: Record<string, string> = {
    pending:
        "bg-amber-50 text-amber-600 dark:bg-amber-950/50 dark:text-amber-400 border-0 text-[10px] font-bold px-2.5 py-1 rounded-lg",
    paid: "bg-emerald-50 text-emerald-600 dark:bg-emerald-950/50 dark:text-emerald-400 border-0 text-[10px] font-bold px-2.5 py-1 rounded-lg",
    failed: "bg-rose-50 text-rose-600 dark:bg-rose-950/50 dark:text-rose-400 border-0 text-[10px] font-bold px-2.5 py-1 rounded-lg",
};

export default function PlatformPayments({
    invoices,
    filters,
    providers,
    summary,
}: Props) {
    const { props } = usePage<{
        flash?: { success?: string; error?: string };
    }>();

    const [status, setStatus] = useState(filters.status || "");
    const [provider, setProvider] = useState(filters.provider || "");

    const action = (url: string, message: string) => {
        if (window.confirm(message))
            router.post(url, {}, { preserveScroll: true });
    };

    const filterConfigs: FilterConfig[] = [
        {
            key: "status",
            label: "Status",
            type: "select",
            value: status,
            onChange: setStatus,
            options: [
                { label: "Menunggu", value: "pending" },
                { label: "Lunas", value: "paid" },
                { label: "Gagal", value: "failed" },
            ],
        },
        {
            key: "provider",
            label: "Provider",
            type: "select",
            value: provider,
            onChange: setProvider,
            options: providers.map((item) => ({ label: item, value: item })),
        },
    ];

    const columns: Column<Invoice>[] = [
        {
            header: "Invoice",
            headerClassName: "w-[16%] text-left font-semibold text-slate-700",
            className: "w-[16%] align-middle py-3.5",
            cell: (invoice) => (
                <div>
                    <div className="font-bold text-slate-900 dark:text-slate-100 text-xs font-mono">
                        {invoice.invoice_number}
                    </div>
                    <div className="text-[10px] uppercase tracking-wider font-semibold text-slate-400 mt-0.5">
                        {invoice.payment_provider || "manual"}
                    </div>
                </div>
            ),
        },
        {
            header: "Perusahaan",
            headerClassName: "w-[22%] text-left font-semibold text-slate-700",
            className: "w-[22%] align-middle py-3.5",
            cell: (invoice) => (
                <div>
                    <div
                        className="font-bold text-slate-800 dark:text-slate-200 text-xs truncate max-w-42.5"
                        title={invoice.perusahaan?.nama || "-"}
                    >
                        {invoice.perusahaan?.nama || "-"}
                    </div>
                    <div className="text-[11px] font-mono text-slate-400 mt-0.5">
                        {invoice.perusahaan?.kode_perusahaan || "-"}
                    </div>
                </div>
            ),
        },
        {
            header: "Paket",
            headerClassName: "w-[13%] text-left font-semibold text-slate-700",
            className: "w-[13%] align-middle py-3.5 text-xs",
            cell: (invoice) => (
                <span className="inline-block bg-slate-100 text-slate-700 px-2.5 py-0.5 rounded-md text-[11px] font-medium">
                    {invoice.subscription_plan?.name || "-"}
                </span>
            ),
        },
        {
            header: "Nominal",
            headerClassName: "w-[13%] text-right font-semibold text-slate-700",
            className:
                "w-[13%] text-right align-middle py-3.5 font-bold text-slate-900 text-xs",
            cell: (invoice) => money(invoice.amount),
        },
        {
            header: "Status",
            headerClassName: "w-[10%] text-left font-semibold text-slate-700",
            className: "w-[10%] align-middle py-3.5",
            cell: (invoice) => (
                <Badge className={statusClass[invoice.status] || ""}>
                    {statusLabel[invoice.status] || invoice.status}
                </Badge>
            ),
        },
        {
            header: "Tanggal Terbit",
            headerClassName: "w-[14%] text-left font-semibold text-slate-700",
            className: "w-[14%] align-middle py-3.5 text-xs text-slate-600",
            cell: (invoice) => (
                <div>
                    <div className="font-medium text-slate-800">
                        {date(invoice.issued_at)}
                    </div>
                    {invoice.paid_at && (
                        <div className="text-[10px] text-emerald-600 font-medium mt-0.5">
                            Bayar: {date(invoice.paid_at)}
                        </div>
                    )}
                </div>
            ),
        },
        {
            header: "Aksi",
            headerClassName: "w-[12%] text-right font-semibold text-slate-700",
            className: "w-[12%] text-right align-middle py-3.5",
            cell: (invoice) => (
                <div className="flex justify-end gap-1">
                    {/* Tombol Ubah Status jika Pending */}
                    {invoice.status === "pending" && (
                        <>
                            <Button
                                size="sm"
                                variant="outline"
                                className="h-7 px-2 rounded-lg text-[10px] font-semibold hover:bg-emerald-50 hover:text-emerald-600 hover:border-emerald-200"
                                onClick={() =>
                                    action(
                                        `/platform/payments/${invoice.id}/paid`,
                                        `Tandai ${invoice.invoice_number} sebagai lunas?`,
                                    )
                                }
                                title="Tandai Lunas"
                            >
                                Lunas
                            </Button>
                            <Button
                                size="sm"
                                variant="outline"
                                className="h-7 px-2 rounded-lg text-[10px] font-semibold text-rose-600 hover:bg-rose-50 hover:border-rose-200"
                                onClick={() =>
                                    action(
                                        `/platform/payments/${invoice.id}/failed`,
                                        `Tandai ${invoice.invoice_number} sebagai gagal?`,
                                    )
                                }
                                title="Tandai Gagal"
                            >
                                Gagal
                            </Button>
                        </>
                    )}

                    {/* Tombol Tautan Pembayaran Eksternal jika ada */}
                    {invoice.payment_url && invoice.status === "pending" && (
                        <Button
                            size="sm"
                            variant="outline"
                            className="h-7 px-2 rounded-lg text-[10px]"
                            asChild
                            title="Buka Link Bayar"
                        >
                            <a
                                href={invoice.payment_url}
                                target="_blank"
                                rel="noreferrer"
                            >
                                <ExternalLink className="size-3" />
                            </a>
                        </Button>
                    )}

                    {/* 1. Tombol Lihat Detail */}
                    <Button
                        size="sm"
                        variant="ghost"
                        className="h-7 w-7 p-0 rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-800"
                        title="Lihat Detail Invoice"
                        onClick={() => {
                            alert(
                                `Membuka detail untuk: ${invoice.invoice_number}`,
                            );
                        }}
                    >
                        <Eye className="size-3.5" />
                    </Button>

                    {/* 2. Tombol Unduh/Cetak PDF */}
                    <Button
                        size="sm"
                        variant="ghost"
                        className="h-7 w-7 p-0 rounded-lg text-slate-500 hover:bg-slate-100 hover:text-indigo-600"
                        title="Unduh PDF / Bukti Bayar"
                        onClick={() => {
                            window.open(
                                `/platform/payments/${invoice.id}/pdf`,
                                "_blank",
                            );
                        }}
                    >
                        <Download className="size-3.5" />
                    </Button>

                    {/* 3. Tombol Kirim Ulang Invoice */}
                    <Button
                        size="sm"
                        variant="ghost"
                        className="h-7 w-7 p-0 rounded-lg text-slate-500 hover:bg-slate-100 hover:text-emerald-600"
                        title="Kirim Ulang Invoice"
                        onClick={() => {
                            action(
                                `/platform/payments/${invoice.id}/resend`,
                                `Kirim ulang email tagihan ${invoice.invoice_number} ke tenant?`,
                            );
                        }}
                    >
                        <Send className="size-3.5" />
                    </Button>
                </div>
            ),
        },
    ];

    return (
        <AppLayout
            breadcrumbs={[{ title: "Pembayaran", href: "/platform/payments" }]}
        >
            <Head title="Pembayaran Platform" />
            <div className="crm-page space-y-6 pb-10">
                {/* Header Section */}
                <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                    <div>
                        <div className="flex items-center gap-2">
                            <span className="flex h-2 w-2 rounded-full bg-emerald-500 animate-pulse" />
                            <span className="text-xs font-bold uppercase tracking-wider text-indigo-600 dark:text-indigo-400">
                                Financial & Billing Operations
                            </span>
                        </div>
                        <h1 className="text-2xl font-extrabold tracking-tight text-slate-900 dark:text-slate-50 sm:text-3xl mt-1">
                            Pembayaran
                        </h1>
                        <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">
                            Kelola siklus penagihan, invoice berlangganan, serta
                            status pembayaran tenant SaaS.
                        </p>
                    </div>
                </div>

                {/* Flash Messages */}
                {props.flash?.success && (
                    <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 text-xs font-medium text-emerald-800">
                        {props.flash.success}
                    </div>
                )}
                {props.flash?.error && (
                    <div className="rounded-2xl border border-rose-200 bg-rose-50 p-4 text-xs font-medium text-rose-800">
                        {props.flash.error}
                    </div>
                )}

                {/* Metrics Grid */}
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <StatChip
                        icon={WalletCards}
                        label="Total Invoice"
                        value={summary.total.toLocaleString("id-ID")}
                        tone="blue"
                        variant="compact"
                        description="Semua tagihan terbit"
                    />
                    <StatChip
                        icon={Clock3}
                        label="Menunggu Pembayaran"
                        value={`${summary.pending.toLocaleString("id-ID")} (${money(summary.pending_amount)})`}
                        tone="orange"
                        variant="compact"
                        description="Belum dilunasi"
                    />
                    <StatChip
                        icon={CheckCircle2}
                        label="Invoice Lunas"
                        value={`${summary.paid.toLocaleString("id-ID")} (${money(summary.paid_amount)})`}
                        tone="emerald"
                        variant="compact"
                        description="Total akumulasi lunas"
                    />
                    <StatChip
                        icon={CreditCard}
                        label="Lunas Bulan Ini"
                        value={money(summary.paid_this_month)}
                        tone="violet"
                        variant="compact"
                        description="Pendapatan periode ini"
                    />
                </div>

                {/* DataTable */}
                <DataTable
                    data={invoices}
                    columns={columns}
                    filters={filterConfigs}
                    searchValue={filters.search}
                    searchPlaceholder="Cari nomor invoice, perusahaan, atau kode..."
                    baseUrl="/platform/payments"
                    showNumber={true}
                />
            </div>
        </AppLayout>
    );
}
