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';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from '@/components/ui/alert-dialog';

interface Patient {
    id: string;
    medical_record_number: string;
    name: string;
    gender: string;
    nik: string;
    birth_date: string;
    birth_place: string;
    phone_number: string;
    blood_type: string;
    religion: string;
    is_active: boolean;
    created_at: string;
}

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

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

export default function PatientIndex() {
    const { patients, status } = usePage<PageProps>().props;
    const [searchTerm, setSearchTerm] = useState('');
    const [filteredPatients, setFilteredPatients] = useState<Patient[]>(patients.data);

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

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

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

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

                <div>
                    {filteredPatients.length === 0 ? (
                        <EmptyState
                            title={searchTerm ? "Pasien tidak ditemukan" : "Belum ada pasien"}
                            description={searchTerm ?
                                "Tidak ada pasien yang sesuai dengan pencarian Anda" :
                                "Mulai dengan menambahkan pasien baru"}
                            action={
                                <Button asChild>
                                    <Link href={route('patients.create')}>
                                        <PlusIcon className="mr-2 h-4 w-4" />
                                        Tambah Pasien
                                    </Link>
                                </Button>
                            }
                        />
                    ) : (
                        <>
                            <div className="rounded-md border">
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>No. Pasien</TableHead>
                                            <TableHead>Nama</TableHead>
                                            <TableHead>NIK</TableHead>
                                            <TableHead>Jenis Kelamin</TableHead>
                                            <TableHead>Tempat, Tanggal Lahir</TableHead>
                                            <TableHead>Golongan Darah</TableHead>
                                            <TableHead>Agama</TableHead>
                                            <TableHead>Status</TableHead>
                                            <TableHead>Aksi</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {filteredPatients.map((patient) => (
                                            <TableRow key={patient.id}>
                                                <TableCell className="font-medium">
                                                    {patient.medical_record_number}
                                                </TableCell>
                                                <TableCell>
                                                    {patient.name}
                                                    <br/>
                                                    {patient.phone_number}
                                                </TableCell>
                                                <TableCell>{patient.nik || '-'}</TableCell>
                                                <TableCell className="capitalize">
                                                    {patient.gender}
                                                </TableCell>
                                                <TableCell>
                                                    {patient.birth_place ? `${patient.birth_place}, ${new Date(patient.birth_date).toLocaleDateString('id-ID', {
                                                        day: '2-digit',
                                                        month: 'long',
                                                        year: 'numeric'
                                                    })}` : new Date(patient.birth_date).toLocaleDateString('id-ID', {
                                                        day: '2-digit',
                                                        month: 'long',
                                                        year: 'numeric'
                                                    })}
                                                </TableCell>
                                                <TableCell>
                                                    {patient.blood_type || '-'}
                                                </TableCell>
                                                <TableCell>
                                                    <span className="capitalize">
                                                        {patient.religion}
                                                    </span>
                                                </TableCell>
                                                <TableCell>
                                                    <Badge
                                                        variant={patient.is_active ? 'default' : 'destructive'}
                                                    >
                                                        {patient.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('patients.edit', patient.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 pasien akan dihapus permanen. Tindakan ini tidak dapat dibatalkan.
                                                                </AlertDialogDescription>
                                                            </AlertDialogHeader>
                                                            <AlertDialogFooter>
                                                                <AlertDialogCancel>Batal</AlertDialogCancel>
                                                                <AlertDialogAction asChild>
                                                                    <Link
                                                                        href={route('patients.destroy', patient.id)}
                                                                        method="delete"
                                                                        as="button"
                                                                        preserveScroll
                                                                    >
                                                                        Hapus
                                                                    </Link>
                                                                </AlertDialogAction>
                                                            </AlertDialogFooter>
                                                        </AlertDialogContent>
                                                    </AlertDialog>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </div>

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