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 ServiceRoom {
    id: string;
    code: string;
    name: string;
    type: string;
    class: string;
    location: string;
    capacity: number;
    price: string;
    status: string;
    is_active: boolean;
    created_at: string;
}

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

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Dashboard', href: '/dashboard' },
    { title: 'Manajemen Ruangan', href: '/service-rooms' },
];

export default function ServiceRoomIndex() {
    const { rooms, status } = usePage<PageProps>().props;
    const [searchTerm, setSearchTerm] = useState('');
    const [filteredRooms, setFilteredRooms] = useState<ServiceRoom[]>(rooms.data);

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

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

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

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

                <div>
                    {filteredRooms.length === 0 ? (
                        <EmptyState
                            title={searchTerm ? 'Ruangan tidak ditemukan' : 'Belum ada ruangan'}
                            description={searchTerm ? 'Tidak ada ruangan yang sesuai dengan pencarian Anda' : 'Mulai dengan menambahkan ruangan baru'}
                            action={
                                <Button asChild>
                                    <Link href={route('service-rooms.create')}>
                                        <PlusIcon className="mr-2 h-4 w-4" />
                                        Tambah Ruangan
                                    </Link>
                                </Button>
                            }
                        />
                    ) : (
                        <>
                            <div className="rounded-md border">
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Kode</TableHead>
                                            <TableHead>Nama Ruangan</TableHead>
                                            <TableHead>Jenis</TableHead>
                                            <TableHead>Kelas</TableHead>
                                            <TableHead>Lokasi</TableHead>
                                            <TableHead>Kapasitas</TableHead>
                                            <TableHead>Harga/Hari</TableHead>
                                            <TableHead>Status</TableHead>
                                            <TableHead>Aksi</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {filteredRooms.map((room) => (
                                            <TableRow key={room.id}>
                                                <TableCell className="font-medium">{room.code}</TableCell>
                                                <TableCell>{room.name}</TableCell>
                                                <TableCell>{room.type}</TableCell>
                                                <TableCell>{room.class}</TableCell>
                                                <TableCell>{room.location}</TableCell>
                                                <TableCell>{room.capacity}</TableCell>
                                                <TableCell>{room.price}</TableCell>
                                                <TableCell>
                                                    <Badge variant={room.status === 'Tersedia' ? 'default' : 'destructive'}>{room.status}</Badge>
                                                </TableCell>
                                                <TableCell className="flex justify-start gap-2">
                                                    <Button variant="ghost" size="icon" asChild className="hover:bg-neutral-100">
                                                        <Link href={route('service-rooms.edit', room.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 ruangan akan dihapus permanen. Tindakan ini tidak dapat dibatalkan.
                                                                </AlertDialogDescription>
                                                            </AlertDialogHeader>
                                                            <AlertDialogFooter>
                                                                <AlertDialogCancel>Batal</AlertDialogCancel>
                                                                <AlertDialogAction asChild>
                                                                    <Link
                                                                        href={route('service-rooms.destroy', room.id)}
                                                                        method="delete"
                                                                        as="button"
                                                                        preserveScroll
                                                                    >
                                                                        Hapus
                                                                    </Link>
                                                                </AlertDialogAction>
                                                            </AlertDialogFooter>
                                                        </AlertDialogContent>
                                                    </AlertDialog>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </div>

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