'use client';

import { useTranslations } from 'next-intl';
import type { InterestErrors, InterestField, InterestValues } from '@/lib/validation';
import { ConsentField } from './ConsentField';
import { FormField, inputClass } from './FormField';

type TextFieldConfig = {
  field: 'fullName' | 'phone' | 'email';
  labelKey: 'name' | 'phone' | 'email';
  hintKey?: 'phoneHint';
  optionalKey?: 'optional';
  name: string;
  type: 'text' | 'tel' | 'email';
  autoComplete: string;
  inputMode?: 'tel' | 'email';
  ltr?: boolean;
  required?: boolean;
};

const TEXT_FIELDS: readonly TextFieldConfig[] = [
  { field: 'fullName', labelKey: 'name', name: 'name', type: 'text', autoComplete: 'name', required: true },
  {
    field: 'phone', labelKey: 'phone', hintKey: 'phoneHint', name: 'tel', type: 'tel',
    autoComplete: 'tel', inputMode: 'tel', ltr: true, required: true,
  },
  {
    field: 'email', labelKey: 'email', optionalKey: 'optional', name: 'email', type: 'email',
    autoComplete: 'email', inputMode: 'email', ltr: true,
  },
];

type InterestFieldsProps = {
  values: InterestValues;
  errors: InterestErrors;
  disabled: boolean;
  project: string;
  onChange: (field: InterestField, value: string | boolean) => void;
  onBlur: (field: InterestField) => void;
};

export function InterestFields({ values, errors, disabled, project, onChange, onBlur }: InterestFieldsProps) {
  const t = useTranslations('form');

  return (
    <>
      {TEXT_FIELDS.map((cfg) => {
        const error = errors[cfg.field];
        return (
          <FormField
            key={cfg.field}
            label={t(cfg.labelKey)}
            hint={cfg.hintKey && t(cfg.hintKey)}
            optionalLabel={cfg.optionalKey && t(cfg.optionalKey)}
            error={error && t(`errors.${error}`)}
          >
            {(control) => (
              <input
                {...control}
                type={cfg.type}
                name={cfg.name}
                autoComplete={cfg.autoComplete}
                inputMode={cfg.inputMode}
                dir={cfg.ltr ? 'ltr' : undefined}
                required={cfg.required}
                value={values[cfg.field]}
                onChange={(e) => onChange(cfg.field, e.target.value)}
                onBlur={() => onBlur(cfg.field)}
                disabled={disabled}
                className={`${inputClass(Boolean(error))} ${cfg.ltr ? 'text-start' : ''}`}
              />
            )}
          </FormField>
        );
      })}

      <ConsentField
        checked={values.consent}
        error={errors.consent}
        disabled={disabled}
        project={project}
        onChange={(checked) => onChange('consent', checked)}
      />
    </>
  );
}
