import React, { useState } from "react";
import { ScrollView, RefreshControl, View } from "react-native";
import { useAtom } from "jotai";
import CalendarPage from "@/components/pages/calendar/CalendarPage";
import { refreshTriggerAtom } from "@/components/pages/calendar/atoms";
import { colorMap } from "@/constants/colorMap";
import TabletCalendarPage from "@/components/pages/(tablet_pages)/calendar/TabletCalendarPage";
import { DeviceType } from "expo-device";
import * as Device from "expo-device";
import { useCalSync } from "@/hooks/useCalSync";
import Toast from "react-native-toast-message";

export default function Screen() {
  const [refreshing, setRefreshing] = useState(false);
  const [shouldRefresh, setShouldRefresh] = useAtom(refreshTriggerAtom);

  const isTablet: boolean = Device.deviceType === DeviceType.TABLET;

  const {
    isConnectedToGoogle,
    isConnectedToMicrosoft,
    isConnectedToApple,
    resyncAllCalendars,
    isSyncing,
  } = useCalSync();

  const onRefresh = React.useCallback(async () => {
    setRefreshing(true);

    const minimumDelay = new Promise((resolve) => setTimeout(resolve, 1000));

    try {
      if (isConnectedToGoogle || isConnectedToMicrosoft || isConnectedToApple) {
        await Promise.all([resyncAllCalendars(), minimumDelay]);
      } else {
        await minimumDelay;
      }
    } catch (error) {
      console.error("Refresh failed:", error);
    } finally {
      setRefreshing(false);
      setShouldRefresh((prev) => !prev);
    }
  }, [
    resyncAllCalendars,
    isConnectedToGoogle,
    isConnectedToMicrosoft,
    isConnectedToApple,
  ]);

  return (
    <View style={{ flex: 1 }}>
      <View style={{ flex: 1, zIndex: 0 }}>
        {Device.deviceType === DeviceType.TABLET ? (
          <TabletCalendarPage />
        ) : (
          <CalendarPage />
        )}
      </View>

      <ScrollView
        style={{
          position: "absolute",
          top: 0,
          left: isTablet ? "15%" : "0",
          height: isTablet ? "9%" : "4%",
          width: isTablet ? "62%" : "100%",
          zIndex: 50,
          backgroundColor: "transparent",
        }}
        contentContainerStyle={{
          flex: 1,
          justifyContent: "center",
          paddingRight: 200,
        }}
        refreshControl={
          <RefreshControl
            colors={[
              colorMap.pink,
              colorMap.green,
              colorMap.orange,
              colorMap.purple,
              colorMap.teal,
            ]}
            tintColor={colorMap.pink}
            progressBackgroundColor={"white"}
            refreshing={refreshing || isSyncing}
            onRefresh={onRefresh}
            style={{
              position: "absolute",
              left: "50%", // Position at screen center
              transform: [
                // Offset by half its own width
                { translateX: -20 }, // Assuming the refresh control is ~40px wide
              ],
            }}
          />
        }
        bounces={true}
        showsVerticalScrollIndicator={false}
        pointerEvents={refreshing || isSyncing ? "auto" : "none"}
      />
    </View>
  );
}
