"use client";

import { useEffect, useLayoutEffect, useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import AnimatedSection from "@/components/AnimatedSection";
import { useToast } from "@/hooks/use-toast";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { verifyLogin } from "@/lib/api/auth";
import { getTranslation } from "@/src/hooks/useTranslation";
import { useLanguage } from "@/src/hooks/LanguageContext";
import { scrollWindowToTop } from "@/lib/commonFunctions";
import { parsePhoneNumberFromString } from "libphonenumber-js";
import { countryList } from "@/lib/api/countries";
import { Eye, EyeOff } from "lucide-react";
import {
  initializeGoogleSignIn,
  renderGoogleSignInButton,
  decodeGoogleToken,
} from "@/lib/googleAuth";
import { checkEmailExists } from "@/lib/api/apis";
import { notifyAuthChange } from "@/lib/authEvents";

type Country = (typeof countryList)[number];
export default function Login() {
  const { toast } = useToast();
  const router = useRouter();
  const [credentials, setCredentials] = useState({ mobile: "", password: "" });
  const [loading, setLoading] = useState(false);
  const [showDropdown, setShowDropdown] = useState(false);
  const [mounted, setMounted] = useState(false);
  const { language } = useLanguage();

  const [search, setSearch] = useState("");
  const [countries] = useState(countryList);
  const [selectedCountry, setSelectedCountry] = useState<Country | null>(null);

  const [mobileMaxLength, setMobileMaxLength] = useState(15);
  const [showPassword, setShowPassword] = useState(false);

  useEffect(() => {
    if (!selectedCountry) return;

    const testLengths = Array.from({ length: 15 }, (_, i) => i + 1);

    let max = 15;

    for (const len of testLengths) {
      const dummy = "9".repeat(len);

      const phone = parsePhoneNumberFromString(
        `${selectedCountry.code}${dummy}`,
      );

      if (phone?.isValid()) {
        max = len;
        break;
      }
    }

    setMobileMaxLength(max);
  }, [selectedCountry]);

  useLayoutEffect(() => {
    scrollWindowToTop();
  }, [mounted]);

  useEffect(() => {
    const india =
      countryList.find((c) => c.iso === "IN") ||
      countryList.find((c) => c.code === "+91");

    setSelectedCountry(india || countryList[0]);
  }, []);

  const filteredCountries = useMemo(() => {
    const q = search.toLowerCase().trim();

    if (!q) return countryList;

    return countryList
      .filter((c) => {
        return (
          c.name.toLowerCase().includes(q) ||
          c.iso.toLowerCase().includes(q) ||
          c.code.toLowerCase().includes(q)
        );
      })
      .sort((a, b) => {
        const aStarts = a.name.toLowerCase().startsWith(q) ? 0 : 1;
        const bStarts = b.name.toLowerCase().startsWith(q) ? 0 : 1;
        return aStarts - bStarts;
      });
  }, [search]);

  const handleGoogleSignInSuccess = async (token: string) => {
    try {
      setLoading(true);

      // Decode the token to get user info
      const googleUser = decodeGoogleToken(token);

      if (!googleUser) {
        toast({
          description: "Failed to process Google Sign-In. Please try again.",
          variant: "destructive",
        });
        return;
      }

      console.log("Google user decoded:", googleUser);

      // Check if email exists in the system
      console.log("Checking if email exists...");
      const emailCheckResponse = await checkEmailExists(googleUser.email);
      console.log("Email check response:", emailCheckResponse);

      if (!emailCheckResponse.status) {
        toast({
          description:
            emailCheckResponse.message ||
            "Email check failed. Please try again.",
          variant: "destructive",
        });
        return;
      }

      // Here you would typically send the token to your backend
      // The backend should verify the token with Google and create/login the user
      // For now, we'll store the user data locally as an example

      const userData = {
        id: googleUser.id,
        email: googleUser.email,
        name: googleUser.name,
        image: googleUser.image,
        google_signin: true,
        regist_status: 0, // Assuming new Google sign-ins need registration
        exists: emailCheckResponse.data?.exists || false,
      };

      // Store token and user data
      localStorage.setItem("token", token);
      localStorage.setItem("user_data", JSON.stringify(userData));
      localStorage.setItem("user_name", googleUser.name);

      // Let the header (and other listeners) update immediately
      notifyAuthChange();

      toast({
        description: "Google Sign-In successful! Redirecting...",
      });

      // Redirect after a short delay
      setTimeout(() => {
        const redirectTo = localStorage.getItem("redirectAfterAuth");
        if (redirectTo) {
          localStorage.removeItem("redirectAfterAuth");
          router.push(redirectTo);
        } else {
          window.location.replace("/");
        }
      }, 500);
    } catch (error: any) {
      console.error("Google Sign-In error:", error);
      toast({
        description:
          error.message || "Google Sign-In failed. Please try again.",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // Guard: if the user is already logged in, don't show the login page.
    // Redirect (replace, so it isn't kept in history) back to home.
    const token = localStorage.getItem("token");
    const storedUser = localStorage.getItem("user_data");
    if (token && storedUser) {
      router.replace("/");
      return;
    }

    setMounted(true);

    // Initialize Google Sign-In
    initializeGoogleSignIn();

    // Listen for Google Sign-In success
    const handleGoogleSignIn = (event: Event) => {
      const customEvent = event as CustomEvent;
      const token = customEvent.detail?.token;

      if (token) {
        handleGoogleSignInSuccess(token);
      }
    };

    window.addEventListener("googleSignInSuccess", handleGoogleSignIn);

    return () => {
      window.removeEventListener("googleSignInSuccess", handleGoogleSignIn);
    };
  }, []);

  // Render Google Sign-In button after mounted
  useEffect(() => {
    if (mounted) {
      setTimeout(() => {
        renderGoogleSignInButton("google_signin_button", "outline", "large");
      }, 100);
    }
  }, [mounted]);

  if (!mounted) return null;

  const t = getTranslation(language);

  const handleLogin = async () => {
    if (!credentials.mobile) {
      toast({
        // title: "Missing Information",
        description: "Please enter your mobile number.",
        variant: "destructive",
      });
      return;
    }

    if (!credentials.password) {
      toast({
        // title: "Missing Information",
        description: "Please enter your password.",
        variant: "destructive",
      });
      return;
    }

    if (!selectedCountry) {
      toast({
        // title: "Select Country",
        description: "Please select a country code.",
        variant: "destructive",
      });
      return;
    }

    const mobileOnlyDigits = credentials.mobile.replace(/\D/g, "");

    // ✅ build full international number: +91 + 9876543210
    const fullNumber = `${selectedCountry.code}${mobileOnlyDigits}`;

    const phone = parsePhoneNumberFromString(fullNumber);

    if (!phone || !phone.isValid()) {
      toast({
        // title: "Invalid Mobile Number",
        description: `Please enter a valid mobile number for ${selectedCountry.name}.`,
        variant: "destructive",
      });
      return;
    }

    // Indian numbers must start with 6-9
    if (selectedCountry.code === "+91" && !/^[6-9]/.test(mobileOnlyDigits)) {
      toast({
        description: "Indian mobile numbers must start with 6, 7, 8, or 9.",
        variant: "destructive",
      });
      return;
    }

    try {
      setLoading(true);

      // ✅ send full international number to API (best)
      const response = await verifyLogin(
        credentials.mobile,
        credentials.password,
        selectedCountry.code,
      );

      if (response?.status && response?.data) {
        const { jwt, name } = response.data;

        if (jwt) localStorage.setItem("token", jwt);

        localStorage.setItem("user_data", JSON.stringify(response.data));
        localStorage.setItem("user_name", name || "User");

        if (response?.data?.regist_status == 1) {
          localStorage.setItem(
            "register_details",
            JSON.stringify(response.data),
          );
        }

        // Let the header (and other listeners) update immediately
        notifyAuthChange();

        toast({
          // title: "Login Successful",
          description: response.message || "You have logged in successfully.",
        });
        console.log("datatatata", response);
        const redirectTo = localStorage.getItem("redirectAfterAuth");

        if (redirectTo && response?.data?.regist_status !== 1) {
          localStorage.removeItem("redirectAfterAuth");
          router.push(redirectTo);
        } else {
          window.location.replace("/");
        }
      } else {
        toast({
          // title: "Login Failed",
          description: response?.message || "Invalid credentials",
          variant: "destructive",
        });
      }
    } catch (error: any) {
      toast({
        // title: "Error",
        description: error.message || "Something went wrong.",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      onClick={() => setShowDropdown(false)}
      className="min-h-screen flex items-start justify-center p-4 pt-24 lg:h-screen lg:overflow-hidden lg:items-start"
    >
      <div className="w-full max-w-8xl bg-white rounded-l-3xl overflow-hidden lg:h-[80vh]">
        <div className="grid lg:grid-cols-2 lg:h-[80vh]">
          {/* LEFT SIDE - LOGIN FORM */}
          <div className="lg:overflow-y-auto lg:h-[80vh] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
            <div className="p-6 md:p-10 min-h-full flex items-center justify-center">
            <AnimatedSection className="w-full max-w-md">
              <Card className="border-0 border-[#fff] bg-white/80 backdrop-blur-sm">
                <CardHeader className="text-center space-y-6 pb-8">
                  <CardTitle className="text-2xl font-bold text-gray-900">
                    {t.login.title}
                  </CardTitle>
                </CardHeader>

                <CardContent className="space-y-8">
                  {/* Mobile Number Field */}
                  <div className="space-y-4">
                    <Label
                      htmlFor="mobile"
                      className="text-base font-semibold text-gray-700"
                    >
                      {t.login.mobileLabel}
                      <span className="text-red-500"> *</span>
                    </Label>

                    <div className="flex flex-row gap-2 sm:gap-3">
                      {/* Country Code Selector */}
                      <div className="relative w-[90px] sm:w-[140px] shrink-0">
                        <button
                          type="button"
                          // disabled={!selectedCountry}
                          className="flex items-center justify-between gap-1 sm:gap-3 px-2 sm:px-3 border-2 border-gray-300 rounded-md bg-gray-50 w-full h-12 disabled:opacity-50"
                          onClick={(e) => {
                            e.stopPropagation();
                            setShowDropdown((prev) => !prev);
                            setSearch("");
                          }}
                        >
                          <div className="flex items-center gap-1 sm:gap-2">
                            <span className="hidden sm:inline text-2xl leading-none">
                              {selectedCountry?.flag || "🌍"}
                            </span>
                            <span className="text-sm sm:text-base font-semibold text-gray-800">
                              {selectedCountry?.code || "--"}
                            </span>
                          </div>

                          <span className="text-gray-500 text-xl sm:text-2xl">▾</span>
                        </button>

                        {/* Dropdown */}
                        {showDropdown && (
                          <div className="absolute left-0 top-full mt-2 z-50 w-[calc(100vw-3rem)] sm:w-[320px] bg-white shadow-lg rounded-md border border-gray-200 overflow-hidden">
                            {/* Search */}
                            <div className="p-2 border-b border-gray-200 bg-white sticky top-0">
                              <input
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                placeholder="Search country..."
                                className="w-full h-10 px-3 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-[#FAA631] focus:border-[#FAA631]"
                                autoFocus
                              />
                            </div>

                            {/* List */}
                            <div className="max-h-56 overflow-y-auto">
                              {filteredCountries.length > 0 ? (
                                filteredCountries.map((item) => (
                                  <button
                                    key={`${item.iso}-${item.code}`}
                                    type="button"
                                    className="w-full flex items-center justify-between px-3 py-2 hover:bg-gray-100 transition"
                                    onClick={() => {
                                      setSelectedCountry(item);
                                      setShowDropdown(false);
                                      setSearch("");
                                    }}
                                  >
                                    <span className="text-sm">
                                      {item.flag} {item.name}
                                    </span>

                                    <span className="font-semibold">
                                      {item.code}
                                    </span>
                                  </button>
                                ))
                              ) : (
                                <div className="p-3 text-center text-gray-500">
                                  No country found
                                </div>
                              )}
                            </div>
                          </div>
                        )}
                      </div>

                      {/* Mobile Number Input */}
                      <Input
                        id="mobile"
                        name="mobile"
                        type="tel"
                        inputMode="numeric"
                        pattern="[0-9]*"
                        // maxLength={15}
                        value={credentials.mobile}
                        onChange={(e) => {
                          const digits = e.target.value
                            .replace(/\D/g, "")
                            .slice(0, mobileMaxLength);

                          setCredentials({
                            ...credentials,
                            mobile: digits,
                          });
                        }}
                        placeholder={t.login.mobilePlaceholder}
                        className="h-12 text-base border-2 border-gray-300 transition-colors flex-1 min-w-0"
                      />
                    </div>
                  </div>

                  {/* Password Field */}
                  <div className="space-y-4">
                    <Label
                      htmlFor="password"
                      className="text-base font-semibold text-gray-700"
                    >
                      {t.login.passwordLabel}
                      <span className="text-red-500"> *</span>
                    </Label>
                    <div className="relative">
                      <Input
                        id="password"
                        name="password"
                        type={showPassword ? "text" : "password"}
                        value={credentials.password}
                        onChange={(e) =>
                          setCredentials({
                            ...credentials,
                            password: e.target.value,
                          })
                        }
                        placeholder=""
                        className="h-12 text-base border-2 border-gray-300 transition-colors tracking-widest placeholder:tracking-widest pr-12"
                      />
                      <button
                        type="button"
                        onClick={() => setShowPassword(!showPassword)}
                        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700 transition-colors"
                        aria-label={
                          showPassword ? "Hide password" : "Show password"
                        }
                      >
                        {showPassword ? (
                          <EyeOff size={20} />
                        ) : (
                          <Eye size={20} />
                        )}
                      </button>
                    </div>

                    {/* Forgot Password Link */}
                    <div className="text-center">
                      <Link
                        href="/forgot-password"
                        className="text-sm font-semibold text-[#FAA631] transition-colors"
                      >
                        {t.login.forgotPassword}
                      </Link>
                    </div>
                  </div>
                  {/* Divider */}
                  <div className="relative">
                    <div className="absolute inset-0 flex items-center">
                      <span className="w-full border-t border-gray-300" />
                    </div>
                    <div className="relative flex justify-center text-sm">
                      <span className="px-2 bg-white text-gray-500">
                        or
                      </span>
                    </div>
                  </div>

                  {/* Google Sign-In Button */}
                  <div
                    id="google_signin_button"
                    className="flex justify-center"
                  />

                  {/* Continue Button */}
                  <Button
                    onClick={handleLogin}
                    disabled={loading}
                    className="w-full h-12 bg-[#FAA631]  hover:bg-orange-500 text-white text-base font-semibold shadow-lg hover:shadow-xl transition-all duration-300 disabled:opacity-60 disabled:cursor-not-allowed"
                  >
                    {loading ? t.login.continuing : t.login.continue}
                  </Button>

                  {/* Sign Up Link */}
                  <div className="text-center pt-4">
                    <p className="text-sm text-gray-600">
                      {t.login.noAccount}{" "}
                    </p>

                    <div className="mt-2 w-full">
                      <Button
                        asChild
                        variant="outline"
                        size="default"
                        className="w-full h-12 bg-[#FAA631]  hover:bg-orange-500 text-white text-base font-semibold shadow-lg hover:shadow-xl transition-all duration-300"
                      >
                        <Link href="/signup">{t.login.signUp}</Link>
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </AnimatedSection>
            </div>
          </div>

          {/* RIGHT SIDE - IMAGE */}
          <div className="hidden lg:flex items-center justify-center relative h-[80vh]">
            <img
              src="/images/courseQuiz.jpg"
              alt="Login"
              className="w-full h-full object-cover rounded-2xl"
            />

            {/* Optional Overlay Text */}
            {/* <div className="absolute bottom-10 text-white">
              <h3 className="text-2xl font-bold mb-3 text-center">
                Begin Your Gita Journey
              </h3>

              <p className="text-white/90">
                Learn timeless wisdom and participate in the Olympiad.
              </p>
            </div> */}
          </div>
        </div>
      </div>
    </div>
  );
}
