import React, { type FC, useState } from 'react';
import {
  Controller,
  type UseControllerProps,
  useFormContext,
} from 'react-hook-form';

import Rating, { type RatingProps } from '@material-hu/mui/Rating';

import { IconContainer } from './HugoNumberRating';

type Props = RatingProps &
  UseControllerProps & {
    name: string;
    max?: number;
  };

const HugoFormNumberRating: FC<Props> = ({
  name,
  rules,
  defaultValue,
  max = 5,
  ...rest
}) => {
  const [hoveredValue, setHoveredValue] = useState(-1);
  const { control } = useFormContext();
  return (
    <Controller
      name={name}
      control={control}
      rules={rules}
      defaultValue={defaultValue}
      render={({ field }) => (
        <Rating
          {...field}
          value={Number(field.value)}
          name={name}
          max={max}
          IconContainerComponent={iconProps => (
            <IconContainer
              {...iconProps}
              max={max}
              hoveredValue={hoveredValue}
              selectedValue={field.value}
            />
          )}
          onChangeActive={(_, newHover) => {
            setHoveredValue(newHover);
          }}
          getLabelText={value => `${value}`}
          highlightSelectedOnly
          sx={{
            width: '100%',
            '& .MuiRating-iconFocus': {
              transform: 'none !important',
              scale: '1 !important',
            },
            '.MuiRating-pristine': {
              display: 'none',
            },
            '& > label': {
              flex: 1,
            },
          }}
          {...rest}
        />
      )}
    />
  );
};

export default HugoFormNumberRating;
