import React, { useRef, useEffect, useContext, useState } from 'react';
import { Modal, ScrollView, StyleSheet, Text, TouchableHighlight, View } from 'react-native';
import { faCaretDown } from '@fortawesome/free-solid-svg-icons';
import { useField } from '@unform/core';
import * as _ from 'lodash';
import AppContext from '../../AppProvider/AppContext';
import { TextError, TitleText } from '../../Input/native/Input.style';
import { Pressable } from '../../Pressable';
import { TextNative } from '../../TextNative';
import { IPropsSelect, ISelectItems } from '../select.interface';
import { SelectStyle, SelectContainer, SelectItem, FontAwesomeIconItem, SelectItemPlaceHolder } from './Select.style';
import { SelectPure } from './SelectPure';

export interface IPropsSelectNative extends IPropsSelect {
   items: ISelectItems[];
}

function getValueSelect(options: ISelectItems[], value: any): any {
   let returnValue: any = null;

   options.forEach((i) => {
      if (i.value && _.isEqual(i.value, value)) {
         returnValue = i.value;
      } else if (_.isEqual(i.id, value)) {
         returnValue = i.value ? i.value : i.name;
      }
   });

   return returnValue;
}

function getValueSelectLabel(currentValue: any): any {
   return currentValue?.name || currentValue;
}

export const Select: React.FunctionComponent<IPropsSelectNative> = ({
   children,
   name,
   title,
   items,
   theme,
   as = SelectPure,
   ...rest
}: IPropsSelect) => {
   // Custom component
   const { pureComponents: { Select: SelectComponent = null } = {} } = useContext(AppContext);
   const Component = SelectComponent ?? as;

   const { fieldName, registerField, defaultValue, error, clearError } = useField(name);

   const [openModal, setOpenModal] = useState(false);
   const [labelSelect, setLabelSelect] = useState(getValueSelectLabel(defaultValue));
   const [placeholder, setPlaceholder] = useState('Selecione uma opção...');
   const [selectedValue, setSelectedValue] = useState(getValueSelect(items, defaultValue));
   const inputRef = useRef<any>(getValueSelect(items, defaultValue));

   useEffect(() => {
      registerField({
         name: fieldName,
         ref: inputRef,
         path: 'current',
      });
   }, [fieldName, registerField, children]);

   const select = (itemValue: ISelectItems): void => {
      if (itemValue.value) {
         setSelectedValue(itemValue.value);
         inputRef.current = itemValue.value;
      } else {
         setSelectedValue(itemValue.id);
         inputRef.current = itemValue.id;
      }

      setOpenModal(false);
      setLabelSelect(itemValue.name);
      clearError();
   };

   function onPress(): any {
      setOpenModal(true);
   }

   return (
      <View>
         {title && <TitleText>{title}</TitleText>}

         <SelectContainer testID="select" onPress={onPress} error={error} ripple>
            <View style={{ flex: 1 }}>
               {!labelSelect && <SelectItemPlaceHolder>{placeholder}</SelectItemPlaceHolder>}
               {!!labelSelect && <SelectItem>{labelSelect}</SelectItem>}
            </View>
            <View>
               <FontAwesomeIconItem icon={faCaretDown} />
            </View>
         </SelectContainer>

         {!!error && <TextError testID="select-error">{error}</TextError>}

         <ModalOptions openModal={openModal} setOpenModal={setOpenModal} items={items} select={select} />
      </View>
   );
};

function ModalOptions({ openModal, setOpenModal, items, select }): any {
   return (
      <Modal animationType="fade" visible={openModal} transparent>
         <View
            style={{
               flex: 1,
               justifyContent: 'center',
               alignItems: 'center',
               flexGrow: 1,
            }}
         >
            <Pressable
               onPress={() => setOpenModal(false)}
               style={{
                  flex: 1,
                  justifyContent: 'center',
                  alignItems: 'center',
                  backgroundColor: 'rgba(0,0,0,0.5)',
                  flexGrow: 1,
                  width: '100%',
                  height: '100%',
                  position: 'absolute',
               }}
            >
               <View />
            </Pressable>
            <View style={{ flexDirection: 'row' }}>
               <ScrollView
                  style={{
                     margin: 20,
                     width: '90%',
                     backgroundColor: 'white',
                     elevation: 5,
                  }}
                  contentContainerStyle={{ flexGrow: 1 }}
               >
                  <View
                     style={{
                        flex: 1,
                        padding: 10,
                     }}
                  >
                     {items &&
                        items.map((i) => (
                           <Pressable
                              style={{ paddingVertical: 10 }}
                              key={i.id}
                              onPress={() => select(i)}
                              testID={`option-${i.id}`}
                           >
                              <TextNative>{i.name}</TextNative>
                           </Pressable>
                        ))}
                  </View>
               </ScrollView>
            </View>
         </View>
      </Modal>
   );
}
