/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';

import { Control, useController } from 'react-hook-form';

import { Input } from '@/components/ui/input';

import { FieldWrapper } from './FieldWrapper';

interface RadioFieldProps {
  control: Control<any>;
  name: string;
  label?: string;
  required?: boolean;
  options: { id: number | string; name: string }[];
  helper?: string;
  customOptionId?: number | string;
  customFieldName?: string;
  customFieldPlaceholder?: string;
}

export function RadioField(props: RadioFieldProps) {
  const {
    field,
    fieldState: { error },
  } = useController({ control: props.control, name: props.name });

  const customFieldController = useController({
    control: props.control,
    name: props.customFieldName || 'dummy',
  });

  const customField = props.customFieldName ? customFieldController : null;

  const showCustomInput = props.customOptionId && field.value === props.customOptionId;

  return (
    <FieldWrapper
      label={props.label}
      required={props.required}
      helper={props.helper}
      error={error?.message}
    >
      <div className="space-y-3">
        {props.options.map((option) => (
          <div key={option.id} className="flex flex-col gap-2">
            <div className="flex items-center gap-2">
              <input
                type="radio"
                id={`${props.name}-${option.id}`}
                checked={field.value === option.id}
                onChange={() => field.onChange(option.id)}
                className="h-4 w-4 border-mma-blue/50 accent-mma-blue"
              />
              <label
                htmlFor={`${props.name}-${option.id}`}
                className="text-sm font-semibold text-mma-blue cursor-pointer"
              >
                {option.name}
              </label>
            </div>
            {props.customOptionId === option.id && showCustomInput && customField && (
              <Input
                {...customField.field}
                placeholder={props.customFieldPlaceholder}
                className=""
              />
            )}
          </div>
        ))}
      </div>
    </FieldWrapper>
  );
}
