import React, { useRef, useState, useEffect } from "react";
import { View, ActivityIndicator } from "react-native";
import ScreenWrapper from "~/components/ui/ScreenWrapper";
import { Text } from "~/components/ui/text";
import { Button } from "~/components/ui/button";
import LottieView from "lottie-react-native";
import * as Network from "expo-network";
import { router } from "expo-router";
import { HOME } from "~/lib/routes";
import ModalToast from "~/components/ui/toast";

export default function NoInternetScreen() {
  const [checking, setChecking] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [toastVisible, setToastVisible] = useState(false);
  const [toastTitle, setToastTitle] = useState("Can't connect to network");
  const [toastDescription, setToastDescription] = useState<string | undefined>(
    undefined
  );
  const [toastVariant, setToastVariant] = useState<
    "success" | "error" | "warning" | "info"
  >("error");
  const toastTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const showToast = () => {
    if (toastTimeoutRef.current) {
      clearTimeout(toastTimeoutRef.current);
    }

    setToastTitle("Can't connect to network");
    setToastDescription(undefined);
    setToastVariant("error");
    setToastVisible(true);

    toastTimeoutRef.current = setTimeout(() => {
      setToastVisible(false);
      toastTimeoutRef.current = null;
    }, 2500);
  };

  useEffect(() => {
    return () => {
      if (toastTimeoutRef.current) {
        clearTimeout(toastTimeoutRef.current);
      }
    };
  }, []);

  const handleRetry = async () => {
    setChecking(true);
    setError(null);
    try {
      const state = await Network.getNetworkStateAsync();
      const isOffline =
        !state.isConnected || state.isInternetReachable === false;

      if (!isOffline) {
        router.replace(HOME);
      } else {
        setError("Still offline. Please check your connection.");
        showToast();
      }
    } catch (e) {
      setError("Unable to check connection. Please try again.");
      showToast();
    } finally {
      setChecking(false);
    }
  };

  return (
    <ScreenWrapper edges={[]}>
      <View className="flex-1 bg-white items-center justify-center px-8">
        <LottieView
          source={require("../assets/lottie/NoInternet.json")}
          autoPlay
          loop
          style={{ width: 260, height: 260, marginBottom: 24 }}
        />

        <Text className="text-2xl font-dmsans-bold text-[#105D38] mb-3">
          No Internet
        </Text>

        <Text className="text-base font-dmsans text-gray-500 text-center mb-6">
          Please reconnect the application to the internet.
        </Text>

        <Button
          className="bg-primary w-full  px-6 h-11 flex-row items-center justify-center"
          onPress={handleRetry}
          disabled={checking}
        >
          {checking ? (
            <ActivityIndicator size="small" color="#FFFFFF" />
          ) : (
            <Text className="font-dmsans text-white">Retry</Text>
          )}
        </Button>
      </View>
      <ModalToast
        visible={toastVisible}
        title={toastTitle}
        description={toastDescription}
        variant={toastVariant}
      />
    </ScreenWrapper>
  );
}
