import React, { forwardRef, useState } from 'react';
import {
  Input,
  Image,
  InputProps,
  Box,
  Popover,
  PopoverAnchor,
  PopoverContent,
  PopoverBody,
  List,
  ListItem,
} from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';

import { carBodySelectOptions } from './helper';
import { CarBodySelectOption } from './types';

export const CarBodySelect = forwardRef<HTMLInputElement, InputProps>(
  function CarBodySelect(props, ref) {
    const initialOption = carBodySelectOptions.find(({ value }) => value === Number(props.value));
    const [selected, setSelected] = useState<Partial<CarBodySelectOption>>(initialOption);

    const handleOptionClick = (option: CarBodySelectOption) => {
      setSelected(option);
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      props.onChange(option.value);
    };

    const [isDropdownOpen, setIsDropdownOpen] = useState<boolean>(false);

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

    return (
      <Box width='100%'>
        <Popover
          isOpen={isDropdownOpen}
          autoFocus={false}
          placement='bottom-start'
          matchWidth
        >
          <PopoverAnchor>
            <Input
              {...props}
              ref={ref}
              value={
                selected?.labelTKey
                  ? t(`options.${selected.labelTKey}`)
                  : undefined
              }
              readOnly
              onClick={() => setIsDropdownOpen(true)}
              onBlur={() => setIsDropdownOpen(false)}
              placeholder={t('placeholder')}
            />
          </PopoverAnchor>
          <PopoverContent width='100%' maxWidth='100%'>
            <PopoverBody border='1px' borderColor='gray.300' p={0}>
              <List
                display='grid'
                gridTemplateColumns='repeat(auto-fit, minmax(150px, 1fr))'
              >
                {carBodySelectOptions.map((option) => (
                  <ListItem
                    key={option.value}
                    display='flex'
                    flexDirection='column'
                    justifyContent='flex-end'
                    alignItems='center'
                    p={2}
                    cursor='pointer'
                    _hover={{
                      bgColor: 'primary.50',
                    }}
                    _active={{
                      bgColor: 'primary.100',
                    }}
                    onClick={() => handleOptionClick(option)}
                  >
                    <Image src={option.img} />
                    {t(`options.${option.labelTKey}`)}
                  </ListItem>
                ))}
              </List>
            </PopoverBody>
          </PopoverContent>
        </Popover>
      </Box>
    );
  },
);
