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 { 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 { EDU_EVENTS_RELATIONS, FILTER_ALL } from '../../../../constants/custom';
import {
  EDUC_EVENT_SORTING,
  SORT_DIRECTION,
  SORT_DIRECTION_TAG,
  SORT_TAG,
} from '../../../../constants/sorting';
import { getDateAsString } from '../../../../helpers/stringHelpers';
import { useEducation, useEducationTypes } from '../../../../hooks/useEducation';
import { useFilterButtons } from '../../../../hooks/useFilterButtons';
import useSortList from '../../../../hooks/useSortList';
import { useUserInfo } from '../../../../hooks/useStorage';
import EducationFilterModal from './components/EducationFilterModal';

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

  const [organization, setOrganization] = useState('');
  const [year, setYear] = useState('');
  const [isFuture, setIsFuture] = useState<boolean | undefined>(undefined);
  const [relation, setRelation] = useState(EDU_EVENTS_RELATIONS[1].label);
  const [type, setType] = useState(FILTER_ALL);
  const [filterModalVisible, setFilterModalVisible] = useState(false);
  const [sortModalVisible, setSortModalVisible] = useState(false);

  useFilterButtons(setSortModalVisible, setFilterModalVisible);

  const { data: types, isLoading: isTypesLoading } = useEducationTypes(userInfo?.token);

  const { list, isLoading } = useEducation(
    userInfo.token,
    types?.find(item => item.displayName === type)?.id || '',
    isFuture === undefined ? '' : `${isFuture}`,
    year,
    EDU_EVENTS_RELATIONS.find(item => item.label === relation)?.value || '',
  );

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

  const sortedList = useSortList(list || [], sortDirection, sort, EDUC_EVENT_SORTING);
  const filteredList = sortedList
    .filter(item => {
      if (organization.length) {
        return item.displayName.toLowerCase().includes(organization.toLowerCase());
      }
      return true;
    })
    .filter(item => {
      if (type !== FILTER_ALL) {
        return item.type === type;
      }
      return true;
    });

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      <TagGroup
        items={[
          `${SORT_TAG} ${EDUC_EVENT_SORTING.find(s => s.label === sort)?.displayName ?? ''}`,
          `${SORT_DIRECTION_TAG} ${sortDirection}`,
          ...(organization.length ? [`Pořadatel: ${organization}`] : []),
          ...(year ? [`Rok: ${year}`] : []),
          ...(isFuture ? [`Termín: ${isFuture ? 'Již proběhla' : 'Teprve proběhne'}`] : []),
          ...(relation !== FILTER_ALL ? [`Vztah k akci: ${relation}`] : []),
          ...(type !== FILTER_ALL ? [`Typ akce: ${type}`] : []),
        ]}
      />
      {!isLoading && !isTypesLoading ? (
        <View className="flex-1 space-y-4">
          {filteredList?.length ? (
            <FlashList
              estimatedItemSize={100}
              data={filteredList}
              extraData={expandedId}
              keyExtractor={(item, index) => `${item.id}-${index}`}
              renderItem={({ item, index }) => (
                <DropdownCard
                  title={item.displayName}
                  logo={item.logo.length ? item.logo : 'empty'}
                  expandedId={expandedId}
                  setExpandedId={setExpandedId}
                  currentId={`${item.id}-${index}`}
                  items={[
                    {
                      title: 'Typ akce',
                      value: item.type,
                    },
                    {
                      title: 'Kapacita',
                      value: item.capacity,
                    },
                    {
                      title: 'Pořadatel',
                      value: item.organization,
                    },
                    {
                      title: 'Vztah k akci',
                      value: item.relation,
                    },
                    {
                      title: `Přihlašování${item.loginFrom?.length ? ' začíná' : ''}`,
                      value: item.loginFrom
                        ? getDateAsString(new Date(item.loginFrom), true)
                        : 'Bez omezení',
                      dropdown: true,
                    },
                    ...(item.loginTo.length
                      ? [
                          {
                            title: 'Přihlašování končí',
                            value: getDateAsString(new Date(item.loginTo), true),
                            dropdown: true,
                          },
                        ]
                      : []),
                  ]}
                >
                  <View className="flex-1 flex-row justify-end pb-4 pr-3">
                    {item.participantEducation && item.hasApplicationAccess && (
                      <Button
                        classNames="py-1 pl-5"
                        variant="text"
                        onPress={() =>
                          navigation.navigate('EducationApplication', {
                            id: item.id,
                            educationName: item.displayName,
                          })
                        }
                      >
                        Moje přihláška
                      </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('EducationDetail', {
                          id: item.id,
                          educationName: item.displayName,
                          logo: item.logo,
                          reminderId: item.enrollId,
                          educationCourseId: item.educationCourseId,
                          hasNoAPiReminder: true,
                        });
                      }}
                    >
                      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={EDUC_EVENT_SORTING}
        selectedValue={sort}
        setSelectedValue={setSort}
        selectedDirection={sortDirection}
        setSelectedDirection={setSortDirection}
      />
      <EducationFilterModal
        isVisible={filterModalVisible}
        setIsVisible={setFilterModalVisible}
        organization={organization}
        setOrganization={setOrganization}
        year={year}
        setYear={setYear}
        isFuture={isFuture}
        setIsFuture={setIsFuture}
        relation={relation}
        setRelation={setRelation}
        type={type}
        setType={setType}
      />
    </View>
  );
};

export default Education;
