import React, { useState, useEffect, useRef } from "react";
import {
  View,
  Keyboard,
  Platform,
  Image,
  TouchableOpacity,
  KeyboardAvoidingView,
  TouchableWithoutFeedback,
} from "react-native";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import { Text } from "~/components/ui/text";
import { router } from "expo-router";
import { usePhoneAuth } from "~/lib/hooks/useAuth";
import { ROUTES } from "~/lib/routes";
import { Icons } from "~/assets/icons";
import { AmbapayIcon, GoogleIcon } from "~/components/ui/icons";
import { useGlobalLoading } from "~/lib/hooks/useGlobalLoading";
import { AuthService } from "~/lib/services/authServices";
import ModalToast from "~/components/ui/toast";
import ScreenWrapper from "~/components/ui/ScreenWrapper";
import { useLangStore } from "~/lib/stores";
import { useTranslation } from "react-i18next";
import { ChevronDown } from "lucide-react-native";
import CountryPicker, {
  Country,
  CountryCode,
} from "react-native-country-picker-modal";

export default function Signin() {
  const [phoneNumber, setPhoneNumber] = useState("");
  const [countryCode, setCountryCode] = useState<CountryCode>("ET");
  const [selectedCountryCode, setSelectedCountryCode] = useState("+251");
  const [isCountryPickerVisible, setIsCountryPickerVisible] = useState(false);
  const { t } = useTranslation();
  const language = useLangStore((state) => state.language);
  const setLanguage = useLangStore((state) => state.setLanguage);
  const [googleLoading, setGoogleLoading] = useState(false);
  const {
    sendOTP,
    loading: phoneLoading,
    error: phoneError,
    confirmationResult,
  } = usePhoneAuth();
  const { withLoading } = useGlobalLoading();

  // Phone auth availability - reCAPTCHA not set up for web yet
  const isPhoneAuthAvailable = Platform.OS !== "web";

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

  const showToast = (
    title: string,
    description?: string,
    variant: "success" | "error" | "warning" | "info" = "info"
  ) => {
    if (toastTimeoutRef.current) {
      clearTimeout(toastTimeoutRef.current);
    }

    setToastTitle(title);
    setToastDescription(description);
    setToastVariant(variant);
    setToastVisible(true);

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

  const handlePhoneChange = (text: string) => {
    setPhoneNumber(text);
  };

  const handlePhoneSignIn = async () => {
    Keyboard.dismiss();

    if (!phoneNumber.trim()) {
      showToast("Error", "Please enter a phone number", "warning");
      return;
    }

    // Phone auth not available on web without reCAPTCHA setup
    if (Platform.OS === "web") {
      showToast(
        "Phone Auth Unavailable",
        "Phone authentication is not available on web. Please use Google Sign-In instead.",
        "warning"
      );
      return;
    }

    const fullPhoneNumber = phoneNumber.startsWith("+")
      ? phoneNumber
      : `${selectedCountryCode}${phoneNumber}`;

    // Dev-only shortcut: on emulator/dev builds, skip Firebase phone auth entirely
    if (__DEV__) {
      console.log(
        "DEV phone auth bypass: skipping sendOTP and navigating directly to OTP screen"
      );
      router.push(ROUTES.OTP);
      return;
    }

    try {
      await withLoading(() => sendOTP(fullPhoneNumber));
      console.log("REACHED HERE AFTER SEND OTP");
    } catch (error) {
      console.error("Phone sign in error:", error);
      showToast(
        t("signin.toastErrorTitle"),
        t("signin.toastOtpFailed"),
        "error"
      );
    }
  };

  const handleGoogleSignIn = async () => {
    setGoogleLoading(true);
    try {
      const result = await withLoading(() => AuthService.signInWithGoogle());

      if (result.error) {
        showToast("Google Sign-In Error", result.error, "error");
        return;
      }

      if (result.user) {
        // Check if user has a profile
        const hasProfile = await AuthService.checkUserProfileExists(
          result.user.uid
        );

        if (hasProfile) {
          // Existing user - go to home
          router.replace(ROUTES.HOME);
        } else {
          // New user - go to setup page
          router.replace(ROUTES.GOOGLE_SETUP);
        }
      }
    } catch (error) {
      console.error("Google sign in error:", error);
      showToast("Error", "Failed to sign in with Google.", "error");
    } finally {
      setGoogleLoading(false);
    }
  };

  // Navigate to OTP page when confirmationResult is available
  useEffect(() => {
    if (confirmationResult) {
      console.log("VERIFICATION STARTED, navigating to OTP");
      router.push(ROUTES.OTP);
    }
  }, [confirmationResult]);

  useEffect(() => {
    if (phoneError) {
      console.log(phoneError);
      showToast(t("signin.toastAuthErrorTitle"), phoneError, "error");
    }
  }, [phoneError]);

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

  return (
    <ScreenWrapper edges={[]}>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        className="flex-1"
        keyboardVerticalOffset={Platform.OS === "ios" ? 10 : 0}
      >
        <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
          <View className="flex-1 justify-between">
            <View className="items-center">
              <View className="flex flex-col space-y-6 items-center mb-10 mt-10">
                <Image
                  source={Icons.mainAmbapayLogo}
                  style={{ width: 96, height: 96 }}
                  resizeMode="contain"
                />
                <View className="flex flex-row space-x-1 pt-10 items-center">
                  <Text className="text-[30px] font-dmsans-extrabold text-primary">
                    amba
                  </Text>
                  <Text className="text-[30px] font-dmsans-extrabold text-secondary">
                    pay
                  </Text>
                </View>
              </View>

              <View className="w-full px-5 space-y-3">
                {/* Phone Sign-In - Only show on native */}
                {isPhoneAuthAvailable && (
                  <>
                    <Label className="text-base font-dmsans-medium">
                      {t("signin.phoneLabel")}
                    </Label>
                    <View className="h-2" />
                    <Input
                      placeholder={t("signin.phonePlaceholder")}
                      value={phoneNumber}
                      onChangeText={handlePhoneChange}
                      keyboardType="phone-pad"
                      containerClassName="w-full "
                      borderClassName="border-[#D9DBE9] bg-white"
                      placeholderColor="#7E7E7E"
                      textClassName="text-[#000] pt-3 text-sm"
                      leftIcon={
                        <TouchableOpacity
                          className="flex-row items-center pr-1"
                          onPress={() => setIsCountryPickerVisible(true)}
                        >
                          <Text className="text-[#000] text-sm mr-1">
                            {selectedCountryCode}
                          </Text>
                          <ChevronDown size={14} color="#000" />
                        </TouchableOpacity>
                      }
                    />
                  </>
                )}

                {/* Web-specific message */}
                {Platform.OS === "web" && (
                  <Text className="text-gray-600 font-dmsans text-center mb-4">
                    Sign in with your Google account to continue
                  </Text>
                )}
              </View>
            </View>

            <View className={`w-full px-5 pb-6`}>
              {/* Phone Sign-In Button - Only show on native */}
              {isPhoneAuthAvailable && (
                <>
                  <Button
                    className="bg-primary rounded-[8px] w-full"
                    onPress={handlePhoneSignIn}
                    disabled={
                      phoneLoading || googleLoading || !phoneNumber.trim()
                    }
                  >
                    <Text className="font-dmsans text-white text-sm">
                      {phoneLoading
                        ? t("signin.buttonLoading")
                        : t("signin.button")}
                    </Text>
                  </Button>

                  {/* Divider */}
                  <View className="flex-row justify-center items-center my-4">
                    <Text className="mx-4 text-gray-500 font-dmsans">OR</Text>
                  </View>
                </>
              )}

              {/* Google Sign-In Button */}
              <Button
                className="bg-white border border-gray-300 rounded-[8px] w-full"
                onPress={handleGoogleSignIn}
                disabled={phoneLoading || googleLoading}
              >
                <View className="flex-row items-center gap-2">
                  <GoogleIcon />
                  <Text className="font-dmsans text-gray-700">
                    {googleLoading ? "Signing in..." : "Sign in with Google"}
                  </Text>
                </View>
              </Button>

              {/* reCAPTCHA container for web phone auth (hidden, for future use) */}
              {Platform.OS === "web" && (
                <View
                  nativeID="recaptcha-container"
                  style={{ display: "none" }}
                />
              )}
            </View>
          </View>
        </TouchableWithoutFeedback>
      </KeyboardAvoidingView>

      <CountryPicker
        countryCode={countryCode}
        withFilter
        withFlag
        withEmoji
        withCallingCode
        withFlagButton={false}
        visible={isCountryPickerVisible}
        onClose={() => setIsCountryPickerVisible(false)}
        onSelect={(country: Country) => {
          setCountryCode(country.cca2 as CountryCode);
          const code =
            country.callingCode && country.callingCode.length > 0
              ? country.callingCode[0]
              : "251";
          setSelectedCountryCode(`+${code}`);
          setIsCountryPickerVisible(false);
        }}
      />

      <ModalToast
        visible={toastVisible}
        title={toastTitle}
        description={toastDescription}
        variant={toastVariant}
      />
    </ScreenWrapper>
  );
}
