import { Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useMemo, useState } from 'react';
import { CardTable } from '@/components/card-table';
import { DeleteConfirmDialog } from '@/components/delete-confirm-dialog';
import { FilterPopover } from '@/components/filter-popover';
import { useCardTableExpand } from '@/components/hooks/use-card-table-expand';
import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button';
import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
} from '@/components/ui/combobox';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useServerTable } from '@/hooks/use-server-table';
import {
    destroy,
    create as transactionCreate,
    index as transactionIndex,
    edit as transactionEdit,
} from '@/routes/admin/manage/transactions';
import type { Transaction } from './columns';
import { TransactionCardRow } from './transaction-card';
import { TransactionItemSubRow } from './transaction-sub-row';

type FilterOption = {
    id: number;
    name: string;
};

type StatusOption = {
    value: string;
    label: string;
};

type Props = {
    transactions: {
        data: Transaction[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    filters: {
        status?: string;
        channel?: string;
        payment_type?: string;
        customer_id?: string;
        marketing_id?: string;
        created_by_id?: string;
    };
    filterOptions: {
        statusOptions: StatusOption[];
        channelOptions: StatusOption[];
        paymentTypeOptions: StatusOption[];
        customers: FilterOption[];
        employees: FilterOption[];
    };
};

export default function TransactionIndex({
    transactions,
    filters,
    filterOptions,
}: Props) {
    const [deleting, setDeleting] = useState<Transaction | null>(null);
    const expand = useCardTableExpand(true);

    const pagination = {
        current_page: transactions.current_page,
        last_page: transactions.last_page,
        per_page: transactions.per_page,
        total: transactions.total,
    };

    const {
        search,
        filterOpen,
        setFilterOpen,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
        applyFilter,
        clearFilters,
    } = useServerTable({
        route: () => transactionIndex.url(),
        pagination,
        filters,
    });

    const selectedCustomer = useMemo(
        () =>
            filterOptions.customers.find(
                (c) => String(c.id) === filters.customer_id,
            ) ?? null,
        [filterOptions.customers, filters.customer_id],
    );

    const selectedMarketing = useMemo(
        () =>
            filterOptions.employees.find(
                (e) => String(e.id) === filters.marketing_id,
            ) ?? null,
        [filterOptions.employees, filters.marketing_id],
    );

    const selectedEmployee = useMemo(
        () =>
            filterOptions.employees.find(
                (e) => String(e.id) === filters.created_by_id,
            ) ?? null,
        [filterOptions.employees, filters.created_by_id],
    );

    function handleDelete() {
        if (!deleting) {
            return;
        }

        router.delete(destroy.url(deleting.id), {
            onSuccess: () => setDeleting(null),
        });
    }

    const filterToolbar = (
        <FilterPopover
            open={filterOpen}
            onOpenChange={setFilterOpen}
            filters={filters}
            hasActiveFilters={
                Boolean(filters.status) ||
                Boolean(filters.channel) ||
                Boolean(filters.payment_type) ||
                Boolean(filters.customer_id) ||
                Boolean(filters.marketing_id) ||
                Boolean(filters.created_by_id)
            }
            onClear={clearFilters}
        >
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">Status</label>
                <Select
                    value={filters.status ?? 'all'}
                    onValueChange={(value) => applyFilter('status', value)}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua Status" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Semua Status</SelectItem>
                        {filterOptions.statusOptions.map((opt) => (
                            <SelectItem key={opt.value} value={opt.value}>
                                {opt.label}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            </div>
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Channel
                </label>
                <Select
                    value={filters.channel ?? 'all'}
                    onValueChange={(value) => applyFilter('channel', value)}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua Channel" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Semua Channel</SelectItem>
                        {filterOptions.channelOptions.map((opt) => (
                            <SelectItem key={opt.value} value={opt.value}>
                                {opt.label}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            </div>
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Tipe Pembayaran
                </label>
                <Select
                    value={filters.payment_type ?? 'all'}
                    onValueChange={(value) =>
                        applyFilter('payment_type', value)
                    }
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua Tipe" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Semua Tipe</SelectItem>
                        {filterOptions.paymentTypeOptions.map((opt) => (
                            <SelectItem key={opt.value} value={opt.value}>
                                {opt.label}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            </div>
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Pelanggan
                </label>
                <Combobox
                    items={filterOptions.customers}
                    itemToStringLabel={(c) => c.name}
                    value={selectedCustomer}
                    onValueChange={(value) =>
                        applyFilter(
                            'customer_id',
                            value ? String(value.id) : '',
                        )
                    }
                >
                    <ComboboxInput
                        placeholder="Pilih pelanggan..."
                        className="w-full"
                    />
                    <ComboboxContent>
                        <ComboboxEmpty>
                            Tidak ada pelanggan ditemukan.
                        </ComboboxEmpty>
                        <ComboboxList>
                            {(customer) => (
                                <ComboboxItem value={customer}>
                                    {customer.name}
                                </ComboboxItem>
                            )}
                        </ComboboxList>
                    </ComboboxContent>
                </Combobox>
            </div>
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Marketing
                </label>
                <Combobox
                    items={filterOptions.employees}
                    itemToStringLabel={(e) => e.name}
                    value={selectedMarketing}
                    onValueChange={(value) =>
                        applyFilter(
                            'marketing_id',
                            value ? String(value.id) : '',
                        )
                    }
                >
                    <ComboboxInput
                        placeholder="Pilih marketing..."
                        className="w-full"
                    />
                    <ComboboxContent>
                        <ComboboxEmpty>
                            Tidak ada marketing ditemukan.
                        </ComboboxEmpty>
                        <ComboboxList>
                            {(employee) => (
                                <ComboboxItem value={employee}>
                                    {employee.name}
                                </ComboboxItem>
                            )}
                        </ComboboxList>
                    </ComboboxContent>
                </Combobox>
            </div>
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Pegawai
                </label>
                <Combobox
                    items={filterOptions.employees}
                    itemToStringLabel={(e) => e.name}
                    value={selectedEmployee}
                    onValueChange={(value) =>
                        applyFilter(
                            'created_by_id',
                            value ? String(value.id) : '',
                        )
                    }
                >
                    <ComboboxInput
                        placeholder="Pilih pegawai..."
                        className="w-full"
                    />
                    <ComboboxContent>
                        <ComboboxEmpty>
                            Tidak ada pegawai ditemukan.
                        </ComboboxEmpty>
                        <ComboboxList>
                            {(employee) => (
                                <ComboboxItem value={employee}>
                                    {employee.name}
                                </ComboboxItem>
                            )}
                        </ComboboxList>
                    </ComboboxContent>
                </Combobox>
            </div>
        </FilterPopover>
    );

    return (
        <>
            <Head title="Transaksi" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Transaksi"
                    actions={
                        <Button asChild>
                            <a href={transactionCreate.url()}>
                                <Plus className="h-4 w-4" />
                                Tambah
                            </a>
                        </Button>
                    }
                />

                <CardTable
                    data={transactions.data}
                    getItemKey={(t) => t.id}
                    expandedKeys={expand.expandedKeys}
                    onToggleExpand={expand.toggleExpand}
                    searchValue={search}
                    onSearchChange={handleSearchChange}
                    searchPlaceholder="Cari berdasarkan produk atau nomor transaksi..."
                    toolbar={filterToolbar}
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    renderCard={({
                        item,
                        index,
                        isExpanded,
                        onToggleExpand,
                    }) => (
                        <TransactionCardRow
                            transaction={item}
                            index={
                                (pagination.current_page - 1) *
                                    pagination.per_page +
                                index +
                                1
                            }
                            isExpanded={isExpanded}
                            onToggleExpand={onToggleExpand}
                            onEdit={(t) => {
                                window.location.href = transactionEdit.url(t.id);
                            }}
                            onDelete={(t) => setDeleting(t)}
                        />
                    )}
                    renderSubContent={(transaction) => (
                        <TransactionItemSubRow transaction={transaction} />
                    )}
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Transaksi"
                    description="Apakah Anda yakin ingin menghapus transaksi ini? Stok akan dikembalikan. Tindakan ini tidak dapat dibatalkan."
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}
