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 { SKAUTIS_EDU_EVENT_ENROLL_URL } from '../../../../constants/api';
import { FILTER_ALL } from '../../../../constants/custom';
import {
  EDUC_EVENT_SEARCH_SORTING,
  SORT_DIRECTION,
  SORT_DIRECTION_TAG,
  SORT_TAG,
} from '../../../../constants/sorting';
import { getDateAsString } from '../../../../helpers/stringHelpers';
import { useEducationGroups, useEducationTypes } from '../../../../hooks/useEducation';
import { useFilterButtons } from '../../../../hooks/useFilterButtons';
import { useSearchEducation } from '../../../../hooks/useSearchEducation';
import useSortList from '../../../../hooks/useSortList';
import { useUserInfo } from '../../../../hooks/useStorage';
import { EventEducationAllResponse } from '../../../../services/api/APIS/Events/types';
import { openURL } from '../../../../services/nativeHelpers/openURL';
import EducationFilterModal from './components/EducationFilterModal';

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

  const [name, setName] = useState('');
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [group, setGroup] = useState(FILTER_ALL);
  const [type, setType] = useState(FILTER_ALL);
  const [filterModalVisible, setFilterModalVisible] = useState(false);
  const [sortModalVisible, setSortModalVisible] = useState(false);

  useFilterButtons(setSortModalVisible, setFilterModalVisible);

  const [sort, setSort] = useState(EDUC_EVENT_SEARCH_SORTING[1].label);
  const [sortDirection, setSortDirection] = useState(SORT_DIRECTION[0].label);
  const [expandedId, setExpandedId] = useState('');

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

  const { list, isLoading: isListLoading } = useSearchEducation(
    userInfo?.token,
    name,
    year,
    groups?.find(item => item.displayName === group)?.id || '',
    types?.find(item => item.displayName === type)?.id || '',
  );

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

  const isLoading = isListLoading || isTypesLoading || isGroupsLoading;

  const enroll = async (item: EventEducationAllResponse) => {
    const skuatIsUrl = `${SKAUTIS_EDU_EVENT_ENROLL_URL}?ID_EventEducationCourse=${item.educationCourseId}&ID_EventEducation=${item.id}`;
    let url = !item.loginLocation.length || item.loginSkautis ? skuatIsUrl : item.loginLocation;
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      url = 'http://' + url;
    }
    await openURL(url);
  };

  const canEnroll = (item: EventEducationAllResponse) =>
    (item?.loginSkautis || item?.loginLocation.length) &&
    (!item?.loginTo.length || new Date(item?.loginTo) > new Date()) &&
    (!item?.loginFrom.length || new Date(item?.loginFrom) <= new Date());

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      <TagGroup
        items={[
          `${SORT_TAG} ${EDUC_EVENT_SEARCH_SORTING.find(s => s.label === sort)?.displayName ?? ''}`,
          `${SORT_DIRECTION_TAG} ${sortDirection}`,
          ...(name.length ? [`Název akce: ${name}`] : []),
          ...(year ? [`Rok: ${year}`] : []),
          ...(group !== FILTER_ALL ? [`Skupina: ${group}`] : []),
          ...(type !== FILTER_ALL ? [`Typ: ${type}`] : []),
        ]}
      />
      {!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}
                  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,
                    },
                    ...(item.loginTo.registrationDeadline
                      ? [
                          {
                            title: 'Uzávěrka přihlášek',
                            value: getDateAsString(new Date(item.registrationDeadline), true),
                          },
                        ]
                      : []),
                    {
                      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">
                    {canEnroll(item) && (
                      <Button classNames="py-1 pl-5" variant="text" onPress={() => enroll(item)}>
                        Přihlásit se
                      </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,
                        })
                      }
                    >
                      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_SEARCH_SORTING}
        selectedValue={sort}
        setSelectedValue={setSort}
        selectedDirection={sortDirection}
        setSelectedDirection={setSortDirection}
      />
      <EducationFilterModal
        isVisible={filterModalVisible}
        setIsVisible={setFilterModalVisible}
        name={name}
        setName={setName}
        year={year}
        setYear={setYear}
        group={group}
        setGroup={setGroup}
        type={type}
        setType={setType}
      />
    </View>
  );
};

export default SearchEducation;
