import { Head, Link, router } from '@inertiajs/react';
import { Plus, RotateCcw } from 'lucide-react';
import { useState } from 'react';
import { ConfirmDialog } from '@/components/confirm-dialog';
import type { PaginationState } from '@/components/data-table';
import { DataTable } from '@/components/data-table';
import { DeleteConfirmDialog } from '@/components/delete-confirm-dialog';
import type { FilterField } from '@/components/filter-dialog';
import { FilterDialog } from '@/components/filter-dialog';
import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button';
import { usePermissions } from '@/hooks/use-permissions';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as administratorsIndex,
    create,
    destroy,
    edit,
    reset_password,
    update_user_status,
} from '@/routes/admin/users/administrators';
import type { Administrator } from './columns';
import { createAdministratorColumns } from './columns';

type Props = {
    administrators: {
        data: Administrator[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    filters: {
        gender?: string;
    };
};

const filterFields: FilterField[] = [
    {
        key: 'gender',
        label: 'Jenis Kelamin',
        options: [
            { value: 'male', label: 'Laki-laki' },
            { value: 'female', label: 'Perempuan' },
        ],
    },
];

export default function AdministratorIndex({ administrators, filters }: Props) {
    const [deleting, setDeleting] = useState<Administrator | null>(null);
    const [resetting, setResetting] = useState<Administrator | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-administrators');

    const pagination: PaginationState = {
        current_page: administrators.current_page,
        last_page: administrators.last_page,
        per_page: administrators.per_page,
        total: administrators.total,
    };

    const {
        search,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
        applyFilters,
    } = useServerTable({
        route: () => administratorsIndex.url(),
        pagination,
        filters,
    });

    function handleDelete() {
        if (!deleting) {
            return;
        }

        router.delete(destroy(deleting.id), {
            onSuccess: () => setDeleting(null),
        });
    }

    function handleResetPassword() {
        if (!resetting) {
            return;
        }

        router.patch(
            reset_password.url(resetting.id),
            {},
            {
                onSuccess: () => setResetting(null),
            },
        );
    }

    function handleUserStatusChange(admin: Administrator, isActive: boolean) {
        router.patch(
            update_user_status.url(admin.id),
            { is_active: isActive },
            { preserveScroll: true },
        );
    }

    const columns = createAdministratorColumns({
        handleEdit: (admin) => {
            router.get(edit.url(admin.id));
        },
        handleDeleteClick: (admin) => setDeleting(admin),
        handleResetPassword: (admin) => setResetting(admin),
        handleUserStatusChange,
        canUpdate: hasPermission('update-administrators'),
        canResetPassword: hasPermission('reset-administrators-password'),
        canDelete: hasPermission('delete-administrators'),
        canUpdateStatus: hasPermission('update-administrators-status'),
    });

    return (
        <>
            <Head title="Administrator" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Administrator"
                    actions={
                        canCreate && (
                            <Button asChild>
                                <Link href={create.url()}>
                                    <Plus className="h-4 w-4" />
                                    Tambah
                                </Link>
                            </Button>
                        )
                    }
                />

                <DataTable
                    columns={columns}
                    data={administrators.data}
                    searchKey="name"
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    toolbar={
                        <FilterDialog
                            fields={filterFields}
                            activeFilters={filters}
                            onApply={applyFilters}
                        />
                    }
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Administrator"
                    description={(admin) =>
                        `Apakah Anda yakin ingin menghapus administrator "${admin.profile?.full_name}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />

                <ConfirmDialog
                    open={resetting !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setResetting(null);
                        }
                    }}
                    title="Reset Kata Sandi"
                    description={
                        resetting
                            ? `Apakah Anda yakin ingin mereset kata sandi administrator "${resetting.profile?.full_name}" ke kata sandi default?`
                            : ''
                    }
                    confirmLabel="Reset"
                    confirmIcon={<RotateCcw className="h-4 w-4" />}
                    variant="default"
                    onConfirm={handleResetPassword}
                />
            </div>
        </>
    );
}
