import { useEffect, useRef } from 'react';

import { Box, Button, Flex, Text } from '@chakra-ui/react';
import { MdAdd } from 'react-icons/md';

import { isNullOrUndefined, isNumber } from '@/utils/validator';

export type SelectListModel = {
  id: any;
  name: any;
  isSelected?: boolean;
};

const optionToOptionDisplay = (
  data: SelectListModel[] | undefined,
  selectedOptions: SelectListModel[],
  search?: string
): SelectListModel[] => {
  if (isNullOrUndefined(data)) {
    return [];
  }
  const out: SelectListModel[] = [];
  data.forEach((element) => {
    if (search) {
      if (isNumber(element.name)) {
        if (!element.name.toString().includes(search.toLowerCase())) {
          return;
        }
      } else if (!element.name.toLowerCase().includes(search.toLowerCase())) {
        return;
      }
    }
    out.push({
      ...element,
      isSelected:
        selectedOptions.find((elem) => elem.id === element.id) !== undefined,
    });
  });
  return out;
};

export type SelectListProps = {
  options?: SelectListModel[];
  selected: SelectListModel[];
  onSelectValue: (data: SelectListModel) => void;
  search?: string;
  // if set add capability to add the search item
  onCreate?: (data: string) => void;
};
export const SelectList = ({
  options,
  selected,
  onSelectValue,
  search,
  onCreate,
}: SelectListProps) => {
  const displayedValue = optionToOptionDisplay(options, selected, search);
  const scrollToRef = useRef<HTMLButtonElement | null>(null);
  useEffect(() => {
    if (scrollToRef?.current) {
      scrollToRef?.current?.scrollIntoView({
        behavior: 'smooth',
        block: 'center',
      });
    }
  }, []);
  return (
    <Box position="relative">
      <Flex
        direction="column"
        width="full"
        position="absolute"
        border="1px"
        borderColor="black"
        backgroundColor="gray.700"
        overflowY="auto"
        overflowX="hidden"
        maxHeight="300px"
        zIndex={300}
        transform="translateY(1px)"
      >
        {displayedValue.length === 0 && (
          <Text marginX="auto" color="red.500" fontWeight="bold" marginY="10px">
            ... No element found...
          </Text>
        )}
        {displayedValue.map((data) => (
          <Button
            key={data.id}
            marginY="1px"
            borderRadius="0px"
            autoFocus={false}
            backgroundColor={data.isSelected ? 'green.800' : '0x00000000'}
            _hover={{ backgroundColor: 'gray.400' }}
            onClick={() => onSelectValue(data)}
            ref={data.isSelected ? scrollToRef : undefined}
          >
            <Text marginRight="auto" autoFocus={false}>
              {data.name}
            </Text>
          </Button>
        ))}
        {onCreate && search && search.length > 0 && (
          <Button
            marginY="1px"
            borderRadius="0px"
            autoFocus={false}
            _hover={{ backgroundColor: 'gray.400' }}
            onClick={() => onCreate(search)}
          >
            <Flex marginRight="auto">
              <MdAdd />
              <Text autoFocus={false}>Create '{search}'</Text>
            </Flex>
          </Button>
        )}
      </Flex>
    </Box>
  );
};
