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 {
  EVENTS_SORTING,
  SORT_DIRECTION,
  SORT_DIRECTION_TAG,
  SORT_TAG,
} from '../../../../constants/sorting';
import { getDateAsString } from '../../../../helpers/stringHelpers';
import { useEventFilter, useEventGeneralAllGet } from '../../../../hooks/useEvents';
import { useFilterButtons } from '../../../../hooks/useFilterButtons';
import useSortList from '../../../../hooks/useSortList';
import { useUserInfo } from '../../../../hooks/useStorage';
import EventsFilterModal from './components/EventsFilterModal';

const Events = () => {
  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(EVENTS_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 [type, setType] = useState(FILTER_ALL);
  const [scope, setScope] = useState(FILTER_ALL);

  const { states, types, scopes } = useEventFilter(userInfo?.token);

  const relationValue = EVENTS_RELATIONS.find(r => r.label === relation)?.value ?? '';
  const typeId = types?.find(t => t.displayName === type)?.id ?? '';
  const stateId = states?.find(s => s.displayName === state)?.id ?? '';
  const scopeId = scopes?.find(s => s.displayName === scope)?.id ?? '';
  const { data: list, isFetching: isLoading } = useEventGeneralAllGet(
    userInfo?.token,
    isFuture === undefined ? '' : `${isFuture}`,
    year,
    relationValue === EVENTS_RELATIONS[1].value ? 'true' : '',
    relationValue === EVENTS_RELATIONS[2].value ? 'true' : '',
    relationValue === EVENTS_RELATIONS[3].value ? 'true' : '',
    typeId,
    stateId,
    scopeId,
  );

  const topButtons = [
    <IconButton
      key="add"
      classNames="mr-2"
      variant="secondary"
      onPress={() =>
        navigation.navigate('EventEdit', {
          filterIsFuture: isFuture,
          filterYear: year,
          filterRelationValue: relationValue,
          filterTypeId: typeId,
          filterStateId: stateId,
          filterScopeId: scopeId,
        })
      }
    >
      <FontAwesome5 name="plus" size={28} />
    </IconButton>,
  ];

  useFilterButtons(setSortModalVisible, setFilterModalVisible, topButtons);

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

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      <TagGroup
        items={[
          `${SORT_TAG} ${EVENTS_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'}`] : []),
          ...(type !== FILTER_ALL ? [`Typ: ${type}`] : []),
          ...(scope !== FILTER_ALL ? [`Rozsah: ${scope}`] : []),
        ]}
      />
      {!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: 'Typ:',
                      value: item.type,
                    },
                    {
                      title: 'Rozsah:',
                      value: item.scope,
                    },
                    {
                      title: 'Stav:',
                      value: item.state,
                    },
                  ]}
                >
                  <View className="flex-1 flex-row justify-end pb-4 pr-3">
                    <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('EventDetail', {
                          id: item.id,
                          isRelation: relationValue === EVENTS_RELATIONS[1].value,
                          eventName: item.displayName,
                          filterIsFuture: isFuture,
                          filterYear: year,
                          filterRelationValue: relationValue,
                          filterTypeId: typeId,
                          filterStateId: stateId,
                          filterScopeId: scopeId,
                        })
                      }
                    >
                      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={EVENTS_SORTING}
        selectedValue={sort}
        setSelectedValue={setSort}
        selectedDirection={sortDirection}
        setSelectedDirection={setSortDirection}
      />
      <EventsFilterModal
        isVisible={filterModalVisible}
        setIsVisible={setFilterModalVisible}
        state={state}
        setState={setState}
        isFuture={isFuture}
        setIsFuture={setIsFuture}
        year={year}
        setYear={setYear}
        relation={relation}
        setRelation={setRelation}
        type={type}
        setType={setType}
        scope={scope}
        setScope={setScope}
      />
    </View>
  );
};

export default Events;
