import React, { useState } from 'react';
import { Div, Label } from '@cloudflare/elements';
import { createStyledComponent } from '@cloudflare/style-container';
import Radio from './Radio';
import Error from './Error';
import { useRenderOnResize } from '@cloudflare/util-hooks';

type FormRadiosProps<ValueType> = {
  name: string;
  label?: React.ReactNode;
  labelProps?: React.ComponentType<typeof Div>;
  options: {
    label: React.ReactNode;
    value: ValueType;
    disabled?: boolean;
  }[];
  value?: ValueType;
  onChange: (value: ValueType) => void;
  className?: string;
  error?: React.ReactNode;
  errorProps?: React.ComponentProps<typeof Div>;
  disabled?: boolean;
};

let count = 0;

function Radios<ValueType>({
  name,
  label,
  labelProps,
  options,
  value,
  onChange,
  className,
  error,
  errorProps,
  disabled
}: FormRadiosProps<ValueType>) {
  useRenderOnResize();

  const [ids] = useState(() => ({
    label: `cf-form-radios-label${++count}`,
    error: `cf-form-radios-error${++count}`
  }));

  return (
    <div className={className}>
      {label && (
        <Label id={ids.label} {...labelProps} mb={2}>
          {label}
        </Label>
      )}
      {options.map((option, index) => (
        <Radio<ValueType>
          name={name}
          label={option.label}
          value={option.value}
          checked={option.value === value}
          onChange={() => onChange(option.value)}
          disabled={disabled || option.disabled}
          labelFirst={false}
          noLabel
          invalid={!!error}
          labelProps={{ marginLeft: 3, display: 'inline-block' }}
          erroredBy={error ? ids.error : undefined}
          describedBy={label ? ids.label : undefined}
          componentStyleProps={{ display: 'inline-block' }}
          marginBottom={error && index === options.length - 1 ? 2 : 3}
        />
      ))}
      {error && (
        <Error mb={2} mt={-2} {...(errorProps || {})} id={ids.error}>
          {error}
        </Error>
      )}
    </div>
  );
}

const StyledFormRadios = createStyledComponent(() => ({}), Radios);

export type RadiosProps<ValueType> = FormRadiosProps<ValueType> &
  Omit<React.ComponentProps<typeof Div>, 'onChange'>;

export default function FormRadios<ValueType>(props: RadiosProps<ValueType>) {
  // @ts-ignore
  return <StyledFormRadios {...props} />;
}
