import { Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useCallback, useState } from 'react';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { DataTable } from '@/components/data-table';
import type { PaginationState, SortState } from '@/components/data-table';
import { Button } from '@/components/ui/button';
import {
    index as rolesIndex,
    create as roleCreate,
    edit as roleEdit,
    destroy as roleDestroy,
} from '@/routes/admin/settings/roles';
import { createRoleColumns } from './columns';
import type { Role } from './columns';

type Props = {
    roles: {
        data: Role[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
};

export default function RoleIndex({ roles }: Props) {
    const [deleting, setDeleting] = useState<Role | null>(null);
    const [search, setSearch] = useState('');
    const [sort, setSort] = useState<SortState>({
        column: 'created_at',
        direction: 'desc',
    });

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

    function handlePageChange(page: number) {
        router.get(
            rolesIndex.url(),
            {
                page,
                per_page: pagination.per_page,
                search,
                sort: sort.column,
                direction: sort.direction,
            },
            { preserveState: true, replace: true },
        );
    }

    function handlePerPageChange(perPage: number) {
        router.get(
            rolesIndex.url(),
            {
                page: 1,
                per_page: perPage,
                search,
                sort: sort.column,
                direction: sort.direction,
            },
            { preserveState: true, replace: true },
        );
    }

    const handleSearchChange = useCallback(
        (value: string) => {
            setSearch(value);
            router.get(
                rolesIndex.url(),
                {
                    page: 1,
                    per_page: pagination.per_page,
                    search: value,
                    sort: sort.column,
                    direction: sort.direction,
                },
                { preserveState: true, replace: true },
            );
        },
        [pagination.per_page, sort],
    );

    function handleSortChange(column: string, direction: 'asc' | 'desc') {
        setSort({ column, direction });
        router.get(
            rolesIndex.url(),
            {
                page: 1,
                per_page: pagination.per_page,
                search,
                sort: column,
                direction,
            },
            { preserveState: true, replace: true },
        );
    }

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

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

    const columns = createRoleColumns({
        handleEdit: (role) => {
            window.location.href = roleEdit.url(role.id);
        },
        handleDeleteClick: (role) => setDeleting(role),
    });

    return (
        <>
            <Head title="Role & Permission" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-semibold tracking-tight">
                            Role & Permission
                        </h2>
                    </div>
                    <Button asChild>
                        <a href={roleCreate.url()}>
                            <Plus className="h-4 w-4" />
                            Tambah
                        </a>
                    </Button>
                </div>

                <DataTable
                    columns={columns}
                    data={roles.data}
                    searchKey="name"
                    searchPlaceholder="Cari role..."
                    emptyText="Belum ada data role."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    onSortChange={handleSortChange}
                    currentSort={sort}
                    searchValue={search}
                />

                <ConfirmDialog
                    open={deleting !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Role"
                    description={`Apakah Anda yakin ingin menghapus role "${deleting?.name}"? Semua user dengan role ini akan kehilangan permission terkait.`}
                    confirmLabel="Hapus"
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}

RoleIndex.layout = {
    breadcrumbs: [
        {
            title: 'Pengaturan',
            href: '/admin/settings',
        },
        {
            title: 'Role & Permission',
            href: rolesIndex.url(),
        },
    ],
};
