'use client';
import { useQuery } from '@tanstack/react-query';
import calendarAPi from 'api/calendar';
import LoadingScreen from 'components/LoadingScreen';
import Navbar from 'components/Navbar';
import Navigation from 'components/Navigation';
import { useCallback, useMemo, useState } from 'react';
import {
  RefreshControl,
  ScrollView,
  useWindowDimensions,
  View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import Pages from './Pages';
import PartyCarousel from './PartyCarousel';
import { HomeStyle } from './styled';
import Tabs from './Tabs';
import TabsAuto from './TabsAuto';
import TabsAvia from './TabsAvia';

const Home = () => {
  const [activeTab, setActiveTab] = useState<'avia' | 'auto'>('avia');
  const [refreshing, setRefreshing] = useState(false);
  const { width: screenWidth } = useWindowDimensions();
  const scale = screenWidth < 360 ? 0.85 : 1;
  const styles = useMemo(() => HomeStyle(scale), [scale]);

  const {
    data: autoData,
    isLoading: autoLoad,
    refetch: refetchAuto,
    isFetching: fetchAuto,
  } = useQuery({
    queryKey: ['calendar', 'AUTO'],
    queryFn: () => calendarAPi.getCalendar({ cargoType: 'AUTO' }),
  });

  const {
    data: aviaData,
    isLoading: aviaLoad,
    refetch: refetchAvia,
    isFetching: fetchAvia,
  } = useQuery({
    queryKey: ['calendarAvia', 'AVIA'],
    queryFn: () => calendarAPi.getCalendar({ cargoType: 'AVIA' }),
  });

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    try {
      await Promise.all([refetchAuto(), refetchAvia()]);
    } finally {
      setRefreshing(false);
    }
  }, [refetchAuto, refetchAvia]);

  const refreshControl = useMemo(
    () => <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />,
    [refreshing, onRefresh],
  );

  const activeTabContent = useMemo(() => {
    if (activeTab === 'auto') {
      return <TabsAuto />;
    } else if (activeTab === 'avia') {
      return <TabsAvia />;
    }
    return null;
  }, [activeTab]);

  if (autoLoad || aviaLoad || fetchAuto || fetchAvia) {
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={styles.container}>
          <Navbar />
          <LoadingScreen />
          <Navigation />
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={styles.container}>
        <Navbar />
        <ScrollView
          refreshControl={refreshControl}
          removeClippedSubviews={true}
          keyboardShouldPersistTaps="handled"
        >
          <PartyCarousel autoData={autoData} aviaData={aviaData} />
          <Tabs setActiveTab={setActiveTab} activeTab={activeTab} />
          {activeTabContent}
          <Pages />
        </ScrollView>
        <Navigation />
      </View>
    </SafeAreaView>
  );
};

export default Home;
