import React, { forwardRef } from 'react';
import {
  Input,
  Box,
  Popover,
  PopoverAnchor,
  PopoverContent,
  PopoverBody,
  useRadioGroup,
  Grid,
  GridItem,
  UseRadioGroupProps,
  useDisclosure,
} from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';

import { carBodySelectOptions, getInputValue } from './helper';
import { CarBodyOption } from './option';
import { CarBodySelectProps } from './types';

export const CarBodySelect = forwardRef<HTMLInputElement, CarBodySelectProps>(
  function CarBodySelect(props, ref) {
    const handleOptionClick: UseRadioGroupProps['onChange'] = (value) => {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      props.onChange(value);
    };

    const { value, getRadioProps, getRootProps } = useRadioGroup({
      defaultValue: props.value,
      value: props.value,
      onChange: handleOptionClick,
    });

    const { isOpen, onOpen, onClose } = useDisclosure();

    const { t } = useTranslation('~', {
      keyPrefix: 'dry-wash.order-create.car-body-select',
    });

    return (
      <Box width='100%'>
        <Popover
          isOpen={isOpen}
          autoFocus={false}
          placement='bottom-start'
          matchWidth
        >
          <PopoverAnchor>
            <Input
              {...props}
              ref={ref}
              value={getInputValue(Number(value), t) ?? props.value}
              readOnly
              onClick={onOpen}
              onBlur={onClose}
              placeholder={t('placeholder')}
            />
          </PopoverAnchor>
          <PopoverContent width='100%' maxWidth='100%'>
            <PopoverBody border='1px' borderColor='gray.300' p={0}>
              <Grid
                templateColumns='repeat(auto-fit, minmax(150px, 1fr))'
                {...getRootProps()}
              >
                {carBodySelectOptions.map(({ value, img, labelTKey }) => (
                  <GridItem key={value}>
                    <CarBodyOption
                      image={img}
                      label={t(`options.${labelTKey}`)}
                      {...getRadioProps({ value: String(value) })}
                    />
                  </GridItem>
                ))}
              </Grid>
            </PopoverBody>
          </PopoverContent>
        </Popover>
      </Box>
    );
  },
);
