import { formClassName, formHelpClassName } from '@admin/components/ui/field-styles';
import { useFormResponse } from '@admin/hooks/use-form-response';
import { useSingletonPermissions } from '@admin/hooks/use-singleton-permissions';
import { dashboardPersistentLayout } from '@admin/layouts/dashboard-page-layout';
import {
    BackgroundImagesFormFields,
    type BackgroundImagesFormData,
} from '@admin/pages/sections/background-images/background-images-form-fields';
import { cn } from '@admin/lib/utils';
import { Head, useForm } from '@inertiajs/react';
import { FormEvent } from 'react';

type EditBackgroundImagesProps = {
    section: BackgroundImagesFormData;
    exists: boolean;
};

function EditBackgroundImages({ section, exists }: EditBackgroundImagesProps) {
    const { canEdit } = useSingletonPermissions('background-images-section');
    const { data, setData, put, processing, errors } = useForm(section);

    const action = useFormResponse({
        loadingMessage: exists ? 'Saving changes...' : 'Saving background images...',
    });

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

        put('/admin/api/sections/background-images', {
            onStart: action.onStart,
            onSuccess: action.onSuccess,
            onError: action.onError,
            preserveScroll: true,
        });
    };

    return (
        <>
            <Head title="Background images" />

            <div className="grid grid-cols-12 gap-6">
                <div className="col-span-12">
                    <p className={cn('mb-4', formHelpClassName)}>
                        {exists
                            ? 'Manage shared marketing backgrounds for the statistics band and page breadcrumbs.'
                            : 'No background images saved yet — upload images and save once to create the record.'}
                    </p>

                    <form className={formClassName} noValidate onSubmit={handleSubmit}>
                        <BackgroundImagesFormFields data={data} errors={errors} setData={setData} />

                        {canEdit && (
                            <button type="submit" className="ti-btn ti-btn-primary" disabled={processing}>
                                {exists ? 'Save changes' : 'Save'}
                            </button>
                        )}
                        {!canEdit && <p className={formHelpClassName}>You do not have permission to edit this page.</p>}
                    </form>
                </div>
            </div>
        </>
    );
}

export default Object.assign(EditBackgroundImages, {
    layout: dashboardPersistentLayout('Background images', 'Statistics band and breadcrumb backgrounds'),
});
