import { storage } from "@/configs/storage";
import { useColor } from "@/hooks/useColor";
import { useTranslations } from "@/providers/TranslationProviders";
import { secondToTime } from "@/utils/helper";
import { SpinnerGapIcon } from "phosphor-react-native";
import { useCallback, useEffect, useState } from "react";
import { Pressable, Text, View } from "react-native";

type OtpTimerProps = {
  onClick: () => void;
  loading?: boolean;
  time?: number; // in seconds
  otpTimerKey: string;
};

const OtpTimer = ({
  onClick,
  loading = false,
  time = 0,
  otpTimerKey,
}: OtpTimerProps) => {
  const { primary } = useColor();
  const { tran } = useTranslations();
  const [timer, setTimer] = useState<number>(time);

  // Initialize timer whenever `time` prop changes
  useEffect(() => {
    setTimer(time);
  }, [time]);

  // Countdown interval
  useEffect(() => {
    if (timer <= 0) return;

    const interval = setInterval(() => {
      setTimer((prev) => {
        if (prev <= 1) {
          clearInterval(interval);

          // Remove OTP timer from AsyncStorage
          (async () => {
            try {
              storage.remove(otpTimerKey);
            } catch (err) {
              console.error("Failed to remove OTP timer:", err);
            }
          })();

          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(interval);
  }, [timer, otpTimerKey]);

  const handleResend = useCallback(() => {
    if (loading) return;
    onClick();
    setTimer(time); // reset timer when resending
  }, [onClick, loading, time]);

  return (
    <View>
      {timer > 0 ? (
        <Text className="pt-4 text-center text-amber-600">
          {tran("Resend OTP in")} {secondToTime(timer)} {tran("seconds")}
        </Text>
      ) : (
        <View className="flex-row justify-center items-center pt-3">
          <Text className="text-slate-600 font-satoshi-medium">
            {tran("Didn't receive email?")}
          </Text>
          <Pressable
            className="ml-1 font-medium underline"
            onPress={handleResend}
            disabled={loading}
          >
            {loading ? (
              <View className="flex-row items-center justify-center">
                <SpinnerGapIcon />
                <Text className="ml-2">{tran("Loading...")}</Text>
              </View>
            ) : (
              <Text
                style={{
                  color: primary.base,
                }}
                className="font-satoshi-bold"
              >
                {tran("Resend")}
              </Text>
            )}
          </Pressable>
        </View>
      )}
    </View>
  );
};

export default OtpTimer;
