import { useState } from "react";
import { Head, router } from "@inertiajs/react";
import { Plus, Users, Tag, Sparkles } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
    DataTable,
    Column,
    PaginatedData,
} from "@/components/crm/global-datatable";
import {
    DynamicFormDialog,
    FieldConfig,
} from "@/components/crm/global-formdialog";
import { ConfirmDeleteDialog } from "@/components/crm/global-alertdialog";
import AppLayout from "@/layouts/app-layout";

interface CustomerCategory {
    id: number;
    name: string;
    description: string | null;
    customers_count: number;
    created_at?: string | null;
    updated_at?: string | null;
}

interface Props {
    categories: PaginatedData<CustomerCategory>;
    filters?: {
        search?: string;
    };
}

const ENDPOINT = "/crm/customer-categories";

export default function CustomerCategoriesIndex({
    categories,
    filters,
}: Props) {
    const [formOpen, setFormOpen] = useState(false);
    const [deleteOpen, setDeleteOpen] = useState(false);
    const [selectedItem, setSelectedItem] = useState<CustomerCategory | null>(
        null,
    );
    const [deleteProcessing, setDeleteProcessing] = useState(false);

    const formFields: FieldConfig[] = [
        {
            name: "name",
            label: "Nama Kategori",
            type: "text",
            placeholder: "Misal: VIP Customer, Retailer...",
            required: true,
            colSpan: 4,
        },
        {
            name: "description",
            label: "Deskripsi",
            type: "textarea",
            placeholder: "Jelaskan karakteristik segmen kategori ini...",
            rows: 4,
            colSpan: 4,
        },
    ];

    const initialValues = {
        name: "",
        description: "",
    };

    const openCreateModal = () => {
        setSelectedItem(null);
        setFormOpen(true);
    };

    const openEditModal = (category: CustomerCategory) => {
        setSelectedItem(category);
        setFormOpen(true);
    };

    const openDeleteModal = (category: CustomerCategory) => {
        setSelectedItem(category);
        setDeleteOpen(true);
    };

    const handleDelete = () => {
        if (!selectedItem || deleteProcessing) return;

        setDeleteProcessing(true);

        router.delete(`${ENDPOINT}/${selectedItem.id}`, {
            onSuccess: () => {
                setDeleteOpen(false);
                setSelectedItem(null);
            },
            onFinish: () => {
                setDeleteProcessing(false);
            },
        });
    };

    // Definisi kolom tabel (Kolom Aksi dianiagakan dari array ini karena sudah ditangani otomatis oleh DataTable)
    const columns: Column<CustomerCategory>[] = [
        {
            header: "Nama Kategori",
            accessor: "name",
            className: "w-1/4",
            cell: (category) => (
                <div className="flex items-center gap-3 py-1">
                    <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-indigo-100 bg-indigo-50 text-indigo-600">
                        <Tag className="h-5 w-5" />
                    </div>
                    <div className="min-w-0">
                        <div className="truncate font-semibold text-foreground">
                            {category.name}
                        </div>
                        <div className="font-mono text-[11px] font-medium text-muted-foreground bg-muted px-1.5 py-0.5 rounded border border-border/60 whitespace-nowrap">
                            ID Kategori: #{category.id}
                        </div>
                    </div>
                </div>
            ),
        },
        {
            header: "Deskripsi",
            accessor: "description",
            className: "w-1/2",
            cell: (category) =>
                category.description ? (
                    <div className="line-clamp-2 max-w-md text-sm text-muted-foreground">
                        {category.description}
                    </div>
                ) : (
                    <span className="text-xs italic text-muted-foreground/60">
                        Tidak ada deskripsi
                    </span>
                ),
        },
        {
            header: "Pelanggan",
            accessor: "customers_count",
            className: "w-1/4 text-center",
            cell: (category) => {
                const count = category.customers_count ?? 0;

                return (
                    <div className="flex justify-center">
                        <Badge
                            variant="outline"
                            className={
                                count > 0
                                    ? "rounded-full border-emerald-200 bg-emerald-50 px-2.5 py-1 font-semibold text-emerald-700"
                                    : "rounded-full border-border bg-muted/50 px-2.5 py-1 font-semibold text-muted-foreground"
                            }
                        >
                            <Users className="mr-1.5 h-3.5 w-3.5" />
                            {count} Pelanggan
                        </Badge>
                    </div>
                );
            },
        },
    ];

    return (
        <AppLayout>
            <Head title="Kategori Pelanggan" />

            <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 gap-6 sm:flex-row sm:items-center sm:justify-between">
                        <div className="space-y-2">
                            <div className="inline-flex items-center gap-2 rounded-full border border-indigo-500/20 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 Customer Segmentation
                            </div>
                            <h1 className="text-3xl font-extrabold tracking-tight text-white sm:text-4xl">
                                Kategori Pelanggan
                            </h1>
                            <p className="max-w-2xl text-sm leading-relaxed text-muted-foreground/60">
                                Kelola klasifikasi pelanggan untuk membantu
                                segmentasi dan strategi penjualan CRM.
                            </p>
                        </div>

                        <Button
                            type="button"
                            onClick={openCreateModal}
                            className="h-11 gap-2 self-start rounded-xl bg-indigo-600 px-5 font-medium text-white shadow-lg shadow-indigo-600/30 transition-all hover:bg-indigo-500 sm:self-auto"
                        >
                            <Plus className="h-4 w-4" />
                            Tambah Kategori
                        </Button>
                    </div>
                </div>

                {/* Data Table Section */}
                <div className="rounded-2xl border border-border/80 bg-card p-6 shadow-sm">
                    <div className="mb-6 flex flex-col gap-1">
                        <div className="flex items-center gap-2">
                            <Tag className="h-5 w-5 text-indigo-600" />
                            <h2 className="text-lg font-bold text-foreground">
                                Daftar Kategori Pelanggan
                            </h2>
                        </div>
                        <p className="text-sm text-muted-foreground">
                            Kelola master data klasifikasi pelanggan Anda.
                        </p>
                    </div>

                    <DataTable
                        data={categories}
                        columns={columns}
                        baseUrl={ENDPOINT}
                        searchValue={filters?.search ?? ""}
                        searchPlaceholder="Cari nama kategori..."
                        showNumber
                        useSkeleton={true}
                        onEdit={(category) => openEditModal(category)}
                        onDelete={(category) => openDeleteModal(category)}
                    />
                </div>

                {/* Form Dialog Modal */}
                <DynamicFormDialog
                    open={formOpen}
                    onOpenChange={(open) => {
                        setFormOpen(open);
                        if (!open) setSelectedItem(null);
                    }}
                    title={
                        selectedItem
                            ? "Edit Kategori Pelanggan"
                            : "Tambah Kategori Pelanggan"
                    }
                    endpoint={ENDPOINT}
                    fields={formFields}
                    initialValues={initialValues}
                    itemToEdit={selectedItem}
                    primaryKey="id"
                    submitText="Simpan Kategori"
                    editText="Perbarui Kategori"
                    dialogSize="md"
                />

                {/* Confirm Delete Dialog */}
                <ConfirmDeleteDialog
                    open={deleteOpen}
                    onOpenChange={(open) => {
                        if (!deleteProcessing) setDeleteOpen(open);
                        if (!open && !deleteProcessing) setSelectedItem(null);
                    }}
                    title="Hapus Kategori Pelanggan?"
                    itemName={selectedItem?.name}
                    confirmText="Ya, Hapus"
                    loadingText="Menghapus..."
                    loading={deleteProcessing}
                    onConfirm={handleDelete}
                />
            </div>
        </AppLayout>
    );
}
