"use client"; import type { ReactNode } from "react"; import { useFormContext, useWatch } from "react-hook-form"; import { CERTIFICATION_AGENCIES, certificationAgencyLabel, } from "@/lib/api/certifications"; import type { ContactRole } from "@/lib/api/contacts"; import { FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { NativeSelect } from "@/components/ui/native-select"; import { Input } from "@/components/ui/input"; import { DatePicker, rangeEndAfter } from "@/components/ui/date-picker"; import { ContactCombobox } from "@/components/contacts/contact-combobox"; import { PersonCombobox } from "@/components/people/person-combobox"; // What a contact created from a course or a card starts as: whoever ran the // training. const SCHOOL: readonly ContactRole[] = ["school"]; interface TrainingDateField { name: string; label: string; } interface TrainingFieldsProps { // A card always names its agency; a course run by a private instructor need // not, so its form offers "No agency" and stores `null`. agencyRequired: boolean; // The field sharing the agency's row. besideAgency: ReactNode; // Start, then end: the pickers treat the pair as a range. dates: readonly [TrainingDateField, TrainingDateField]; // The date the pickers rank by last use at or before. until?: string; // Replaces the instructor field's own `onChange`, for a form that does more // when the instructor changes. onInstructorChange?: (uuid: string | null) => void; } // The block a course and a certification share: who ran the training, when, and // who taught it. Both forms hold these under the same names - `agency`, // `agency_other`, `contact_uuid`, `instructor_uuid`, `instructor_number` - and // name their own pair of dates. export function TrainingFields({ agencyRequired, besideAgency, dates, until, onInstructorChange, }: TrainingFieldsProps) { const { control, setValue } = useFormContext(); // `agency_other` is only shown - and only accepted by the API - for "other". const agency = useWatch({ control, name: "agency" }); const [startField, endField] = dates; const [start = "", end = ""] = useWatch({ control, name: [startField.name, endField.name], }) as [string | undefined, string | undefined]; const onStartChange = (value: string) => { const kept = rangeEndAfter(value, end); if (kept !== end) { setValue(endField.name, kept, { shouldDirty: true, shouldValidate: true, }); } }; return ( <>