import { useNavigation } from '@react-navigation/native';
import FlashList from '@shopify/flash-list/dist/FlashList';
import cn from 'classnames';
import React, { useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

import Loader from '../../../../components/Loader/Loader';
import SortingModal from '../../../../components/Modal/SortingModal';
import { NavProps } from '../../../../components/Routes/Routes';
import TagGroup from '../../../../components/TagGroup/TagGroup';
import { UNIT_AREA_LIST } from '../../../../constants/custom';
import {
  SORT_DIRECTION,
  SORT_DIRECTION_TAG,
  SORT_TAG,
  UNIT_SORTING,
} from '../../../../constants/sorting';
import { useFilterButtons } from '../../../../hooks/useFilterButtons';
import { useSearchUnit } from '../../../../hooks/useSearchUnit';
import useSortList from '../../../../hooks/useSortList';
import { useUserInfo } from '../../../../hooks/useStorage';
import UnitFilterModal from './components/UnitFilterModal';

const SearchUnit = () => {
  const [userInfo] = useUserInfo();
  const navigation = useNavigation<NavProps>();

  const [number, setNumber] = useState('');
  const [byNumberStart, setByNumberStart] = useState(false);
  const [name, setName] = useState('');
  const [place, setPlace] = useState('');
  const [area, setArea] = useState(UNIT_AREA_LIST[0].label);
  const [bankAccount, setBankAccount] = useState('');
  const [ic, setIc] = useState('');
  const [filterModalVisible, setFilterModalVisible] = useState(false);
  const [sortModalVisible, setSortModalVisible] = useState(false);

  useFilterButtons(setSortModalVisible, setFilterModalVisible);

  const [sort, setSort] = useState(UNIT_SORTING[1].label);
  const [sortDirection, setSortDirection] = useState(SORT_DIRECTION[0].label);

  const { data: list, isLoading } = useSearchUnit(
    userInfo.token,
    number,
    byNumberStart,
    name,
    place,
    UNIT_AREA_LIST.find(a => a.label === area)?.id ?? '',
    bankAccount,
    ic,
  );

  const sortedList = useSortList(list || [], sortDirection, sort, UNIT_SORTING);

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      <TagGroup
        classNames="mb-4"
        items={[
          `${SORT_TAG} ${UNIT_SORTING.find(s => s.label === sort)?.displayName ?? ''}`,
          `${SORT_DIRECTION_TAG} ${sortDirection}`,
          ...(number.length ? [`Evidenční číslo: ${number}`] : []),
          ...(byNumberStart ? [`Evidenční číslo začíná`] : []),
          ...(name.length ? [`Jméno: ${name}`] : []),
          ...(place.length ? [`Místo působení: ${place}`] : []),
          ...(area !== UNIT_AREA_LIST[0].label ? [`Zaměření: ${area}`] : []),
          ...(bankAccount.length ? [`Bankovní účet: ${bankAccount}`] : []),
          ...(ic.length ? [`IČ: ${ic}`] : []),
        ]}
      />
      {!isLoading ? (
        <View className="flex-1 space-y-4">
          {sortedList?.length ? (
            <FlashList
              estimatedItemSize={100}
              data={sortedList}
              renderItem={({ item }) => (
                <TouchableOpacity
                  key={item.id}
                  onPress={() => navigation.navigate('UnitInfo', { id: item.id })}
                  className="mb-4 rounded bg-secondary-bg p-2"
                >
                  <Text className="p-2 font-panton text-lg font-bold text-primary">
                    {item.displayName}
                  </Text>
                  {[
                    {
                      title: 'Evidenční číslo',
                      value: item.number,
                    },
                    {
                      title: 'Typ jednotky',
                      value: item.type,
                    },
                    {
                      title: 'Místo působení',
                      value: item.place,
                    },
                  ]?.map((row, index) => (
                    <View key={index}>
                      {row && (
                        <>
                          <View
                            className={cn('flex-row justify-between p-2', {
                              'rounded-sm bg-primary-bg': index % 2 === 1,
                            })}
                          >
                            <Text>{row?.title}</Text>
                            <Text className="flex-1 flex-wrap text-right">{row?.value}</Text>
                          </View>
                        </>
                      )}
                    </View>
                  ))}
                </TouchableOpacity>
              )}
            />
          ) : (
            <Text className="mt-4 rounded bg-secondary-bg p-4">
              Pro danná kritéria nebyly nalezeny žádné jednotky.
            </Text>
          )}
        </View>
      ) : (
        <Loader />
      )}
      <SortingModal
        isVisible={sortModalVisible}
        setIsVisible={setSortModalVisible}
        values={UNIT_SORTING}
        selectedValue={sort}
        setSelectedValue={setSort}
        selectedDirection={sortDirection}
        setSelectedDirection={setSortDirection}
      />
      <UnitFilterModal
        isVisible={filterModalVisible}
        setIsVisible={setFilterModalVisible}
        number={number}
        setNumber={setNumber}
        byNumberStart={byNumberStart}
        setByNumberStart={setByNumberStart}
        name={name}
        setName={setName}
        place={place}
        setPlace={setPlace}
        area={area}
        setArea={setArea}
        bankAccount={bankAccount}
        setBankAccount={setBankAccount}
        ic={ic}
        setIc={setIc}
      />
    </View>
  );
};

export default SearchUnit;
