'use client';

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

interface CurrencyFieldProps {
  label: string;
  description?: string;
  required?: boolean;
  currencyLabel?: string;
  placeholder?: string;
}

export function CurrencyField({
  label,
  description,
  required,
  currencyLabel,
  placeholder
}: CurrencyFieldProps) {
  const field = useFieldContext();
  const isTouched = useStore(field.store, (s) => s.meta.isTouched);
  const isValid = useStore(field.store, (s) => s.meta.isValid);
  const value = useStore(field.store, (s) => s.value) as string | number | undefined;

  return (
    <FormFieldSet>
      <FormField>
        <FieldLabel htmlFor={field.name}>
          {label}
          {required && ' *'}
        </FieldLabel>
        <CrmCurrencyInput
          value={value === undefined || value === null ? '' : String(value)}
          onChange={(nextValue) => field.handleChange(nextValue === '' ? '' : Number(nextValue))}
          currencyLabel={currencyLabel}
          placeholder={placeholder}
          className={isTouched && !isValid ? 'border-destructive' : undefined}
        />
        {description && <FieldDescription>{description}</FieldDescription>}
      </FormField>
      <FormFieldError />
    </FormFieldSet>
  );
}

export const FormCurrencyField = createFormField(CurrencyField);
