'use client';
import { useQuery } from '@tanstack/react-query';
import calendarAPi from 'api/calendar';
import Layout from 'components/Layout';
import LoadingScreen from 'components/LoadingScreen';
import { useCallback, useMemo, useState } from 'react';
import { RefreshControl, ScrollView, useWindowDimensions } from 'react-native';
import Pages from './Pages';
import PartyCarousel from './PartyCarousel';
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 {
    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 (
      <Layout>
        <LoadingScreen />
      </Layout>
    );
  }

  return (
    <Layout>
      <ScrollView
        refreshControl={refreshControl}
        removeClippedSubviews={true}
        keyboardShouldPersistTaps="handled"
      >
        <PartyCarousel
          autoData={autoData}
          aviaData={aviaData}
          activeTab={activeTab}
        />
        <Tabs setActiveTab={setActiveTab} activeTab={activeTab} />
        {activeTabContent}
        <Pages />
      </ScrollView>
    </Layout>
  );
};

export default Home;
