import { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { Alert, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, Stack, Typography, } from "@mui/material"; import { VendorFormFields } from "./vendor-form-fields"; import { vendorSchema, type VendorFormValues } from "@/domain/vendors/schemas/vendor-schema"; import { useCreateVendor } from "@/domain/vendors/use-cases/use-create-vendor"; import { useVendorFacets } from "@/domain/vendors/use-cases/use-vendor-facets"; import type { VendorFacetCompany } from "@/domain/vendors/types/vendor"; interface VendorCreateModalProps { open: boolean; onClose: () => void; tradeOptions: string[]; } const defaultValues: VendorFormValues = { companyName: "", contactName: "", email: "", phone: "", companyPhone: "", googleMapsUrl: "", notes: "", totalJobs: 0, address: "", city: "", state: "", zip: "", tradeSpecialties: "", isActive: true, }; export function VendorCreateModal({ open, onClose, tradeOptions }: VendorCreateModalProps) { const { data: facets, isLoading: isLoadingFacets, error: facetsError } = useVendorFacets(); const createVendor = useCreateVendor(); const [submitError, setSubmitError] = useState(null); const { control, handleSubmit, reset, setValue, formState: { errors }, } = useForm({ resolver: zodResolver(vendorSchema), defaultValues, }); useEffect(() => { if (open) { reset(defaultValues); setSubmitError(null); } }, [open, reset]); const onCompanySelected = (company: VendorFacetCompany | null) => { if (!company) return; setValue("companyPhone", company.companyPhone); setValue("email", company.email); setValue("address", company.address); setValue("city", company.city); setValue("state", company.state); setValue("zip", company.zip); setValue("googleMapsUrl", company.googleMapsUrl); }; const onSubmit = (values: VendorFormValues) => { setSubmitError(null); createVendor.mutate(values, { onSuccess: () => { onClose(); }, onError: (error: Error) => { setSubmitError(error.message || "Failed to create vendor"); }, }); }; const companies = facets?.companies ?? []; return ( Add Vendor Register a technician and their vendor company. {Boolean(facetsError) && ( Company autocomplete unavailable. You can still type a company manually. )} {Boolean(submitError) && {submitError}} {isLoadingFacets ? ( ) : ( )} ); }