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 { PlusIcon, PencilIcon, Trash2Icon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Toaster, toast } from 'sonner';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from '@/components/ui/alert-dialog';

interface Insurance {
    id: string;
    code: string;
    name: string;
    phone_number: string | null;
    contact_person: string | null;
    coverage_percentage: number;
    agreement_period: string;
    is_active: boolean;
    created_at: string;
}

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

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

export default function InsuranceIndex() {
    const { insurances, status } = usePage<PageProps>().props;
    const [searchTerm, setSearchTerm] = useState('');
    const [filteredInsurances, setFilteredInsurances] = useState<Insurance[]>(insurances.data);

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

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

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Manajemen Asuransi" />
            <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 Asuransi</h1>
                    </div>
                    <Button asChild>
                        <Link href={route('insurances.create')}>
                            <PlusIcon className="mr-2 h-4 w-4" />
                            Tambah Asuransi
                        </Link>
                    </Button>
                </div>

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

                <div>
                    {filteredInsurances.length === 0 ? (
                        <EmptyState
                            title={searchTerm ? "Asuransi tidak ditemukan" : "Belum ada asuransi"}
                            description={searchTerm ?
                                "Tidak ada asuransi yang sesuai dengan pencarian Anda" :
                                "Mulai dengan menambahkan asuransi baru"}
                            action={
                                <Button asChild>
                                    <Link href={route('insurances.create')}>
                                        <PlusIcon className="mr-2 h-4 w-4" />
                                        Tambah Asuransi
                                    </Link>
                                </Button>
                            }
                        />
                    ) : (
                        <>
                            <div className="rounded-md border">
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Kode</TableHead>
                                            <TableHead>Nama Asuransi</TableHead>
                                            <TableHead>Kontak</TableHead>
                                            <TableHead>Coverage</TableHead>
                                            <TableHead>Periode Perjanjian</TableHead>
                                            <TableHead>Status</TableHead>
                                            <TableHead>Aksi</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {filteredInsurances.map((insurance) => (
                                            <TableRow key={insurance.id}>
                                                <TableCell className="font-medium">
                                                    {insurance.code}
                                                </TableCell>
                                                <TableCell>{insurance.name}</TableCell>
                                                <TableCell>
                                                    {insurance.contact_person || '-'}
                                                    {insurance.phone_number && (
                                                        <div className="text-sm text-gray-600">
                                                            {insurance.phone_number}
                                                        </div>
                                                    )}
                                                </TableCell>
                                                <TableCell>
                                                    {insurance.coverage_percentage}%
                                                </TableCell>
                                                <TableCell>
                                                    {insurance.agreement_period}
                                                </TableCell>
                                                <TableCell>
                                                    <Badge
                                                        variant={insurance.is_active ? 'default' : 'destructive'}
                                                    >
                                                        {insurance.is_active ? 'Aktif' : 'Non-Aktif'}
                                                    </Badge>
                                                </TableCell>
                                                <TableCell className="flex justify-start gap-2">
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        asChild
                                                        className="hover:bg-neutral-100"
                                                    >
                                                        <Link href={route('insurances.edit', insurance.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"
                                                            >
                                                                <Trash2Icon className="h-4 w-4" />
                                                            </Button>
                                                        </AlertDialogTrigger>
                                                        <AlertDialogContent>
                                                            <AlertDialogHeader>
                                                                <AlertDialogTitle>Apakah Anda yakin?</AlertDialogTitle>
                                                                <AlertDialogDescription>
                                                                    Data asuransi akan dihapus permanen. Tindakan ini tidak dapat dibatalkan.
                                                                </AlertDialogDescription>
                                                            </AlertDialogHeader>
                                                            <AlertDialogFooter>
                                                                <AlertDialogCancel>Batal</AlertDialogCancel>
                                                                <AlertDialogAction asChild>
                                                                    <Link
                                                                        href={route('insurances.destroy', insurance.id)}
                                                                        method="delete"
                                                                        as="button"
                                                                        preserveScroll
                                                                    >
                                                                        Hapus
                                                                    </Link>
                                                                </AlertDialogAction>
                                                            </AlertDialogFooter>
                                                        </AlertDialogContent>
                                                    </AlertDialog>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </div>

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