import { useEffect, useState, useRef } from 'react';
import { EDIT_ACCESS_RUSSIAN, ROLES_ID_RUSSIAN_NAME } from '../../../constants/constants';
import {
  SelectWrapper,
  SelectContainer,
  SelectButton,
  Dropdown,
  Option,
  OptionName,
  Chevron,
  SelectedValue,
  Placeholder,
} from './StyledComponents';

export const SelectRoles = ({
  onChange,
  initialValue,
  excludeAdmin = true,
}) => {
  const [options, setOptions] = useState([]);

  useEffect(() => {
    const options = Object.entries(ROLES_ID_RUSSIAN_NAME)
      .map(([id, name]) => ({
        id: parseInt(id),
        name,
      }))
      .filter((option) => !excludeAdmin || option.id !== 1);
    setOptions(options);
  }, []);

  return (
    <Select options={options} onChange={onChange} initialValue={initialValue} />
  );
};

export const SelectAccessLevels = ({ onChange, initialValue }) => {
  const [options, setOptions] = useState([]);

  useEffect(() => {
    const options = Object.entries(EDIT_ACCESS_RUSSIAN).map(([id, value]) => ({
      id: parseInt(id),
      name: EDIT_ACCESS_RUSSIAN[id] || value,
    }));

    setOptions(options);
  }, []);

  return (
    <Select options={options} onChange={onChange} initialValue={initialValue} />
  );
};

const Select = ({
  options,
  onChange,
  initialValue,
  valueKey = 'id',
  labelKey = 'name',
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedOption, setSelectedOption] = useState(null);
  const selectRef = useRef(null);

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        isOpen &&
        selectRef.current &&
        !selectRef.current.contains(event.target)
      ) {
        setIsOpen(false);
      }
    };

    const handleEscapeKey = (event) => {
      if (
        isOpen &&
        event.key === 'Escape' &&
        selectRef.current &&
        !selectRef.current.contains(event.target)
      ) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('keydown', handleEscapeKey);

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleEscapeKey);
    };
  }, [isOpen]);

  useEffect(() => {
    if (initialValue !== undefined) {
      const option = options.find((opt) => opt[valueKey] === initialValue);
      setSelectedOption(option);
    } else {
      setSelectedOption(null);
    }
  }, [initialValue, options, valueKey]);

  const handleOptionClick = (option) => {
    setSelectedOption(option);
    setIsOpen(false);
    onChange?.(option[valueKey]);
  };

  if (!options.length) return null;

  return (
    <SelectWrapper ref={selectRef}>
      <SelectContainer>
        <SelectButton onClick={() => setIsOpen(!isOpen)} type="button">
          <SelectedValue>
            {selectedOption ? (
              <OptionName>{selectedOption[labelKey]}</OptionName>
            ) : (
              <Placeholder>Выберите...</Placeholder>
            )}
          </SelectedValue>
          <Chevron isOpen={isOpen}>▼</Chevron>
        </SelectButton>

        {isOpen && (
          <Dropdown>
            {options.map((option, index) => (
              <Option
                key={option[valueKey] || index}
                // selected={selectedOption ? selectedOption : null}
                onClick={() => handleOptionClick(option)}
              >
                <OptionName>{option[labelKey]}</OptionName>
                <SelectedValue></SelectedValue>
              </Option>
            ))}
          </Dropdown>
        )}
      </SelectContainer>
    </SelectWrapper>
  );
};
