'use client'; import { useForm, Controller } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Switch } from '@/components/ui/switch'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { useCreateOrganization, useUpdateOrganization } from '@/hooks/use-master-data'; import { useEffect } from 'react'; import { Organization } from '@/types/organization'; // Organization role types matching database const ORGANIZATION_ROLES = [ { value: '1', label: 'Owner' }, { value: '2', label: 'Designer' }, { value: '3', label: 'Consultant' }, { value: '4', label: 'Contractor' }, { value: '5', label: 'Third Party' }, ] as const; const organizationSchema = z.object({ organizationCode: z.string().min(1, 'Organization Code is required'), organizationName: z.string().min(1, 'Organization Name is required'), roleId: z.string().optional(), isActive: z.boolean().optional(), }); type OrganizationFormData = z.infer; interface OrganizationDialogProps { open: boolean; onOpenChange: (open: boolean) => void; organization?: Organization | null; } export function OrganizationDialog({ open, onOpenChange, organization }: OrganizationDialogProps) { const createOrg = useCreateOrganization(); const updateOrg = useUpdateOrganization(); const { register, handleSubmit, reset, setValue, watch, control, formState: { errors }, } = useForm({ resolver: zodResolver(organizationSchema), defaultValues: { organizationCode: '', organizationName: '', roleId: '', isActive: true, }, }); useEffect(() => { if (organization) { reset({ organizationCode: organization.organizationCode, organizationName: organization.organizationName, roleId: organization.roleId?.toString() || '', isActive: organization.isActive, }); } else { reset({ organizationCode: '', organizationName: '', roleId: '', isActive: true, }); } }, [organization, reset, open]); const onSubmit = (data: OrganizationFormData) => { const submitData = { ...data, roleId: data.roleId ? Number(data.roleId) : undefined, }; if (organization) { updateOrg.mutate({ uuid: organization.publicId, data: submitData }, { onSuccess: () => onOpenChange(false) }); } else { createOrg.mutate(submitData, { onSuccess: () => onOpenChange(false), }); } }; return ( {organization ? 'Edit Organization' : 'New Organization'}
{errors.organizationCode &&

{errors.organizationCode.message}

}
{errors.organizationName &&

{errors.organizationName.message}

}

Enable or disable this organization

} />
); }