"use client" import { useRef, useState } from "react" import { useMutation } from "@tanstack/react-query" import { toast } from "sonner" import { useForm } from "react-hook-form" import { zodResolver } from "@hookform/resolvers/zod" import { z } from "zod" import { UploadIcon } from "lucide-react" import { Button } from "@/shared/components/ui/button" import { Input } from "@/shared/components/ui/input" import { Textarea } from "@/shared/components/ui/textarea" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/shared/components/ui/select" import { Field, FieldLabel, FieldError } from "@/shared/components/ui/field" import { useAuthApi } from "@/shared/useApi" const DOCUMENT_TYPES = [ { value: "contract", label: "Contract" }, { value: "id", label: "ID / Passport" }, { value: "ase", label: "ASE" }, { value: "certification", label: "Certification" }, { value: "other", label: "Other" }, ] as const const schema = z.object({ name: z.string().trim().min(1, "Name is required").max(150), type: z.enum(["contract", "id", "ase", "certification", "other"]), issued_date: z.string().optional(), expiry_date: z.string().optional(), notes: z.string().max(2000).optional(), }) type FormValues = z.infer export type EmployeeDocumentFormProps = { employeeId: string onSuccess?: () => void onCancel?: () => void } export function EmployeeDocumentForm({ employeeId, onSuccess, onCancel }: EmployeeDocumentFormProps) { const api = useAuthApi() const fileRef = useRef(null) const [file, setFile] = useState(null) const { register, handleSubmit, setValue, watch, formState: { errors }, reset, } = useForm({ resolver: zodResolver(schema), defaultValues: { name: "", type: "other", issued_date: "", expiry_date: "", notes: "" }, }) const type = watch("type") const mutation = useMutation({ mutationFn: (values: FormValues) => { if (!file) throw new Error("Select a file to upload.") const promise = api.employees.uploadDocument(employeeId, { file, name: values.name, type: values.type, issued_date: values.issued_date || undefined, expiry_date: values.expiry_date || undefined, notes: values.notes || undefined, }) toast.promise(promise, { loading: "Uploading document...", success: "Document uploaded", error: (err: any) => err?.message ?? "Failed to upload", }) return promise }, onSuccess: () => { reset() setFile(null) onSuccess?.() }, }) return (
mutation.mutate(v))}> File
{file ? file.name : "No file selected"} setFile(e.target.files?.[0] ?? null)} />
{!file && mutation.isError && ( Select a file before uploading. )}
Name {errors.name && {errors.name.message}} Type
Issued Date Expiry Date
Notes