import { Head } from '@inertiajs/react';
import { useState } from 'react';
import type { PaginationState } from '@/components/data-display';
import { DataTable } from '@/components/data-display';
import { PageHeader } from '@/components/layout';
import { useServerTable } from '@/hooks/use-server-table';
import type { FormHistory } from './columns';
import { createFormHistoryColumns } from './columns';
import { AttributeChangesDialog } from './attribute-changes-dialog';

type Props = {
    formHistories: {
        data: FormHistory[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    modules: string[];
    events: Record<string, string>;
};

export default function FormHistoryIndex({ formHistories, modules, events }: Props) {
    const [detailItem, setDetailItem] = useState<FormHistory | null>(null);

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

    const {
        search,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
    } = useServerTable({
        route: () => route('admin.form-histories.index'),
        pagination,
    });

    const columns = createFormHistoryColumns({
        handleDetail: (item) => setDetailItem(item),
    });

    return (
        <>
            <Head title="Log Aktivitas" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader title="Log Aktivitas" />

                <DataTable
                    columns={columns}
                    data={formHistories.data}
                    searchKey="description"
                    emptyText="Belum ada log aktivitas."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                />

                <AttributeChangesDialog
                    open={detailItem !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDetailItem(null);
                        }
                    }}
                    item={detailItem}
                />
            </div>
        </>
    );
}
