import React, { useState, useEffect } from "react"; import { apiPatchFetcher } from "@/lib/fetcher"; import { withCache } from "@/components/mutual/context/cache/withCache"; import { Input } from "@/components/mutual/ui/input"; import { Label } from "@/components/mutual/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/mutual/ui/select"; import { Textarea } from "@/components/mutual/ui/textarea"; import { Checkbox } from "@/components/mutual/ui/checkbox"; import { RadioGroup, RadioGroupItem } from "@/components/mutual/ui/radio-group"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/mutual/ui/dropdown-menu"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/mutual/ui/form"; import { Button } from "@/components/mutual/ui/button"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import * as z from "zod"; import { getCacheData, setCacheData, clearCacheData } from "@/components/mutual/context/cache/context"; import { useRouter } from "next/navigation"; // Define form schema with zod const zodSchema = z.object({ name: z.string().min(2, { message: "Name must be at least 2 characters." }), email: z.string().email({ message: "Please enter a valid email address." }), description: z.string().min(10, { message: "Description must be at least 10 characters." }), category: z.string({ required_error: "Please select a category." }), priority: z.string({ required_error: "Please select a priority level." }), notifications: z.boolean(), terms: z.boolean().refine(val => val === true, { message: "You must accept the terms." }), attachments: z.string().optional() }); // Define the form type type FormValues = z.infer; function UpdateFromBuildComponentBase({ cacheData, cacheLoading, cacheError, refreshCache, updateCache, clearCache, activePageUrl }: { cacheData?: { [url: string]: any } | null; cacheLoading?: boolean; cacheError?: string | null; refreshCache?: (url?: string) => Promise; updateCache?: (url: string, data: any) => Promise; clearCache?: (url: string) => Promise; activePageUrl?: string; }) { const [open, setOpen] = useState(false); const [cacheLoaded, setCacheLoaded] = useState(false); const router = useRouter(); const listUrl = `/panel/${activePageUrl?.replace("/update", "")}`; const form = useForm({ resolver: zodResolver(zodSchema), defaultValues: { name: "", email: "", description: "", category: "", priority: "", notifications: false, terms: false, attachments: "" } }); // Load cached form values only once when component mounts useEffect(() => { const fetchCacheDirectly = async () => { if (activePageUrl && !cacheLoaded) { try { // Directly fetch cache data using the imported function const cachedData = await getCacheData(activePageUrl); if (cachedData) { const formValues = form.getValues(); // Create a merged data object with proper typing // Convert boolean values explicitly to handle potential string representations const notificationsValue = typeof cachedData.notifications === 'string' ? cachedData.notifications === 'true' : Boolean(cachedData.notifications); const termsValue = typeof cachedData.terms === 'string' ? cachedData.terms === 'true' : Boolean(cachedData.terms); const mergedData: FormValues = { name: cachedData.name || formValues.name || "", email: cachedData.email || formValues.email || "", description: cachedData.description || formValues.description || "", category: cachedData.category || formValues.category || "", priority: cachedData.priority || formValues.priority || "", notifications: notificationsValue, terms: termsValue, attachments: cachedData.attachments || formValues.attachments || "" }; form.reset(mergedData); } setCacheLoaded(true); if (refreshCache) { refreshCache(activePageUrl); } } catch (error) { console.error("Error fetching cache directly:", error); } } }; fetchCacheDirectly(); }, []); // Empty dependency array since we only want to run once on mount // Function to handle input blur events const handleFieldBlur = async (fieldName: keyof FormValues, value: any) => { // Only update if the value is not empty if (value && activePageUrl) { try { // Get current form values const currentValues = form.getValues(); // Prepare updated data const updatedData = { ...currentValues, [fieldName]: value }; console.log("Directly updating cache with:", updatedData); // Directly update cache using imported function await setCacheData(activePageUrl, updatedData); // Also use the context method if available (for state consistency) if (updateCache) { updateCache(activePageUrl, updatedData); } } catch (error) { console.error("Error updating cache:", error); } } }; // Type-safe submit handler const onSubmit = async (data: FormValues) => { console.log("Form submitted with data:", data); try { // Submit form data to API using PATCH for updates const response = await apiPatchFetcher({ url: "/api/test/update", isNoCache: true, body: data }); console.log("API response:", response); // Clear cache on successful submission if (activePageUrl) { try { console.log("Directly clearing cache for URL:", activePageUrl); // Directly clear cache using imported function await clearCacheData(activePageUrl); // Also use the context method if available (for state consistency) if (clearCache) { clearCache(activePageUrl); } } catch (error) { console.error("Error clearing cache:", error); } } // Reset form with empty values const emptyValues: FormValues = { name: "", email: "", description: "", category: "", priority: "", notifications: false, terms: false, attachments: "" }; form.reset(emptyValues); } catch (error) { console.error("Error submitting form:", error); } } return (
{/* back to list button */}

Update Form

{/* Input example */} ( Name { field.onBlur(); handleFieldBlur("name", e.target.value) }} /> )} /> {/* Email input example */} ( Email { field.onBlur(); handleFieldBlur("email", e.target.value) }} /> )} /> {/* Textarea example */} ( Description