/** @jsxRuntime classic */
/** @jsx jsx */
import { useState, useEffect, useRef, Fragment } from 'react';
import { useColors } from '../../hooks/useColors';
import { IOption } from '../../types';
import { containerCss, labelTagCss, marginBottom, marginTop } from './style';
import { jsx } from '@emotion/react';
import { useTypography } from '../../hooks/useTypography';
import { BnIcon, Popup, SelectOptions, Typography } from '../../components';
import { ETypography, ETypographyColor, Icons } from '../../types/theme';

export interface ITagsProps {
  options: IOption[];
  label?: string;
  bottomInfo?: string;
  selected: string[];
  handleChange: (value: string) => void;
}

export const TagsInput = ({
  options,
  selected,
  handleChange,
  label = '',
  bottomInfo = '',
}: ITagsProps) => {
  const [searchPhrase, setSearchPhrase] = useState<string>('');
  const [isOpen, setOpen] = useState<boolean>(false);
  const { colors } = useColors();
  const { typography } = useTypography();
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (searchPhrase) {
      setOpen(true);
    } else {
      setOpen(false);
    }
  }, [searchPhrase]);

  const handleAddition = (v: string) => {
    setSearchPhrase('');
    setOpen(false);
    handleChange(v);
    inputRef?.current?.focus();
  };

  return (
    <Fragment>
      {label && (
        <div css={marginBottom}>
          <Typography
            color={ETypographyColor.secondary}
            type={ETypography.captionAccented}
          >
            {label}
          </Typography>
        </div>
      )}
      <Popup
        fullWidth
        body={
          <SelectOptions
            options={options.filter((opt) => opt.label.includes(searchPhrase))}
            value={selected}
            isMultiple
            onSelect={handleAddition}
            autoFocus={false}
          />
        }
        disableAutoTrigger
        trigger={isOpen}
      >
        <div css={containerCss(colors, typography)}>
          {selected.map((tag, index) => {
            const state = options.find((opt) => String(opt.value) === tag);
            if (state) {
              return (
                <LabelTag
                  key={index}
                  state={state}
                  handleRemove={handleChange}
                />
              );
            }
            return <Fragment />;
          })}
          <input
            ref={inputRef}
            value={searchPhrase}
            onChange={(e) => setSearchPhrase(e.target.value)}
          />
        </div>
      </Popup>
      {bottomInfo && (
        <div css={marginTop}>
          <Typography
            color={ETypographyColor.secondary}
            type={ETypography.caption}
          >
            {bottomInfo}
          </Typography>
        </div>
      )}
    </Fragment>
  );
};

const LabelTag = ({
  state,
  handleRemove,
}: {
  state: IOption;
  handleRemove: (value: string) => void;
}) => {
  const { colors } = useColors();
  const { typography } = useTypography();
  return (
    <div css={labelTagCss(colors, typography)}>
      {state.label}
      <button type="button" onClick={() => handleRemove(String(state.value))}>
        <BnIcon icon={Icons.close} />
      </button>
    </div>
  );
};
