import { adminToast } from '@admin/components/ui/admin-toast';
import { CreatePageLayout } from '@admin/components/ui/create-page-layout';
import { DataTable, type DataTableColumn } from '@admin/components/ui/data-table';
import { DeleteConfirmationModal } from '@admin/components/ui/delete-confirmation-modal';
import { formClassName } from '@admin/components/ui/field-styles';
import { useCrudPermissions } from '@admin/hooks/use-crud-permissions';
import { useFormResponse } from '@admin/hooks/use-form-response';
import { dashboardPersistentLayout } from '@admin/layouts/dashboard-page-layout';
import EditPhoto from '@admin/pages/gallery-photos/edit-photo';
import { PhotoFormFields } from '@admin/pages/gallery-photos/photo-form-fields';
import { Head, useForm } from '@inertiajs/react';
import { FormEvent, useState } from 'react';

type PhotoSummary = {
    id: number;
    caption: string | null;
    status: boolean;
};

type PhotoRecord = PhotoSummary & {
    image?: string;
    sort_order?: number;
};

const sidebarColumns: DataTableColumn<PhotoSummary>[] = [
    { header: 'Caption', key: 'caption', truncate: true, className: 'w-[70%]' },
    { header: 'Status', key: 'status', className: 'w-24' },
];

function CreateGalleryPhoto({ photos }: { photos: PhotoSummary[] }) {
    const { canEdit, canDelete } = useCrudPermissions('gallery-photo');
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [initialData, setInitialData] = useState<PhotoRecord | null>(null);
    const [deleteModal, setDeleteModal] = useState<{ show: boolean; photo: PhotoSummary | null }>({
        show: false,
        photo: null,
    });
    const { data, setData, post, processing, errors, reset } = useForm({
        caption: '',
        image: '',
        sort_order: photos.length + 1,
        status: true,
    });

    const action = useFormResponse({
        onComplete: () => reset(),
        loadingMessage: 'Saving photo...',
    });

    const handleSubmit = (event: FormEvent) => {
        event.preventDefault();

        post('/admin/api/create_gallery_photo', {
            onStart: action.onStart,
            onSuccess: action.onSuccess,
            onError: action.onError,
            preserveScroll: true,
        });
    };

    const handleEdit = async (row: PhotoSummary) => {
        try {
            const response = await fetch(`/admin/edit_gallery_photo/${row.id}`);
            if (!response.ok) {
                throw new Error('Failed to fetch photo');
            }

            setInitialData((await response.json()) as PhotoRecord);
            setIsEditModalOpen(true);
        } catch {
            adminToast.error('Could not load photo');
        }
    };

    return (
        <>
            <Head title="Add photo" />

            <CreatePageLayout
                indexHref={route('admin.gallery-photos')}
                form={
                    <div className="box">
                        <div className="box-header">
                            <h5 className="box-title">Add photo</h5>
                        </div>
                        <div className="box-body">
                            <form className={formClassName} noValidate onSubmit={handleSubmit}>
                                <PhotoFormFields data={data} errors={errors} setData={setData} />
                                <button type="submit" className="ti-btn ti-btn-primary" disabled={processing}>
                                    Save
                                </button>
                            </form>
                        </div>
                    </div>
                }
                sidebar={
                    <DataTable
                        data={photos}
                        columns={sidebarColumns}
                        title="Photos"
                        compact
                        onEdit={canEdit ? handleEdit : undefined}
                        onDelete={canDelete ? (row) => setDeleteModal({ show: true, photo: row }) : undefined}
                        showEdit={canEdit}
                        showDelete={canDelete}
                        noDataText="No photos yet"
                    />
                }
            />

            <DeleteConfirmationModal
                isOpen={deleteModal.show}
                onClose={() => setDeleteModal({ show: false, photo: null })}
                itemName={deleteModal.photo?.caption || 'this photo'}
                itemType="photo"
                deleteEndpoint={`/admin/api/delete_gallery_photo/${deleteModal.photo?.id ?? ''}`}
                loadingMessage="Deleting photo..."
            />

            <EditPhoto isOpen={isEditModalOpen} onClose={() => setIsEditModalOpen(false)} initialData={initialData} />
        </>
    );
}

export default Object.assign(CreateGalleryPhoto, {
    layout: dashboardPersistentLayout('Add photo', 'Add a photo to the Gallery page'),
});
