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

import Button from '../../../../components/Button/Button';
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 { DATES, CONG_EVENTS_RELATIONS, FILTER_ALL } from '../../../../constants/custom';
import {
  CONG_EVENT_SORTING,
  SORT_DIRECTION,
  SORT_DIRECTION_TAG,
  SORT_TAG,
} from '../../../../constants/sorting';
import { getDateAsString } from '../../../../helpers/stringHelpers';
import { useCongressAll } from '../../../../hooks/useCongress';
import { useFilterButtons } from '../../../../hooks/useFilterButtons';
import useSortList from '../../../../hooks/useSortList';
import { useUserInfo } from '../../../../hooks/useStorage';
import CongressFilterModal from './components/CongressFilterModal';

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

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

  useFilterButtons(setSortModalVisible, setFilterModalVisible);

  const [name, setName] = useState('');
  const [date, setDate] = useState(DATES[1].label);
  const [relation, setRelation] = useState(CONG_EVENTS_RELATIONS[1].label);

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

  const relationValue = CONG_EVENTS_RELATIONS.find(r => r.label === relation)?.value ?? '';

  const { data: list, isLoading } = useCongressAll(
    userInfo.token,
    DATES.find(d => d.label === date)?.value
      ? DATES.find(d => d.label === date)?.value === 'future'
        ? 'true'
        : ''
      : '',
    relationValue === 'Unit' ? 'true' : '',
    relationValue === 'ChildDirect' ? 'true' : '',
    relationValue === 'ChildUnit' ? 'true' : '',
    relationValue === 'Participant' ? 'true' : '',
  );

  const sortedList = useSortList(list || [], sortDirection, sort, CONG_EVENT_SORTING);
  const filteredList = sortedList.filter(item => {
    if (name.length) {
      return item.eventName.toLowerCase().includes(name.toLowerCase());
    }
    return true;
  });

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      <TagGroup
        items={[
          `${SORT_TAG} ${CONG_EVENT_SORTING.find(s => s.label === sort)?.displayName ?? ''}`,
          `${SORT_DIRECTION_TAG} ${sortDirection}`,
          ...(name.length ? [`Pořadatel: ${name}`] : []),
          ...(date !== FILTER_ALL ? [`Akce: ${date}`] : []),
          ...(relation !== FILTER_ALL ? [`Vztah k akci: ${relation}`] : []),
        ]}
      />
      {!isLoading ? (
        <>
          {filteredList?.length ? (
            <FlashList
              estimatedItemSize={100}
              data={filteredList}
              extraData={expandedId}
              keyExtractor={(item, index) => `${item.id}-${index}`}
              renderItem={({ item, index }) => (
                <DropdownCard
                  title={item.eventName}
                  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,
                    },
                    ...(item.type.length
                      ? [
                          {
                            title: 'Typ',
                            value: item.type,
                            dropdown: true,
                          },
                        ]
                      : []),
                    ...(item.type.location
                      ? [
                          {
                            title: 'Místo konání',
                            value: item.location,
                            dropdown: true,
                          },
                        ]
                      : []),
                  ]}
                >
                  <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('CongressDetail', {
                          id: item.id,
                          eventName: item.eventName,
                        })
                      }
                    >
                      Detail
                    </Button>
                  </View>
                </DropdownCard>
              )}
            />
          ) : (
            <Text className="mt-4 rounded bg-secondary-bg p-4">
              Pro daná kritéria nebyly nalezeny žádné akce.
            </Text>
          )}
        </>
      ) : (
        <Loader />
      )}
      <SortingModal
        isVisible={sortModalVisible}
        setIsVisible={setSortModalVisible}
        values={CONG_EVENT_SORTING}
        selectedValue={sort}
        setSelectedValue={setSort}
        selectedDirection={sortDirection}
        setSelectedDirection={setSortDirection}
      />
      <CongressFilterModal
        isVisible={filterModalVisible}
        setIsVisible={setFilterModalVisible}
        name={name}
        setName={setName}
        date={date}
        setDate={setDate}
        relation={relation}
        setRelation={setRelation}
      />
    </View>
  );
};

export default Congress;
