import { FontAwesome5 } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import { FlashList } from '@shopify/flash-list';
import React, { useState } from 'react';
import { View, Text } from 'react-native';

import Button from '../../../../components/Button/Button';
import IconButton from '../../../../components/Button/IconButton';
import { DropdownCard } from '../../../../components/Dropdown/Dropdown';
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 { EVENTS_RELATIONS, FILTER_ALL, FILTER_ALL_BUT_CANCEL } from '../../../../constants/custom';
import {
  CAMP_SORTING,
  SORT_DIRECTION,
  SORT_DIRECTION_TAG,
  SORT_TAG,
} from '../../../../constants/sorting';
import { getDateAsString } from '../../../../helpers/stringHelpers';
import { useEventCampAll } from '../../../../hooks/useCamps';
import { useFilterButtons } from '../../../../hooks/useFilterButtons';
import useSortList from '../../../../hooks/useSortList';
import { useUserInfo } from '../../../../hooks/useStorage';
import { dialCall } from '../../../../services/nativeHelpers/dialCall';
import CampFilterModal from './components/CampFilterModal';

const Camps = () => {
  const navigation = useNavigation<NavProps>();
  const [userInfo] = useUserInfo();
  const [expandedId, setExpandedId] = useState('');

  const [filterModalVisible, setFilterModalVisible] = useState(false);
  const [sortModalVisible, setSortModalVisible] = useState(false);

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

  const [state, setState] = useState(FILTER_ALL_BUT_CANCEL);
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [isFuture, setIsFuture] = useState<boolean | undefined>(undefined);
  const [relation, setRelation] = useState(EVENTS_RELATIONS[1].label);
  const [name, setName] = useState('');
  const [location, setLocation] = useState('');
  const [regNumber, setRegNumber] = useState('');

  const relationValue = EVENTS_RELATIONS.find(r => r.label === relation)?.value ?? '';
  const { data: list, isFetching: isLoading } = useEventCampAll(
    userInfo?.token,
    userInfo.roleId,
    name,
    isFuture === undefined ? '' : `${isFuture}`,
    year,
    relationValue === EVENTS_RELATIONS[1].value ? 'true' : '',
    relationValue === EVENTS_RELATIONS[2].value ? 'true' : '',
    relationValue === EVENTS_RELATIONS[3].value ? 'true' : '',
    regNumber,
    location,
  );

  const topButtons = [
    <IconButton
      key="add"
      classNames="mr-2"
      variant="secondary"
      onPress={() =>
        navigation.navigate('CampEdit', {
          id: undefined,
          filterName: name,
          filterIsFuture: isFuture,
          filterYear: year,
          filterRelationValue: relationValue,
          filterRegNumber: regNumber,
          filterLocation: location,
        })
      }
    >
      <FontAwesome5 name="plus" size={28} />
    </IconButton>,
  ];

  useFilterButtons(setSortModalVisible, setFilterModalVisible, topButtons);

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

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      <TagGroup
        items={[
          `${SORT_TAG} ${CAMP_SORTING.find(s => s.label === sort)?.displayName ?? ''}`,
          `${SORT_DIRECTION_TAG} ${sortDirection}`,
          ...(state !== FILTER_ALL_BUT_CANCEL ? [`Stav: ${state}`] : []),
          ...(relation !== FILTER_ALL ? [`Vztah k akci: ${relation}`] : []),
          ...(year ? [`Rok: ${year}`] : []),
          ...(isFuture ? [`Termín: ${isFuture ? 'Již proběhla' : 'Teprve proběhne'}`] : []),
          ...(name.length ? [`Název: ${name}`] : []),
          ...(location.length ? [`Místo konání: ${name}`] : []),
          ...(regNumber.length ? [`Evidenční číslo: ${name}`] : []),
        ]}
      />
      {!isLoading ? (
        <View className="flex-1 space-y-4">
          {sortedList?.length ? (
            <FlashList
              estimatedItemSize={100}
              data={sortedList}
              extraData={expandedId}
              keyExtractor={(item, index) => `${item.id}-${index}`}
              renderItem={({ item, index }) => (
                <DropdownCard
                  title={item.displayName}
                  expandedId={expandedId}
                  setExpandedId={setExpandedId}
                  currentId={`${item.id}-${index}`}
                  items={[
                    {
                      title: 'Termín:',
                      value:
                        !item.startDate || !item.endDate
                          ? 'Bez omezení'
                          : `od ${getDateAsString(new Date(item.startDate))} do ${getDateAsString(
                              new Date(item.endDate),
                            )}`,
                    },
                    {
                      title: 'Pořádající jednotka:',
                      value: item.unit,
                    },
                    {
                      title: 'Stav:',
                      value: item.state,
                    },
                    ...(item.location
                      ? [
                          {
                            title: 'Místo konání:',
                            value: item.location,
                            dropdown: true,
                          },
                        ]
                      : []),
                    ...(item.personLeader
                      ? [
                          {
                            title: 'Vedoucí tábora:',
                            value: item.personLeader,
                            dropdown: true,
                          },
                        ]
                      : []),
                    ...(item.mobile
                      ? [
                          {
                            title: 'Telefon:',
                            value: item.mobile,
                            dropdown: true,
                          },
                        ]
                      : []),
                  ]}
                >
                  <View className="flex-1 flex-row justify-end pb-4 pr-3">
                    <Button
                      classNames="py-1 pl-5"
                      variant="text"
                      onPress={() => dialCall(item.mobile)}
                    >
                      Zavolat
                    </Button>
                    <Button
                      classNames="py-1 pl-5"
                      variant="text"
                      onPress={() => navigation.navigate('UnitInfo', { id: item.unitId })}
                    >
                      Jednotka
                    </Button>
                    <Button
                      classNames="py-1 pl-5"
                      variant="text"
                      onPress={() =>
                        navigation.navigate('CampDetail', {
                          id: item.id,
                          isRelation: relationValue === EVENTS_RELATIONS[1].value,
                          campName: item.displayName,
                          filterName: name,
                          filterIsFuture: isFuture,
                          filterYear: year,
                          filterRelationValue: relationValue,
                          filterRegNumber: regNumber,
                          filterLocation: location,
                        })
                      }
                    >
                      Detail
                    </Button>
                  </View>
                </DropdownCard>
              )}
            />
          ) : (
            <Text className="mt-4 rounded bg-secondary-bg p-4">
              Pro daná kritéria nebyly nalezeny žádné akce.
            </Text>
          )}
        </View>
      ) : (
        <Loader />
      )}
      <SortingModal
        isVisible={sortModalVisible}
        setIsVisible={setSortModalVisible}
        values={CAMP_SORTING}
        selectedValue={sort}
        setSelectedValue={setSort}
        selectedDirection={sortDirection}
        setSelectedDirection={setSortDirection}
      />
      <CampFilterModal
        isVisible={filterModalVisible}
        setIsVisible={setFilterModalVisible}
        state={state}
        setState={setState}
        isFuture={isFuture}
        setIsFuture={setIsFuture}
        year={year}
        setYear={setYear}
        relation={relation}
        setRelation={setRelation}
        name={name}
        setName={setName}
        location={location}
        setLocation={setLocation}
        regNumber={regNumber}
        setRegNumber={setRegNumber}
      />
    </View>
  );
};

export default Camps;
