import React, { useEffect, useRef, useState } from "react";
import { theme } from "data/dataMx";
import {
  Select,
  Option,
  ItemContainer,
  Value,
  ContainerText,
  ContainerIcon,
  ContainerInput,
  ContainerIconFlag,
  IconContainer,
} from "./styles";
import { AtomIcon } from "native/atoms/Icon";
import { AtomBody } from "native/atoms/Typography/Body";
import { ICountriesProps } from "interfaces";
import { countriesList } from "data/countries";
import { CSSObject } from "styled-components";

export interface ICountryPickerProps {
  /** Enable or disable the selector */
  disabled?: boolean;
  /** Country codes array that will appear first */
  importantItems?: string[];
  /** Flag showing if there is an error */
  hasError?: boolean;
  /** Minimum width */
  minWidth?: string;
  /** Text when nothing is selected */
  placeholder?: string;
  /** Unable to change selected value */
  readOnly?: boolean;
  /** Initial selected value */
  value?: string;
  /** Flag showing name countries */
  viewCountry?: boolean;
  required?: boolean;
  /** Action of changing value selected */
  onChange?: (value: ICountriesProps) => void;
  /** Css proprieties */
  styles?: CSSObject;
}

export const AtomCountryPicker = ({
  disabled = false,
  importantItems,
  hasError = false,
  minWidth = "180px",
  value,
  viewCountry = true,
  placeholder = "-",
  readOnly = false,
  required = false,
  onChange,
  styles = {},
  ...props
}: ICountryPickerProps) => {
  const [countriesListNew, setCountriesListNew] = useState([...countriesList]);
  const [items, setItems] = useState(countriesListNew);
  const [view, setView] = useState(false);
  const [actualValue, setActualValue] = useState(
    countriesListNew.find((x) => x.id == value)
  );
  const positionInit = items.find((item) => item.id === actualValue?.id);
  const [valueSelect, setValueSelect] = useState(
    positionInit ? items.indexOf(positionInit) : 0
  );
  const [valueInput, setValueInput] = useState("");
  const [viewIcon, setViewIcon] = useState(!!actualValue?.id);

  const myOptions = useRef<null | any>(null);

  const handlerSetValueSelect = () => {
    const position: any = items.find((item) => item.id === actualValue?.id);
    setValueSelect(position ? items.indexOf(position) : 0);
  };

  const scroll = (keyBoard?: string) => {
    if (keyBoard && myOptions && myOptions.current) {
      myOptions.current.scrollTo({
        y: 0,
        animated: true,
      });
    } else {
      const positionItem = items.findIndex((x) => x.id === actualValue?.id);
      myOptions &&
        myOptions.current?.scrollTo({
          y: actualValue?.id ? positionItem * 40 : 0,
          animated: false,
        });
    }
  };

  const toggleOptions = () => {
    if (!disabled && !readOnly) {
      handlerSetValueSelect();
      setView(true);
      setViewIcon(false);
      setTimeout(() => {
        scroll();
      }, 50);
    }
  };

  const handleChange = (event: any) => {
    setView(true);
    setValueInput(event);
    const NewItems = countriesListNew.filter((item) =>
      item.name.toLowerCase().includes(event.toLowerCase())
    );
    setItems(NewItems);
    const value = NewItems.findIndex((item) => item.id == actualValue?.id);
    if (value > 0) {
      setValueSelect(value);
    } else {
      setValueSelect(0);
      scroll("clear");
    }
  };

  const setSelectedThenCloseDropdown = (index: number) => {
    onChange && onChange(items[index]);
    setActualValue(items[index]);
    setValueInput("");
    setValueSelect(index);
    setView(false);
    setItems(countriesListNew);
    setViewIcon(true);
  };

  const sortArray = () => {
    let count = 0;
    const list = [...countriesListNew];
    importantItems?.forEach((item) => {
      const element = list.find((country) => country.id == item);
      if (element) {
        const indexOf = items.indexOf(element);
        list.splice(indexOf, 1);
        list.splice(count, 0, element);
        count++;
      }
    });
    setCountriesListNew(list);
    setItems(list);
  };

  useEffect(() => {
    setActualValue(countriesListNew.find((x) => x.id == value));
  }, [value]);

  useEffect(() => {
    if (!disabled && !readOnly) {
      sortArray();
    }
  }, [importantItems, disabled, readOnly]);

  return (
    <Select>
      <ContainerInput
        onPress={() => toggleOptions()}
        minWidth={minWidth}
        disabled={disabled}
      >
        {viewIcon && (
          <ContainerIconFlag>
            <AtomIcon name={actualValue?.icon ?? ""} size={24} />
          </ContainerIconFlag>
        )}
        <Value
          disabled={disabled}
          onChangeText={(e: any) => handleChange(e)}
          testID={"input-country-picker"}
          value={valueInput}
          actualValue={!!actualValue?.id}
          readOnly={readOnly}
          placeholder={
            !viewIcon && actualValue?.id
              ? ""
              : actualValue?.id
              ? `+${actualValue.code} ${viewCountry ? actualValue.name : ""}`
              : placeholder
          }
          hasError={hasError}
          viewIcon={viewIcon}
          placeholderTextColor={
            actualValue ? theme.neutral700 : theme.neutral500
          }
          styles={styles}
          {...props}
        ></Value>
        {!disabled && (
          <ContainerIcon>
            <AtomIcon
              name={"keyboard_arrow_down"}
              size={10}
              color={"neutral600"}
            />
          </ContainerIcon>
        )}
      </ContainerInput>
      {view && !disabled && (
        <Option theme={theme} ref={myOptions} testID={"options"}>
          {items.map((item: ICountriesProps, index) => (
            <ItemContainer
              key={item.id}
              theme={theme}
              disabled={disabled}
              aria-selected={valueSelect == index}
              backGround={
                item.id == items[valueSelect]?.id
                  ? theme.neutral200
                  : theme.neutral100
              }
              onPress={() => {
                setSelectedThenCloseDropdown(index);
              }}
            >
              <IconContainer>
                <AtomIcon name={item.icon} size={24} />
              </IconContainer>
              <ContainerText testID={item.id}>
                <AtomBody
                  size="large"
                  text={`+${item.code} ${item.name}`}
                  align="left"
                  color={"neutral700"}
                  weight="regular"
                />
              </ContainerText>
            </ItemContainer>
          ))}
        </Option>
      )}
    </Select>
  );
};
