import { RefObject, useEffect, useMemo, useRef, useState } from 'react';

import {
  Button,
  Flex,
  Input,
  Spinner,
  Tag,
  TagCloseButton,
  TagLabel,
  Wrap,
  WrapItem,
} from '@chakra-ui/react';
import { MdEdit, MdKeyboardArrowDown, MdKeyboardArrowUp } from 'react-icons/md';

import { SelectList, SelectListModel } from '@/components/select/SelectList';
import { isNullOrUndefined } from '@/utils/validator';

export type SelectMultipleProps = {
  options?: object[];
  values?: (number | string)[];
  onChange?: (value: (number | string)[] | undefined) => void;
  keyKey?: string;
  keyValue?: string;
  ref?: RefObject<any>;
  // if set add capability to add the search item
  onCreate?: (data: string) => void;
  // if a suggestion exist at the auto compleat
  suggestion?: string;
};

export const SelectMultiple = ({
  options,
  onChange,
  values,
  ref,
  keyKey = 'id',
  keyValue = keyKey,
  suggestion,
  onCreate,
}: SelectMultipleProps) => {
  const [showList, setShowList] = useState(false);
  const transformedOption = useMemo(() => {
    return options?.map((element) => {
      return {
        id: element[keyKey],
        name: element[keyValue],
      } as SelectListModel;
    });
  }, [options, keyKey, keyValue]);
  const [hasSuggestion, setHasSuggestion] = useState<boolean>(
    onCreate && suggestion ? true : false
  );
  const [currentSearch, setCurrentSearch] = useState<string | undefined>(
    onCreate ? suggestion : undefined
  );
  useEffect(() => {
    if (suggestion) {
      setCurrentSearch(suggestion);
      setHasSuggestion(true);
    }
  }, [suggestion]);

  const refFocus = ref ?? useRef<HTMLInputElement | null>(null);
  const selectedOptions = useMemo(() => {
    if (isNullOrUndefined(values) || !transformedOption) {
      return [];
    }
    return transformedOption.filter((element) => {
      return values.includes(element[keyKey]);
    });
  }, [values, transformedOption]);

  const selectValue = (data: SelectListModel) => {
    const newValues = values?.includes(data.id)
      ? values.filter((elem) => data.id !== elem)
      : [...(values ?? []), data.id];
    setShowList(false);
    if (onChange) {
      if (newValues.length == 0) {
        onChange(undefined);
      } else {
        onChange(newValues);
      }
    }
  };
  if (!options) {
    return <Spinner />;
  }
  const onChangeInput = (value: string): void => {
    setHasSuggestion(false);
    if (value === '') {
      setCurrentSearch(undefined);
    } else {
      setCurrentSearch(value);
    }
  };
  const onOpenClose = () => {
    if (!showList) {
      refFocus?.current?.focus();
      return;
    }
  };
  const createNewItem = !onCreate
    ? undefined
    : (data: string) => {
      onCreate(data);
      setCurrentSearch(undefined);
    };

  return (
    <Flex direction="column" width="full" gap="0px">
      {selectedOptions && (
        <Wrap spacing="5px" justify="left" width="full" marginBottom="2px">
          {selectedOptions.map((data) => (
            <WrapItem key={data[keyKey]}>
              <Tag
                size="md"
                key="md"
                borderRadius="5px"
                variant="solid"
                backgroundColor="green.500"
              >
                <TagLabel>{data[keyValue] ?? `id=${data[keyKey]}`}</TagLabel>
                <TagCloseButton onClick={() => selectValue(data)} />
              </Tag>
            </WrapItem>
          ))}
        </Wrap>
      )}

      <Flex>
        <Input
          ref={refFocus}
          width="full"
          onChange={(e) => onChangeInput(e.target.value)}
          //onSubmit={onSubmit}
          onFocus={() => setShowList(true)}
          onBlur={() => setTimeout(() => setShowList(false), 200)}
          value={showList ? (currentSearch ?? '') : hasSuggestion ? `suggest: ${currentSearch}` : ''}
          borderRadius="5px 0 0 5px"
        />
        <Button
          onClick={onOpenClose}
          variant="outline"
          borderRadius="0 5px 5px 0"
          borderWidth="1px 1px 1px 0"
        >
          {showList ? (
            <MdKeyboardArrowUp color="gray.300" />
          ) : hasSuggestion ? (
            <MdEdit color="gray.300" />
          ) : (
            <MdKeyboardArrowDown color="gray.300" />
          )}
        </Button>
      </Flex>
      {showList && (
        <SelectList
          options={transformedOption}
          selected={selectedOptions}
          search={currentSearch}
          onSelectValue={selectValue}
          onCreate={createNewItem}
        />
      )}
    </Flex>
  );
};
