import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { EmptyState } from '@/components/ui/empty-state';
import { Input } from '@/components/ui/input';
import { Pagination } from '@/components/ui/pagination';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, Link, usePage } from '@inertiajs/react';
import { PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Toaster, toast } from 'sonner';

interface Transaction {
    id: string;
    invoice_number: string;
    registration_number: string;
    patient_name: string;
    insurance_name: string | null;
    cashier_name: string | null;
    transaction_datetime: string;
    payment_datetime: string | null;
    grand_total: string;
    paid_amount: string;
    insurance_covered_amount: string;
    patient_responsibility: string;
    payment_method: string;
    status: string;
    created_at: string;
}

interface PageProps {
    transactions: {
        data: Transaction[];
        links: Array<{
            url: string | null;
            label: string;
            active: boolean;
        }>;
    };
    status?: string;
}

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Dashboard', href: '/dashboard' },
    { title: 'Transaksi', href: '/transactions' },
];

export default function TransactionIndex() {
    const { transactions, status } = usePage<PageProps>().props;
    const [searchTerm, setSearchTerm] = useState('');
    const [filteredTransactions, setFilteredTransactions] = useState<Transaction[]>(transactions.data);

    useEffect(() => {
        if (status) {
            toast.success(status);
        }
    }, [status]);

    useEffect(() => {
        const results = transactions.data.filter((transaction) =>
            Object.values(transaction).some((value) => value && value.toString().toLowerCase().includes(searchTerm.toLowerCase())),
        );
        setFilteredTransactions(results);
    }, [searchTerm, transactions.data]);

    const getPaymentMethodBadgeVariant = (method: string) => {
        switch (method) {
            case 'cash':
                return 'default';
            case 'credit_card':
                return 'success';
            case 'debit_card':
                return 'info';
            case 'insurance':
                return 'warning';
            default:
                return 'outline';
        }
    };

    const getStatusBadgeVariant = (status: string) => {
        switch (status) {
            case 'completed':
                return 'default';
            case 'pending':
                return 'warning';
            case 'cancelled':
                return 'destructive';
            default:
                return 'outline';
        }
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Manajemen Transaksi" />
            <Toaster position="top-right" richColors />

            <div className="flex h-full flex-1 flex-col gap-4 rounded-xl p-4">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-2xl font-bold">Data Transaksi</h1>
                    </div>
                    <Button asChild>
                        <Link href={route('transactions.create')}>
                            <PlusIcon className="mr-2 h-4 w-4" />
                            Tambah Transaksi
                        </Link>
                    </Button>
                </div>

                <div className="w-full md:w-1/3">
                    <Input type="text" placeholder="Cari transaksi..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
                </div>

                <div>
                    {filteredTransactions.length === 0 ? (
                        <EmptyState
                            title={searchTerm ? 'Transaksi tidak ditemukan' : 'Belum ada transaksi'}
                            description={
                                searchTerm ? 'Tidak ada transaksi yang sesuai dengan pencarian Anda' : 'Mulai dengan menambahkan transaksi baru'
                            }
                            action={
                                <Button asChild>
                                    <Link href={route('transactions.create')}>
                                        <PlusIcon className="mr-2 h-4 w-4" />
                                        Tambah Transaksi
                                    </Link>
                                </Button>
                            }
                        />
                    ) : (
                        <>
                            <div className="rounded-md border">
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>No. Invoice</TableHead>
                                            <TableHead>No. Registrasi</TableHead>
                                            <TableHead>Nama Pasien</TableHead>
                                            <TableHead>Petugas Kasir</TableHead>
                                            <TableHead>Tanggal Transaksi</TableHead>
                                            <TableHead>Status</TableHead>
                                            <TableHead>Aksi</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {filteredTransactions.map((transaction) => (
                                            <TableRow key={transaction.id}>
                                                <TableCell className="font-medium">{transaction.invoice_number}</TableCell>
                                                <TableCell>{transaction.registration_number}</TableCell>
                                                <TableCell>{transaction.patient_name}</TableCell>
                                                <TableCell>{transaction.cashier_name || 'N/A'}</TableCell>
                                                <TableCell>
                                                    {new Date(transaction.transaction_datetime).toLocaleDateString('id-ID', {
                                                        day: '2-digit',
                                                        month: 'short',
                                                        year: 'numeric',
                                                        hour: '2-digit',
                                                        minute: '2-digit',
                                                    })}
                                                </TableCell>
                                                <TableCell>
                                                    <Badge variant={getStatusBadgeVariant(transaction.status)}>
                                                        {transaction.status.replace('_', ' ')}
                                                    </Badge>
                                                </TableCell>
                                                <TableCell className="flex justify-start gap-2">
                                                    <Button variant="ghost" size="icon" asChild className="hover:bg-neutral-100">
                                                        <Link href={route('transactions.edit', transaction.id)}>
                                                            <PencilIcon className="h-4 w-4" />
                                                        </Link>
                                                    </Button>

                                                    <AlertDialog>
                                                        <AlertDialogTrigger asChild>
                                                            <Button
                                                                variant="ghost"
                                                                size="icon"
                                                                className="text-red-600 hover:bg-red-50 hover:text-red-700"
                                                                disabled={transaction.status === 'completed'}
                                                            >
                                                                <Trash2Icon className="h-4 w-4" />
                                                            </Button>
                                                        </AlertDialogTrigger>
                                                        <AlertDialogContent>
                                                            <AlertDialogHeader>
                                                                <AlertDialogTitle>Apakah Anda yakin?</AlertDialogTitle>
                                                                <AlertDialogDescription>
                                                                    Data transaksi akan dihapus permanen. Tindakan ini tidak dapat dibatalkan.
                                                                </AlertDialogDescription>
                                                            </AlertDialogHeader>
                                                            <AlertDialogFooter>
                                                                <AlertDialogCancel>Batal</AlertDialogCancel>
                                                                <AlertDialogAction asChild>
                                                                    <Link
                                                                        href={route('transactions.destroy', transaction.id)}
                                                                        method="delete"
                                                                        as="button"
                                                                        preserveScroll
                                                                    >
                                                                        Hapus
                                                                    </Link>
                                                                </AlertDialogAction>
                                                            </AlertDialogFooter>
                                                        </AlertDialogContent>
                                                    </AlertDialog>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </div>

                            {transactions.links.length > 3 && (
                                <div className="mt-4">
                                    <Pagination links={transactions.links} />
                                </div>
                            )}
                        </>
                    )}
                </div>
            </div>
        </AppLayout>
    );
}
