'use client';
import { Box, Chip, FormHelperText, FormLabel, Stack, Typography } from '@mui/material';
import { Controller, FieldValues, RegisterOptions, useFormContext } from 'react-hook-form';
import type { RhfFieldProps } from './types';

export interface ChipOption {
  /** Stable code stored in form state — never the label. */
  code: string;
  /** Already-translated display label. */
  label: string;
}

export type RhfChipSelectProps<TFieldValues extends FieldValues> = RhfFieldProps<TFieldValues> & {
  /** Already-translated group label. */
  label?: string;
  /** Already-translated one-line hint under the label. */
  hint?: string;
  options: ReadonlyArray<ChipOption>;
  /** Single-select behaves like a radio group: re-tapping the selected chip clears it. */
  multiple?: boolean;
  disabled?: boolean;
  /**
   * Renders codes that aren't in `options` as removable chips (a free-text specialty the nurse added).
   * Without it a stored custom value would silently vanish from the UI while staying in form state.
   */
  allowCustomValues?: boolean;
};

/**
 * A chip group bound to a react-hook-form field — `string[]` when `multiple`, `string | null`
 * otherwise.
 *
 * The same "tap to toggle a code" chip row was hand-rolled with bespoke `sx` in the nurse profile,
 * the credentials form and the variant builder, each with its own selected-state colors and its own
 * `useState` array. One binding replaces all three, and selection participates in validation like any
 * other field (a required group can simply carry a `rules.validate`).
 * @component RhfChipSelect
 */
const RhfChipSelect = <TFieldValues extends FieldValues>({
  name,
  control,
  rules,
  label,
  hint,
  options,
  multiple = true,
  disabled = false,
  allowCustomValues = false,
}: RhfChipSelectProps<TFieldValues>) => {
  const context = useFormContext<TFieldValues>();
  const resolvedControl = control ?? context?.control;

  return (
    <Controller
      name={name}
      control={resolvedControl}
      rules={rules as RegisterOptions<TFieldValues>}
      render={({ field, fieldState }) => {
        const selected: string[] = multiple
          ? ((field.value as string[] | undefined) ?? [])
          : field.value == null
            ? []
            : [field.value as string];

        const toggle = (code: string) => {
          if (!multiple) {
            field.onChange(selected.includes(code) ? null : code);
            return;
          }
          field.onChange(selected.includes(code) ? selected.filter((item) => item !== code) : [...selected, code]);
        };

        const knownCodes = options.map((option) => option.code);
        const customCodes = allowCustomValues ? selected.filter((code) => !knownCodes.includes(code)) : [];

        return (
          <Stack sx={{ gap: 1 }}>
            {label ? <FormLabel error={Boolean(fieldState.error)}>{label}</FormLabel> : null}
            {hint ? (
              <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                {hint}
              </Typography>
            ) : null}

            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
              {options.map((option) => {
                const isSelected = selected.includes(option.code);
                return (
                  <Chip
                    key={option.code}
                    label={option.label}
                    data-code={option.code}
                    aria-pressed={isSelected}
                    clickable
                    disabled={disabled}
                    color={isSelected ? 'primary' : 'default'}
                    variant={isSelected ? 'filled' : 'outlined'}
                    onClick={() => toggle(option.code)}
                  />
                );
              })}
              {customCodes.map((code) => (
                <Chip
                  key={code}
                  label={code}
                  data-code={code}
                  disabled={disabled}
                  color="primary"
                  variant="filled"
                  onDelete={() => toggle(code)}
                />
              ))}
            </Box>

            {fieldState.error?.message ? <FormHelperText error>{fieldState.error.message}</FormHelperText> : null}
          </Stack>
        );
      }}
    />
  );
};

export default RhfChipSelect;
