import React, { useCallback, useEffect, useState } from 'react';
import { FlatList, Text, TouchableOpacity } from 'react-native';
import moment from 'moment';

import { Header, PageWrapper, WarningModal } from 'src/components';
import RangeCalendar from 'src/components/Calendars/RangeCalendar';
import { TriumphItem } from '../Components/TriumphItem';

import { useGetTriumphsDates, useGetTriumphsData } from '@api/triumphs';
import { TriumphsData } from '../utils/types';
import { styles } from './styles';

import CalendarSvg from 'assets/icons/calendar-check.svg';
import { useConnection } from 'src/contexts/ConnectionContext';
import { StoreType, storage } from 'src/storage';
import { useNavigation } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';

const TriumphsScreen = () => {
  const navigation = useNavigation();
  const netInfo = useConnection();
  const token = storage.get('token', StoreType.STRING);
  const [selectedDate, setSelectedDate] = useState<string>(moment().format('YYYY-MM-DD'));
  const { data: dates, refetch } = useGetTriumphsDates(true);
  const { data } = useGetTriumphsData(selectedDate, true);
  const [isCalendarVisible, setIsCalendarVisible] = useState(false);
  const [modalType, setModalType] = useState<string | null>(null);

  useEffect(() => {
    if (dates) {
      setSelectedDate(dates.dates[dates.dates.length - 1]);
    }
  }, [dates]);

  useEffect(() => {
    refetch();
  }, [netInfo?.isInternetReachable]);

  const handlePress = useCallback(
    (userId: number) => {
      if (!netInfo?.isInternetReachable) {
        setModalType('offline');
      } else if (!token) {
        setModalType('unauthorized');
      } else {
        navigation.navigate(...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId }] as never));
      }
    },
    [netInfo?.isInternetReachable, token]
  );

  const renderItem = ({ item }: { item: TriumphsData }) => (
    <TriumphItem item={item} onPress={handlePress} />
  );

  return (
    <PageWrapper>
      <Header label="Triumphs" />
      <TouchableOpacity style={styles.dateBtn} onPress={() => setIsCalendarVisible(true)}>
        <CalendarSvg />
        <Text style={styles.dateText}>{moment(selectedDate).format('DD, MMMM YYYY')}</Text>
      </TouchableOpacity>
      {data && data.triumphs ? (
        <FlatList
          data={data.triumphs}
          renderItem={renderItem}
          keyExtractor={(item, index) => index.toString()}
          contentContainerStyle={styles.listContainer}
          showsVerticalScrollIndicator={false}
          maxToRenderPerBatch={30}
          initialNumToRender={30}
        />
      ) : null}
      <RangeCalendar
        isModalVisible={isCalendarVisible}
        closeModal={(startDate?: string | null, endDate?: string | null) => {
          startDate && setSelectedDate(startDate);
          setIsCalendarVisible(false);
        }}
        allowRangeSelection={false}
        highlightedDates={dates?.dates}
        selectedDate={selectedDate}
      />
      {modalType && (
        <WarningModal type={modalType} isVisible={true} onClose={() => setModalType(null)} />
      )}
    </PageWrapper>
  );
};

export default TriumphsScreen;
