import { DataTable } from '@/components/data-table';
import { DeleteConfirmation } from '@/components/modal/delete-confirmation';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogMedia,
    AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import userRoutes from '@/routes/user';
import type { User } from '@/types';
import type { PaginatedData } from '@/types/pagination';
import { Head, Link } from '@inertiajs/react';
import { KeyRound, Plus, Trash2, X } from 'lucide-react';

import { usePermission } from '@/hooks/use-permission';
import { useUserIndex } from './hooks/use-user-index';
import { getColumns } from './partials/columns';

export default function UserIndex({ users, defaultPassword }: { users: PaginatedData<User>, defaultPassword: string }) {
    const { hasPermission } = usePermission();
    const {
        isDeleteDialogOpen,
        isBulkDeleteDialogOpen,
        userToDelete,
        isResetPasswordOpen,
        userToReset,
        rowsToDelete,
        rowSelection,
        setRowSelection,
        setRowsToDelete,
        setIsDeleteDialogOpen,
        setIsBulkDeleteDialogOpen,
        setIsResetPasswordOpen,
        onResetPassword,
        confirmResetPassword,
        onDelete,
        confirmDelete,
        confirmBulkDelete,
        onToggleStatus,
    } = useUserIndex();

    const columns = getColumns({ onResetPassword, onDelete, onToggleStatus }).filter(
        (col) => col.id !== 'actions' || hasPermission('Edit:User') || hasPermission('Delete:User') || hasPermission('ResetPassword:User')
    );

    return (
        <div className="flex flex-col gap-6 p-6">
            <Head title="Pegawai" />

            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl font-bold tracking-tight">Pegawai</h1>
                </div>
                {hasPermission('Create:User') && (
                    <Link href={userRoutes.create().url}>
                        <Button className="gap-2">
                            <Plus className="size-4" />
                            Tambah
                        </Button>
                    </Link>
                )}
            </div>

            <Card className="overflow-hidden border-none shadow-lg bg-card/50 backdrop-blur-sm p-5">
                <CardContent className="p-0">
                    <DataTable
                        columns={columns}
                        data={users.data}
                        meta={users}
                        showSelection={hasPermission('DeleteAny:User')}
                        rowSelection={rowSelection}
                        onRowSelectionChange={setRowSelection}
                        filters={[
                            {
                                columnId: 'is_active',
                                title: 'Status',
                                options: [
                                    { label: 'Aktif', value: 'true' },
                                    { label: 'Tidak Aktif', value: 'false' },
                                ]
                            }
                        ]}
                        bulkActions={
                            hasPermission('DeleteAny:User')
                                ? [
                                    {
                                        label: 'Hapus Terpilih',
                                        onClick: (rows) => {
                                            setRowsToDelete(rows);
                                            setIsBulkDeleteDialogOpen(true);
                                        },
                                        icon: Trash2,
                                        variant: 'destructive',
                                    },
                                ]
                                : []
                        }
                    />
                </CardContent>
            </Card>

            {/* Reset Password Confirmation */}
            <AlertDialog open={isResetPasswordOpen} onOpenChange={setIsResetPasswordOpen}>
                <AlertDialogContent size="default">
                    <AlertDialogHeader>
                        <AlertDialogMedia className="bg-blue-100 text-blue-600 dark:bg-blue-900/20 dark:text-blue-500">
                            <KeyRound className="size-5" />
                        </AlertDialogMedia>
                        <AlertDialogTitle>Reset kata sandi?</AlertDialogTitle>
                        <AlertDialogDescription>
                            Tindakan ini akan mereset kata sandi <strong>{userToReset?.name}</strong> menjadi <strong>{defaultPassword}</strong>. Pengguna dapat mengubahnya kembali nanti.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel variant="outline" className="gap-2">
                            <X className="size-4" />
                            Batal
                        </AlertDialogCancel>
                        <AlertDialogAction onClick={confirmResetPassword} className="bg-blue-600 hover:bg-blue-700 text-white focus:ring-blue-600 gap-2">
                            <KeyRound className="size-4" />
                            Reset
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            {/* Single Delete Confirmation */}
            <DeleteConfirmation
                isOpen={isDeleteDialogOpen}
                onOpenChange={setIsDeleteDialogOpen}
                title="Hapus pegawai?"
                description={
                    <>
                        Tindakan ini tidak dapat dibatalkan. Pegawai <strong>{userToDelete?.name}</strong> akan dihapus secara permanen.
                    </>
                }
                onDelete={confirmDelete}
            />

            {/* Bulk Delete Confirmation */}
            <DeleteConfirmation
                isOpen={isBulkDeleteDialogOpen}
                onOpenChange={setIsBulkDeleteDialogOpen}
                title={`Hapus ${rowsToDelete.length} pegawai?`}
                description={
                    <>
                        Tindakan ini tidak dapat dibatalkan. <strong>{rowsToDelete.length}</strong> item yang terpilih akan dihapus secara permanen.
                    </>
                }
                onDelete={confirmBulkDelete}
            />
        </div>
    );
}

UserIndex.layout = {
    breadcrumbs: [
        {
            title: 'Master',
        },
    ],
};
