import { useEffect, useState } from 'react'; import { useForm, useWatch } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { useTranslation } from 'react-i18next'; import { Check, Pencil, Plus, Trash2, X } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { FieldError } from '@/components/ui/FieldError'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { useOfferingCategories } from '../services/useOfferingCategories'; import { slugifyPreview } from '@/lib/slugify'; import { offeringFormSchema, type OfferingFormData } from '../schemas/offering'; import type { OfferingDto } from '../services/types'; interface OfferingFormProps { initialValues?: OfferingDto; onSubmit: (values: OfferingFormData) => void; isSubmitting: boolean; } export function OfferingForm({ initialValues, onSubmit, isSubmitting }: OfferingFormProps) { const { t } = useTranslation(); const { register, control, handleSubmit, setValue, resetField, formState: { errors, dirtyFields }, } = useForm({ resolver: zodResolver(offeringFormSchema), mode: 'onTouched', defaultValues: initialValues ?? { title: '', description: '', price: '', priceNote: '', features: [''], ctaLabel: '', featured: false, slug: '', categoryId: null, }, }); // Radix Select does not allow an empty value, so "no category" is the sentinel 'none' here // and is mapped back to null for the form value. const NO_CATEGORY = 'none'; const { data: categories, isFetching: isFetchingCategories } = useOfferingCategories(); const categoryId = useWatch({ control, name: 'categoryId' }); const selectedCategory = categoryId != null && categories?.some((c) => c.id === categoryId) ? categoryId : NO_CATEGORY; // A category that no longer exists (deleted meanwhile) falls back to "no category" so the // form never submits an id the API would reject. Only judged on fresh data: a cached list // that is being refetched may still be missing a category that does exist. useEffect(() => { if ( categories !== undefined && !isFetchingCategories && categoryId != null && !categories.some((c) => c.id === categoryId) ) { setValue('categoryId', null); } }, [categories, isFetchingCategories, categoryId, setValue]); // useFieldArray requires object-shaped array items — features is a plain string[], // so add/remove are handled directly via setValue instead. const features = useWatch({ control, name: 'features' }); const title = useWatch({ control, name: 'title' }); const slug = useWatch({ control, name: 'slug' }); const [isEditingSlug, setIsEditingSlug] = useState(false); // Once the admin has manually set a non-empty slug, it stops tracking the title — mirrors // OfferingsService: an explicit Slug always wins, an untouched one keeps auto-regenerating. const isManuallySet = dirtyFields.slug === true && slug !== undefined && slug.length > 0; const displaySlug = isManuallySet ? slug : slugifyPreview(title ?? ''); function confirmSlugEdit() { setIsEditingSlug(false); } function cancelSlugEdit() { resetField('slug'); setIsEditingSlug(false); } // Slug is auto-generated from the title server-side unless explicitly overridden here — // only send it along when the admin actually touched this field, so an untouched slug // keeps auto-regenerating when the title changes (see OfferingsService.UpdateAsync). function submitWithSlugPolicy(values: OfferingFormData) { const payload = { ...values }; if (!isManuallySet) { delete payload.slug; } onSubmit(payload); } function addFeature() { setValue('features', [...features, ''], { shouldValidate: true }); } function removeFeature(index: number) { setValue('features', features.filter((_, i) => i !== index), { shouldValidate: true }); } return (
{errors.title && }
{isEditingSlug ? (
) : (
{t('offerings.form.slugLabel')}: {displaySlug.length > 0 ? displaySlug : t('offerings.form.slugAutoHint')}
)} {errors.slug && }