'use client';

import { useStore } from '@tanstack/react-form';
import { FieldDescription, FieldLabel } from '@/components/ui/field';
import {
  FormField,
  FormFieldError,
  FormFieldSet,
  createFormField,
  useFieldContext
} from '@/components/ui/form-context';
import { CrmDateInput } from '@/features/crm/components/crm-form-controls';

interface DatePickerFieldProps {
  label: string;
  description?: string;
  required?: boolean;
  placeholder?: string;
  disabled?: (date: Date) => boolean;
}

export function DatePickerField({
  label,
  description,
  required,
  placeholder = 'DD/MM/YYYY',
  disabled
}: DatePickerFieldProps) {
  void disabled;
  const field = useFieldContext();
  const value = useStore(field.store, (s) => s.value) as string | null | undefined;

  return (
    <FormFieldSet>
      <FormField>
        <FieldLabel htmlFor={field.name}>
          {label}
          {required && ' *'}
        </FieldLabel>
        <CrmDateInput
          value={value}
          placeholder={placeholder}
          onChange={(nextValue) => {
            field.handleChange(nextValue);
            field.handleBlur();
          }}
        />
        {description && <FieldDescription>{description}</FieldDescription>}
      </FormField>
      <FormFieldError />
    </FormFieldSet>
  );
}

export const FormDatePickerField = createFormField(DatePickerField);
