import { CrudCreateLink } from '@admin/components/ui/crud-create-link';
import { DataTable, type DataTableColumn } from '@admin/components/ui/data-table';
import { DeleteConfirmationModal } from '@admin/components/ui/delete-confirmation-modal';
import { useCrudPermissions } from '@admin/hooks/use-crud-permissions';
import { dashboardPersistentLayout } from '@admin/layouts/dashboard-page-layout';
import { type DocumentTemplateRow } from '@admin/types/document';
import { Head, Link, router } from '@inertiajs/react';
import { useState } from 'react';

type DocumentTemplatesIndexProps = {
    templates: DocumentTemplateRow[];
};

function DocumentTemplatesIndex({ templates }: DocumentTemplatesIndexProps) {
    const { canEdit, canDelete } = useCrudPermissions('documentation');
    const [deleteModal, setDeleteModal] = useState<{ show: boolean; template: DocumentTemplateRow | null }>({
        show: false,
        template: null,
    });

    const columns: DataTableColumn<DocumentTemplateRow>[] = [
        {
            header: 'Name',
            key: 'name',
            truncate: false,
            render: (row) => (
                <div className="min-w-0 py-0.5">
                    <p className="font-medium leading-snug whitespace-normal">{row.name}</p>
                    {row.is_child ? (
                        <p className="mt-0.5 text-xs text-textmuted">{row.parent_name ?? 'Child template'}</p>
                    ) : row.children_count > 0 ? (
                        <p className="mt-0.5 text-xs text-textmuted">
                            {row.children_count} {row.children_count === 1 ? 'child' : 'children'}
                        </p>
                    ) : null}
                </div>
            ),
        },
        {
            header: 'Layout',
            key: 'style',
            className: 'w-36',
            render: (row) => {
                if (row.style === 'invoice') {
                    return 'Invoice';
                }

                if (row.style === 'builder') {
                    return 'Visual builder';
                }

                return 'Plain';
            },
        },
        {
            header: 'Unit',
            key: 'unit_name',
            truncate: true,
            className: 'w-36',
            render: (row) => row.unit_name ?? '—',
        },
        { header: 'Documents', key: 'records_count', truncate: false, className: 'w-28' },
        { header: 'Status', key: 'status', className: 'w-24 whitespace-nowrap' },
    ];

    return (
        <>
            <Head title="Document templates" />

            <div className="grid grid-cols-12 gap-6">
                <div className="col-span-12">
                    <div className="mb-4 flex flex-wrap gap-2">
                        <CrudCreateLink
                            href={route('admin.qr-codes.documentations.templates.create')}
                            label="Create template"
                            resource="documentation"
                            className="ti-btn ti-btn-primary"
                        />
                        <Link href={route('admin.qr-codes.documentations')} className="ti-btn ti-btn-outline-primary">
                            Documentations
                        </Link>
                    </div>
                    <DataTable
                        data={templates}
                        columns={columns}
                        title="Document templates"
                        itemsPerPage={10}
                        onEdit={
                            canEdit
                                ? (row) =>
                                      router.visit(
                                          row.edit_url ??
                                              route('admin.qr-codes.documentations.templates.edit', row.id),
                                      )
                                : undefined
                        }
                        onDelete={canDelete ? (row) => setDeleteModal({ show: true, template: row }) : undefined}
                        showEdit={canEdit}
                        showDelete={canDelete}
                        noDataText="No templates found"
                    />
                </div>
            </div>

            <DeleteConfirmationModal
                isOpen={deleteModal.show}
                onClose={() => setDeleteModal({ show: false, template: null })}
                itemName={deleteModal.template?.name ?? 'this template'}
                itemType="document template"
                deleteEndpoint={`/admin/api/delete_document_template/${deleteModal.template?.id ?? ''}`}
                loadingMessage="Deleting template..."
            />
        </>
    );
}

export default Object.assign(DocumentTemplatesIndex, {
    layout: dashboardPersistentLayout('Document templates', 'Parent and child templates for QR-backed documents'),
});
