"use client"

import { useFormContext, useController, type FieldValues, type FieldPath } from "react-hook-form"
import { FieldShell } from "@/shared/components/form/field-shell"
import { EmployeeCombobox } from "./employee-combobox"

// ── Props ──

export type RhfEmployeeSelectFieldProps<
    TValues extends FieldValues,
    TName extends FieldPath<TValues>,
> = {
    name: TName
    label?: string
    description?: string
    required?: boolean
    disabled?: boolean
    placeholder?: string
}

// ── Component ──

export function RhfEmployeeSelectField<
    TValues extends FieldValues,
    TName extends FieldPath<TValues>,
>({
    name,
    label = "Employee",
    description,
    required,
    disabled,
    placeholder = "Search by name or email...",
}: RhfEmployeeSelectFieldProps<TValues, TName>) {
    const { control } = useFormContext<TValues>()
    const {
        field,
        fieldState: { error },
    } = useController({ name, control, disabled })

    return (
        <FieldShell
            label={label}
            error={error?.message}
            description={description}
            required={required}
        >
            <EmployeeCombobox
                value={field.value}
                onValueChange={(emp) => {
                    field.onChange(emp ? { value: emp.value, label: emp.label } : null)
                }}
                disabled={field.disabled}
                placeholder={placeholder}
                showClear={!!field.value}
                onBlur={field.onBlur}
                aria-invalid={!!error || undefined}
            />
        </FieldShell>
    )
}
