import React, { useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { SelectWrap } from './SelectWrap';
import Input from '@/components/Input';
import { uuid } from '@/utils/uuid';
import { useClickOutside } from '@/utils/useClickOutSide';
import iconDown from '@/assets/icon/down.svg';

interface OptionProps {
  name: string;
  value: string;
}

export interface SelectProps {
  label?: string;
  defaultOptionIdx?: number;
  options: OptionProps[];
  onChange: (data: OptionProps) => void;
  usei18: boolean;
  width?: string | number;
}

const Select: React.FC<SelectProps> = ({
  defaultOptionIdx,
  options,
  onChange,
  usei18 = false,
  label,
  width = '100%',
}) => {
  const { t } = useTranslation();
  const [selectorVisible, setSelectorVisible] = useState(false);
  const [selectIdx, setSelectIdx] = useState(defaultOptionIdx || 0);
  const ref = useRef(null);
  useClickOutside(ref, () => {
    setSelectorVisible(false);
  });
  return (
    <SelectWrap
      haveLabel={label !== undefined}
      width={width}
      selectorVisible={selectorVisible}
    >
      <div
        className="selectContainer"
        onClick={(e: any) => {
          e.stopPropagation();
          setSelectorVisible(!selectorVisible);
        }}
        ref={ref}
      >
        <img src={iconDown} className="icon" />
        {label && <div className="inputLabel">{t(label)}</div>}
        <Input
          value={
            usei18 ? `${t(options[selectIdx].name)}` : options[selectIdx].name
          }
          readOnly
          center={true}
        />
        {selectorVisible && (
          <div className="selector">
            {options.map((option, idx) => (
              <div
                className="optionContainer"
                key={`option${uuid()}`}
                onClick={() => {
                  setSelectIdx(idx);
                  onChange(options[idx]);
                  setSelectorVisible(false);
                }}
              >
                {usei18 ? t(option.name) : option.name}
              </div>
            ))}
          </div>
        )}
      </div>
    </SelectWrap>
  );
};
export default Select;
