'use client'; import { useState, useRef, useMemo, useEffect } from 'react'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { formAdtEditSchema, type TFormAdtEditValues } from './schemas'; import Image from 'next/image'; import { Category, Country, City, Adt } from '@prisma/client'; import { useRouter } from 'next/navigation'; import toast from 'react-hot-toast'; interface AdtEditFormProps { adt: Adt & { price: string; category: Category & { parent: Category | null; }; }; categories: (Category & { children: Category[]; parent: Category | null; })[]; countries: Country[]; cities: City[]; } export default function AdtEditForm({ adt, categories, countries, cities }: AdtEditFormProps) { const [isSubmitting, setIsSubmitting] = useState(false); const [preview, setPreview] = useState(adt.image); const fileInputRef = useRef(null); const router = useRouter(); const form = useForm({ resolver: zodResolver(formAdtEditSchema), defaultValues: { title: adt.title, description: adt.description || '', price: String(adt.price) || '', categoryId: adt.categoryId, countryId: String(adt.countryId), cityId: String(adt.cityId), address: adt.address || '', image: adt.image || '', } }); const [selectedCountry, setSelectedCountry] = useState(adt.countryId); const [filteredCities, setFilteredCities] = useState([]); const [selectedParentCategory, setSelectedParentCategory] = useState( adt.category.parentId || adt.category.id ); const [filteredSubCategories, setFilteredSubCategories] = useState([]); const parentCategories = useMemo(() => { return categories.filter(cat => !cat.parentId); }, [categories]); useEffect(() => { if (selectedCountry) { const countryCities = cities.filter(city => city.countryId === selectedCountry); setFilteredCities(countryCities); } }, [selectedCountry, cities]); useEffect(() => { if (selectedParentCategory) { const subCategories = categories.filter(cat => cat.parentId === selectedParentCategory); setFilteredSubCategories(subCategories); } }, [selectedParentCategory, categories]); const handleImageChange = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (file) { const reader = new FileReader(); reader.onloadend = () => { setPreview(reader.result as string); form.setValue('image', reader.result as string); }; reader.readAsDataURL(file); } }; const onSubmit = async (values: TFormAdtEditValues) => { try { setIsSubmitting(true); const response = await fetch('/api/adt', { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ ...values, id: String(adt.id) }), }); if (!response.ok) { const error = await response.text(); toast.error("Ошибка при обновлении объявления: " + error); throw new Error('Error updating adt'); } const updatedAdt = await response.json(); toast.success("Объявление успешно обновлено"); router.push(`/adt/${updatedAdt.id}`); } catch (error) { console.error('Error:', error); } finally { setIsSubmitting(false); } }; const handleCountryChange = (countryId: string) => { setSelectedCountry(countryId); form.setValue('countryId', countryId); }; const handleCategoryParentChange = (categoryId: string) => { setSelectedParentCategory(categoryId); }; return (
{form.formState.errors.title && (

{form.formState.errors.title.message}

)}