import { Head, Link, router } from '@inertiajs/react';
import { format } from 'date-fns';
import { Plus } from 'lucide-react';
import { useMemo, useState } from 'react';
import { CardTable } from '@/components/card-table';
import { DatePicker } from '@/components/date-picker';
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 { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
import {
    destroy,
    create as transactionCreate,
    index as transactionIndex,
    edit as transactionEdit,
    updateStatus as transactionUpdateStatus,
} from '@/routes/admin/manage/transactions';
import type { Transaction } from './columns';
import { TransactionCardRow } from './transaction-card';
import { TransactionItemSubRow } from './transaction-sub-row';
import { TransactionSummaryCard } from './transaction-summary-card';

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;
    };
    summary: {
        total_orders: number;
        total_subtotal: number;
        total_discount: number;
        total_amount: number;
        net_total: number;
    };
    filters: {
        status?: string;
        channel?: string;
        payment_type?: string;
        customer_id?: string;
        marketing_id?: string;
        created_by_id?: string;
        date_from?: string;
        date_to?: string;
    };
    filterOptions: {
        statusOptions: StatusOption[];
        channelOptions: StatusOption[];
        paymentTypeOptions: StatusOption[];
        customers: FilterOption[];
        employees: FilterOption[];
    };
};

export default function TransactionIndex({
    transactions,
    summary,
    filters,
    filterOptions,
}: Props) {
    const { can } = useCan();
    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),
        });
    }

    function handleUpdateStatus(transaction: Transaction, status: string) {
        router.patch(transactionUpdateStatus.url(transaction.id), { status });
    }

    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) ||
                Boolean(filters.date_from) ||
                Boolean(filters.date_to)
            }
            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>
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">Dari Tanggal</label>
                <DatePicker
                    value={filters.date_from ?? null}
                    onChange={(date) => applyFilter('date_from', date ? format(date, 'yyyy-MM-dd') : '')}
                    placeholder="Pilih tanggal mulai"
                />
            </div>
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">Sampai Tanggal</label>
                <DatePicker
                    value={filters.date_to ?? null}
                    onChange={(date) => applyFilter('date_to', date ? format(date, 'yyyy-MM-dd') : '')}
                    placeholder="Pilih tanggal akhir"
                />
            </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={
                        can('orders.create') ? (
                            <Button asChild>
                                <Link href={transactionCreate.url()}>
                                    <Plus className="h-4 w-4" />
                                    Tambah
                                </Link>
                            </Button>
                        ) : undefined
                    }
                />

                <TransactionSummaryCard summary={summary} />

                <CardTable
                    data={transactions.data}
                    getItemKey={(t) => t.id}
                    expandedKeys={expand.expandedKeys}
                    onToggleExpand={expand.toggleExpand}
                    searchValue={search}
                    onSearchChange={handleSearchChange}

                    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) => {
                                router.visit(transactionEdit.url(t.id));
                            }}
                            onDelete={(t) => setDeleting(t)}
                            onUpdateStatus={(t, status) => handleUpdateStatus(t, status)}
                        />
                    )}
                    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>
        </>
    );
}
