import React, { FC, useEffect, useState } from 'react';
import { Text, View } from 'react-native';

import { latinise } from '../../helpers/searchHelpers';
import { useSearchUnit } from '../../hooks/useSearchUnit';
import { useUserInfo } from '../../hooks/useStorage';
import { showFeedback } from '../../services/feedback/showFeedback';
import Button from '../Button/Button';
import Title from '../List/components/Title';
import InfoModal from '../Modal/InfoModal';
import SelectModal from '../Modal/SelectModal';
import Switch from '../Switch/Switch';
import TextField from '../TextField/TextField';
import TextFieldSelect from '../TextField/TextFieldSelect';

type props = {
  selectedUnitId: string;
  setSelectedUnitId: (value: string) => void;
};

const OrganizerUnitSelect: FC<props> = ({ selectedUnitId, setSelectedUnitId }) => {
  const [searchInNames, setCurrentSearchInNames] = useState(true);
  const [searchInRegNumbers, setCurrentSearchInRegNumbers] = useState(false);
  const [searchInPlace, setCurrentSearchInPlace] = useState(false);
  const [searchValue, setSearchValue] = useState('');
  const [userInfo] = useUserInfo();

  const [isUnitModalVisible, setIsUnitModalVisible] = useState(false);
  const [isInfoModalVisible, setIsInfoModalVisible] = useState(false);
  const [buttonClicked, setButtonClicked] = useState(false);
  const [firstTime, setFirstTime] = useState(true);

  const {
    data: list,
    isFetching: isLoading,
    refetch: refetchList,
  } = useSearchUnit(
    userInfo.token,
    searchInRegNumbers ? searchValue : '',
    false,
    searchInNames ? searchValue : '',
    searchInPlace ? searchValue : '',
    '',
    '',
    '',
  );

  const formattedUnit = (unit: any): string => {
    if (!unit) return '';
    return `${unit.number} - ${unit.displayName}`;
  };

  const [unit, setUnit] = useState<string>(
    selectedUnitId || formattedUnit(list?.find((item: any) => item.id === userInfo.unitId)),
  );

  useEffect(() => {
    if (!isLoading) {
      if (firstTime) {
        setFirstTime(false);
        setUnit(formattedUnit(list?.find((item: any) => item.id === userInfo.unitId)));
      }
      if (buttonClicked) {
        setButtonClicked(false);
        if (list?.length === 0) {
          setIsInfoModalVisible(true);
        } else {
          setIsUnitModalVisible(true);
        }
      }
    }
  }, [isLoading]);

  return (
    <View>
      <Title text="Vyhledat pořadatele" />
      <View className="mt-4 rounded bg-secondary-bg p-4">
        <View className="mb-4">
          <TextField
            title="Text na vyhledání pořadatele"
            value={searchValue}
            setValue={value => setSearchValue(latinise(value))}
          />
        </View>
        <View className="flex-row items-center justify-between">
          <Text className="font-bold">Hledat podle názvu</Text>
          <Switch
            setIsEnabled={value => {
              if (value) {
                setCurrentSearchInRegNumbers(false);
                setCurrentSearchInPlace(false);
              } else if (!searchInRegNumbers && !setCurrentSearchInPlace && !value) {
                return;
              }
              setCurrentSearchInNames(value);
            }}
            isEnabled={searchInNames}
          />
        </View>
        <View className="flex-row items-center justify-between">
          <Text className="font-bold">Hledat podle evidenčního čísla</Text>
          <Switch
            setIsEnabled={value => {
              if (value) {
                setCurrentSearchInNames(false);
                setCurrentSearchInPlace(false);
              } else if (!searchInNames && !setCurrentSearchInPlace && !value) {
                return;
              }
              setCurrentSearchInRegNumbers(value);
            }}
            isEnabled={searchInRegNumbers}
          />
        </View>
        <View className="flex-row items-center justify-between">
          <Text className="font-bold">Hledat podle místa působení</Text>
          <Switch
            setIsEnabled={value => {
              if (value) {
                setCurrentSearchInNames(false);
                setCurrentSearchInRegNumbers(false);
              } else if (!searchInNames && !searchInRegNumbers && !value) {
                return;
              }
              setCurrentSearchInPlace(value);
            }}
            isEnabled={searchInPlace}
          />
        </View>
        <Button
          variant="ternary"
          onPress={() => {
            setButtonClicked(true);
            refetchList();
          }}
        >
          {isLoading ? 'Načítám...' : 'Hledat Pořadatelé'}
        </Button>
        <View className="mt-4">
          <TextFieldSelect
            title="Nalezení pořadatelé"
            items={(list || []).map(item => formattedUnit(item))}
            value={unit}
            setValue={value => {
              setSelectedUnitId(list?.find(item => formattedUnit(item) === value)?.id || '');
              setUnit(value);
            }}
            fullHeight={list && list?.length > 20}
            onWarning={
              list && !list.length
                ? () =>
                    showFeedback({
                      type: 'warning',
                      title: 'Nejdříve vyhledejte pořadatele',
                    })
                : undefined
            }
          />
        </View>
      </View>

      <InfoModal
        isVisible={isInfoModalVisible}
        setIsVisible={setIsInfoModalVisible}
        title="Hledání pořadatele"
        text="Žádný pořadatel nebyl nalezen."
      />
      <SelectModal
        items={(list || []).map(item => formattedUnit(item))}
        selected={unit}
        setSelected={(value: string) => {
          setSelectedUnitId(list?.find(item => formattedUnit(item) === value)?.id || '');
          setUnit(value);
        }}
        fullHeight={(list?.length || 0) > 20}
        title="Vyberte položku"
        itemGetter={item => item}
        isVisible={isUnitModalVisible}
        setIsVisible={setIsUnitModalVisible}
      />
    </View>
  );
};

export default OrganizerUnitSelect;
