import React, { useContext, useEffect, useState } from "react";
import { ThemeContext } from "context/context";
import {
  Select,
  Modal,
  ModalTouchable,
  ModalContent,
  ModalScroll,
  ModalArea,
  Option,
  OptionText,
  HeaderOptions,
  SelectText,
  HeaderText,
} from "./styles";
import { AtomIcon } from "native/atoms/Icon";
import { ErrorsInput } from "interfaces";
import { CSSObject } from "styled-components";
import { Text, View } from "react-native";
import { AtomHeadline } from "native/atoms/Typography/Headline";
import { theme } from "data/dataMx";

export interface IAtomSelectProps {
  /** Array of options */
  items: Array<string | number>;
  /** Value option by default */
  value: string;
  /** Disabled flag by default */
  disabled?: boolean;
  /** Func onChangeValue */
  onChangeValue?: (value: string) => any;
  /** Width component by default */
  width?: string;
  /** Height component by default */
  height?: string;
  required?: boolean;
  readOnly?: boolean;
  hasError?: boolean;
  testID?: string;
  styles?: CSSObject | string;
  errorCallback?: (value: string) => any;
}

export const AtomSelect = ({
  items,
  value,
  disabled = false,
  required = false,
  readOnly = false,
  hasError = false,
  onChangeValue = () => {},
  errorCallback = () => {},
  width = "280px",
  height = "56px",
  testID = "select",
  styles,
}: IAtomSelectProps) => {
  const { fontFamily } = useContext(ThemeContext);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [valueOption, setValueOption] = useState<
    string | ReadonlyArray<string> | number
  >(value);
  const [phColor, setPhColor] = useState<boolean>(true);
  const [hasErrorVal, setHasErrorVal] = useState<boolean>(hasError);
  const changeModalVisibility = (bool: boolean) => {
    setIsModalVisible(bool);
  };

  const onPressItem = (item: string) => {
    changeModalVisibility(!isModalVisible);
    onChangeValue && onChangeValue(item);
    setValueOption(item);
    setPhColor(false);
  };

  const checkRequired = () => {
    setHasErrorVal(false);
    if (required && phColor && value) {
      let error: ErrorsInput = null;
      setHasErrorVal(true);
      error = "required";
      error && errorCallback && errorCallback(error);
    }
  };

  useEffect(() => {
    setValueOption(value);
  }, [value]);

  useEffect(() => {
    setHasErrorVal(hasError);
  }, [hasError]);

  useEffect(() => {
    checkRequired();
  });

  return (
    <>
      <Select
          onPress={
            !readOnly ? () => changeModalVisibility(!isModalVisible) : () => {}
          }
          disabled={disabled}
          testID={testID}
          width={width}
          height={height}
          hasError={hasErrorVal}
          readOnly={readOnly}
          styles={styles}
          activeOpacity={1}
        >
          <SelectText
            disabled={disabled}
            fontFamily={fontFamily.main["regular"]}
            placeholderColor={phColor}
          >
            {valueOption}
          </SelectText>
          <AtomIcon name={"keyboard_arrow_down"} size={10} />
      </Select>
      <Modal
        transparent={true}
        animationType="fade"
        visible={isModalVisible}
        onRequestClose={() => changeModalVisibility(!isModalVisible)}
      >
        <ModalTouchable
          onPress={() => {
            changeModalVisibility(!isModalVisible)
          }}
          testID="modal-touchable"
        >
          <ModalArea>
            <ModalContent width={width}>
              <ModalScroll>
                <HeaderOptions>
                  <HeaderText>
                    <AtomHeadline size="small" text="Select One" weight="semibold" color="neutral600"/>
                  </HeaderText>
                </HeaderOptions>
                {items.map((item, index) => {
                  const itemString = item.toString();
                  return (
                    <Option
                      key={index}
                      index={index}
                      onPress={() => onPressItem(itemString)}
                      testID={`${testID}-${item}`}
                      activeOpacity={1}
                      underlayColor= {theme.neutral200}
                    >
                      <OptionText>{itemString}</OptionText>
                    </Option>
                  );
                })}
              </ModalScroll>
            </ModalContent>
          </ModalArea>
        </ModalTouchable>
      </Modal>
    </>
  );
};
