import { authApi } from "../../apis/authApi";
import {
  startLoading,
  startSmallLoading,
  stopLoading,
  stopSmallLoading,
} from "../../features/loading/loadingSlice";
import { useAppDispatch, useAppSelector } from "../../hooks/useRedux";
import { useMutation } from "@tanstack/react-query";
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useEffect, useRef } from "react";
import { accountLogin } from "../../features/account/accuntSlice";
import logoApp from "../../assets/img/logo-skysim.png";
import { useTranslation } from "react-i18next";

const LoginView: React.FC = () => {
  const navigate = useNavigate();
  const loading = useAppSelector((state) => state.loading);
  const dispatch = useAppDispatch();
  const [email, setEmail] = useState("");
  const [step, setStep] = useState<"email" | "otp">("email");

  const [otp, setOtp] = useState("");
  const [timer, setTimer] = useState(120);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const [errorMessage, setErrorMessage] = useState("");
  const { t } = useTranslation();
  let interval;

  useEffect(() => {
    // Focus input on mount
    inputRef.current?.focus();
  }, []);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value.replace(/[^0-9]/g, "");
    if (val.length <= 6) {
      setOtp(val);
    }
  };

  const handleVerify = async (e: React.FormEvent) => {
    e.preventDefault();
    // Case 1: Timer expired -> Button acts as RESEND
    if (timer === 0) {
      handleResend();
      return;
    }
    if (otp.length !== 6) return;
    setErrorMessage("");
    verifyOtpMutation.mutate();
  };

  const resetTimer = (time: number) => {
    setTimer(time);

    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }

    intervalRef.current = setInterval(() => {
      setTimer((prev) => (prev > 0 ? prev - 1 : 0));
    }, 1000);
  };

  const handleResend = () => {
    setOtp("");
    resendOtpMutation.mutate();
  };

  const getOtpMutation = useMutation({
    mutationFn: async () => {
      dispatch(startSmallLoading());
      const res = await authApi.requestOtp({ email });
      return res;
    },
    onSuccess: (data) => {
      dispatch(stopSmallLoading());
      setErrorMessage("");
      console.log("Get otp response data:", data);
      if (data && data.errorCode === "0") {
        console.log("Get otp successful");
        // show otp step
        // Countdown timer
        setStep("otp");
        setErrorMessage("");
        resetTimer(data.data.expireInSeconds || 120);
      } else {
        console.error("Get otp failed, no token received");
        setErrorMessage(
          data?.message || "Failed to request OTP. Please try again.",
        );
      }
    },
    onError: (error: any) => {
      dispatch(stopSmallLoading());
      console.error("Get otp error:", error.response.data);
    },
  });

  const resendOtpMutation = useMutation({
    mutationFn: async () => {
      dispatch(startSmallLoading());
      const res = await authApi.resendOtp({ email });
      return res;
    },
    onSuccess: (data) => {
      dispatch(stopSmallLoading());
      setErrorMessage("");
      console.log("Resend otp response data:", data);
      if (data && data.errorCode === "0") {
        console.log("Resend otp successful");
        // Countdown timer
        setErrorMessage("");
        resetTimer(data.data.expireInSeconds || 120);
      } else {
        console.error("Resend otp failed, no token received");
        setErrorMessage(
          data?.message || "Failed to request OTP. Please try again.",
        );
      }
    },
    onError: (error: any) => {
      dispatch(stopSmallLoading());
      console.error("Get otp error:", error.response.data);
    },
  });

  const verifyOtpMutation = useMutation({
    mutationFn: async () => {
      dispatch(startSmallLoading());
      const res = await authApi.verifyOtp({ email, otp });
      return res;
    },
    onSuccess: (data) => {
      dispatch(stopSmallLoading());
      console.log("Verify otp response data:", data);
      if (data && data.errorCode === "0") {
        console.log("Verify otp successful " + data.data.accessToken);
        // save token to local storage
        dispatch(accountLogin(data.data));
        navigate("/");
      } else {
        console.error("Verify otp failed, no token received");
        setErrorMessage(
          data?.message || "Failed to verify OTP. Please try again.",
        );
      }
    },
    onError: (error: any) => {
      dispatch(stopSmallLoading());
      console.error("Verify otp error:", error.response.data);
    },
  });

  const handleGetOtp = (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage("");
    getOtpMutation.mutate();
  };

  const onGoogleLogin = async () => {
    dispatch(startLoading({ message: "Redirecting to Google..." }));
    try {
      const res = await authApi.googleLogin();
      if (res && res.errorCode === "0") {
        window.location.href = res.data.url;
      } else {
        console.error("Google login failed:", res);
        dispatch(stopLoading());
      }
    } catch (error) {
      console.error("Google login error:", error);
      dispatch(stopLoading());
    }
  };

  return (
    <div className="min-h-screen bg-white flex flex-col lg:flex-row overflow-hidden">
      <div className="w-full lg:w-1/2 flex flex-col justify-center items-center p-6 md:p-12 lg:p-20 relative z-10 bg-white">
        {/* <button
            onClick={() => navigate(-1)}
            className="absolute top-6 left-6 lg:hidden p-2 text-slate-400 hover:text-[#EE0434] transition-colors"
          >
            <svg
              className="w-6 h-6"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2.5}
                d="M15 19l-7-7 7-7"
              />
            </svg>
          </button> */}

        <div className="w-full max-w-[420px] space-y-10">
          <div className="space-y-4 text-center lg:text-left">
            <div className="lg:hidden flex justify-center mb-8">
              <div className="w-50 h-50 flex items-center justify-center">
                {/* <svg
                  className="w-10 h-10 text-white"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"
                    strokeWidth={2}
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg> */}
                <img src={logoApp} alt="SkySimHub Logo" />
              </div>
            </div>
            <h1 className="text-3xl md:text-4xl lg:text-5xl font-black text-slate-900 tracking-tight">
              {t("welcomeBack")}
            </h1>
            <p className="text-slate-400 font-medium text-base md:text-lg">
              {t("stayConnected")}
            </p>
          </div>
          {step === "email" && (
            <>
              <form className="space-y-8" onSubmit={handleGetOtp}>
                <div className="space-y-3">
                  <label className="block text-slate-500 font-black text-[10px] uppercase tracking-[0.2em] pl-1">
                    {t("emailAddress")}
                  </label>
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder={t("enterYourEmail")}
                    className="w-full bg-slate-50 border-2 border-transparent focus:border-[#EE0434]/20 rounded-2xl py-4 md:py-5 px-6 focus:outline-none focus:bg-white transition-all text-slate-700 font-semibold"
                  />
                </div>
                <div>
                  {errorMessage && (
                    <p className="text-red-500 text-sm font-medium text-base md:text-lg text-center lg:text-left mb-4">
                      {errorMessage}
                    </p>
                  )}
                </div>
                <button
                  type="submit"
                  disabled={loading.isSmallLoading}
                  className={`w-full py-4 md:py-5 rounded-2xl font-black text-xl md:text-2xl shadow-lg transition-all flex items-center justify-center space-x-3 ${
                    !loading.isSmallLoading
                      ? "bg-[#EE0434] text-white hover:scale-[1.01] active:scale-[0.98]"
                      : "bg-slate-100 text-slate-300 cursor-not-allowed"
                  }`}
                >
                  {loading.isSmallLoading && (
                    <div className="w-5 h-5 border-3 border-white/30 border-t-red-500 rounded-full animate-spin"></div>
                  )}
                  <span>{t("login")}</span>
                </button>
              </form>
              <div className="space-y-6">
                <div className="relative">
                  <div className="absolute inset-0 flex items-center">
                    <div className="w-full border-t border-slate-100"></div>
                  </div>
                  <div className="relative flex justify-center text-sm">
                    <span className="px-4 bg-white text-slate-400 font-bold uppercase tracking-wider text-[10px]">
                      {t("orContinueWith")}
                    </span>
                  </div>
                </div>

                <button
                  type="button"
                  onClick={onGoogleLogin}
                  className="w-full bg-white border border-slate-200 text-slate-700 py-4 md:py-5 rounded-2xl font-bold text-lg md:text-xl shadow-sm hover:bg-slate-50 hover:border-slate-300 transition-all flex items-center justify-center space-x-3 active:scale-[0.98]"
                >
                  <svg className="w-6 h-6" viewBox="0 0 24 24">
                    <path
                      d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
                      fill="#4285F4"
                    />
                    <path
                      d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
                      fill="#34A853"
                    />
                    <path
                      d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
                      fill="#FBBC05"
                    />
                    <path
                      d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
                      fill="#EA4335"
                    />
                  </svg>
                  <span>Google</span>
                </button>
              </div>
            </>
          )}
          {step === "otp" && (
            <>
              {" "}
              {timer === 0 && step === "otp" && (
                <button
                  onClick={() => setStep("email")}
                  className="absolute top-6 left-6 p-2 text-slate-400 hover:text-[#EE0434] transition-colors"
                >
                  <svg
                    className="w-6 h-6"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2.5}
                      d="M15 19l-7-7 7-7"
                    />
                  </svg>
                </button>
              )}
              <div className="w-full max-w-[420px] space-y-10">
                <div className="space-y-4 text-center lg:text-left">
                  <h1 className="text-3xl md:text-4xl lg:text-5xl font-black text-slate-900 tracking-tight">
                    {t("checkYourEmail")}
                  </h1>
                  <p className="text-slate-400 font-medium text-base md:text-lg">
                    {t("weveSentVerificationCode")} <br />
                    <span className="text-slate-800 font-bold">{email}</span>
                  </p>
                </div>

                <form className="space-y-8" onSubmit={handleVerify}>
                  <div className="space-y-4">
                    <label className="block text-slate-500 font-black text-[10px] uppercase tracking-[0.2em] pl-1">
                      {t("verificationCode")}
                    </label>

                    <div
                      className="relative h-16 md:h-20 w-full"
                      onClick={() => timer > 0 && inputRef.current?.focus()}
                    >
                      {/* Visual Boxes */}
                      <div
                        className={`absolute inset-0 flex justify-between gap-2 md:gap-4 pointer-events-none ${
                          timer === 0 ? "opacity-50" : "opacity-100"
                        }`}
                      >
                        {[...Array(6)].map((_, idx) => (
                          <div
                            key={idx}
                            className={`flex-1 rounded-xl md:rounded-2xl border-2 flex items-center justify-center text-2xl md:text-3xl font-black transition-all ${
                              otp.length === idx && timer > 0
                                ? "border-[#EE0434] bg-white shadow-lg ring-4 ring-red-50"
                                : otp.length > idx
                                  ? "border-[#EE0434] bg-red-50 text-[#EE0434]"
                                  : "border-slate-100 bg-slate-50 text-slate-300"
                            }`}
                          >
                            {otp[idx] || ""}
                          </div>
                        ))}
                      </div>

                      {/* Hidden Input */}
                      <input
                        ref={inputRef}
                        type="text"
                        inputMode="numeric"
                        autoComplete="one-time-code"
                        value={otp}
                        onChange={handleChange}
                        disabled={timer === 0}
                        className="absolute inset-0 w-full h-full opacity-0 cursor-text disabled:cursor-not-allowed"
                        maxLength={6}
                      />
                    </div>
                  </div>
                  <div>
                    {errorMessage && (
                      <p className="text-red-500 text-sm font-medium text-base md:text-lg text-center lg:text-left mb-4">
                        {errorMessage}
                      </p>
                    )}
                  </div>
                  <button
                    type="submit"
                    // Disabled if: (Timer active AND (otp not full OR verifying))
                    disabled={
                      (timer > 0 && otp.length !== 6) || loading.isSmallLoading
                    }
                    className={`w-full py-4 md:py-5 rounded-2xl font-black text-xl md:text-2xl shadow-lg transition-all flex items-center justify-center space-x-3 ${
                      timer === 0 ||
                      (otp.length === 6 && !loading.isSmallLoading)
                        ? "bg-[#EE0434] text-white hover:scale-[1.01] active:scale-[0.98]"
                        : "bg-slate-100 text-slate-300 cursor-not-allowed"
                    }`}
                  >
                    {loading.isSmallLoading && (
                      <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
                    )}
                    <span>{timer === 0 ? "Resend OTP" : "Verify"}</span>
                  </button>
                </form>

                <div className="text-center">
                  {timer > 0 ? (
                    <p className="text-slate-500 font-medium">
                      {t("codeExpiresIn")}{" "}
                      <span className="text-slate-900 font-bold">{timer}s</span>
                    </p>
                  ) : (
                    <p className="text-[#EE0434] font-medium animate-pulse">
                      {t("codeExpiredPleaseRequestNewOne")}
                    </p>
                  )}
                </div>
              </div>{" "}
            </>
          )}
        </div>
      </div>
      <div className="hidden lg:flex w-1/2 bg-gradient-to-br from-[#EE0434] to-[#80001a] items-center justify-center relative overflow-hidden">
        <div className="relative z-10 text-white text-center space-y-4">
          <h2 className="text-5xl font-black">{t("fastSimpleRed")}</h2>
          <p className="text-xl opacity-80">
            {t("globalConnectivityForTheModernTraveler")}
          </p>
        </div>
      </div>
    </div>
  );
};

export default LoginView;
