"use client";

import Link from "next/link";
import { useState, useEffect, useCallback, useRef } from "react";
import { useTranslation } from "@/hooks/useTranslation";
import { useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { loginWithEmail, loginWithOTP } from "@/store/slices/authSlice";
import { loginSchema } from "@/lib/validators/auth.validator";
import { isAuthenticatedClient } from "@/lib/utils/persistAuth";
import { useLocale } from "@/hooks/useLocale";
import type { ConfirmationResult, RecaptchaVerifier } from "firebase/auth";

type OtpStep = "idle" | "phone" | "otp";

const COUNTRY_MAP: Record<string, string> = {
  "+91": "India",
  "+1": "United States",
  "+44": "United Kingdom",
  "+971": "UAE",
};

export default function LoginPage() {
  const { locale } = useLocale();
  const { t } = useTranslation("auth");
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { isLoading } = useAppSelector((s) => s.auth);

  // Email login state
  const [showPw, setShowPw] = useState(false);
  const [keepSignedIn, setKeepSignedIn] = useState(true);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [emailError, setEmailError] = useState<string | null>(null);

  // OTP flow — confirmationResult never goes to Redux
  const [otpStep, setOtpStep] = useState<OtpStep>("idle");
  const [otpPhone, setOtpPhone] = useState("9898989898");
  const [otpCountryCode, setOtpCountryCode] = useState("+91");
  const [otpCode, setOtpCode] = useState("123456");
  const [otpLoading, setOtpLoading] = useState(false);
  const [otpError, setOtpError] = useState<string | null>(null);
  const confirmationRef = useRef<ConfirmationResult | null>(null);
  const recaptchaRef = useRef<RecaptchaVerifier | null>(null);

  // Redirect if already logged in
  useEffect(() => {
    if (isAuthenticatedClient()) {
      router.replace(`/home`);
    }
  }, [locale, router]);

  // --- Email submit ---
  const handleEmailSubmit = useCallback(
    async (e: React.SyntheticEvent) => {
      e.preventDefault();
      setEmailError(null);

      const parsed = loginSchema.safeParse({ email, password });
      if (!parsed.success) {
        setEmailError(parsed.error.issues[0].message);
        return;
      }

      const result = await dispatch(
        loginWithEmail({
          type: 4,
          email,
          password,
          full_name: "",
          image: "",
          country_code: "",
          mobile_number: "",
          country_name: "",
          device_type: 3,
          device_token: "",
        }),
      );

      if (loginWithEmail.fulfilled.match(result)) {
        router.push(`/home`);
      } else {
        setEmailError((result.payload as string) ?? "Login failed.");
      }
    },
    [email, password, dispatch, locale, router],
  );

  // --- OTP: send ---
  const handleSendOtp = useCallback(async () => {
    const digits = otpPhone.replace(/\D/g, "");
    if (digits.length < 7) {
      setOtpError("Please enter a valid phone number.");
      return;
    }
    setOtpError(null);
    setOtpLoading(true);

    try {
      const { RecaptchaVerifier, signInWithPhoneNumber } =
        await import("firebase/auth");
      const { firebaseAuth } = await import("@/lib/firebase");

      if (recaptchaRef.current) {
        recaptchaRef.current.clear();
        recaptchaRef.current = null;
      }

      recaptchaRef.current = new RecaptchaVerifier(
        firebaseAuth,
        "recaptcha-container",
        { size: "invisible" },
      );

      const fullPhone = `${otpCountryCode}${digits}`;
      confirmationRef.current = await signInWithPhoneNumber(
        firebaseAuth,
        fullPhone,
        recaptchaRef.current,
      );
      setOtpStep("otp");
    } catch (err) {
      setOtpError((err as Error)?.message ?? "Failed to send OTP.");
    } finally {
      setOtpLoading(false);
    }
  }, [otpPhone, otpCountryCode]);

  // --- OTP: verify ---
  const handleVerifyOtp = useCallback(async () => {
    if (otpCode.length !== 6) {
      setOtpError("Enter the 6-digit code.");
      return;
    }
    if (!confirmationRef.current) {
      setOtpError("Session expired. Please resend OTP.");
      return;
    }
    setOtpError(null);
    setOtpLoading(true);

    try {
      await confirmationRef.current.confirm(otpCode);

      const digits = otpPhone.replace(/\D/g, "");
      const result = await dispatch(
        loginWithOTP({
          type: 1,
          mobile_number: `${digits}`,
          country_code: otpCountryCode,
          country_name: COUNTRY_MAP[otpCountryCode] ?? otpCountryCode,
          email: "",
          password: "",
          full_name: "",
          image: "",
          device_type: 3,
          device_token: "",
        }),
      );

      if (loginWithOTP.fulfilled.match(result)) {
        router.push(`/home`);
      } else {
        setOtpError((result.payload as string) ?? "Verification failed.");
      }
    } catch (err) {
      const msg = (err as Error)?.message ?? "";
      setOtpError(
        msg.includes("invalid-verification-code")
          ? "Invalid OTP. Please try again."
          : msg || "Verification failed.",
      );
    } finally {
      setOtpLoading(false);
    }
  }, [otpCode, otpPhone, otpCountryCode, dispatch, locale, router]);

  const resetOtp = () => {
    setOtpStep("idle");
    setOtpPhone("");
    setOtpCode("");
    setOtpError(null);
    confirmationRef.current = null;
  };

  return (
    <main className="auth-shell">
      {/* ── Editorial art panel ── */}
      <aside className="auth-art">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src="https://images.unsplash.com/photo-1529107386315-e1a2ed48a620?w=1600&q=80"
          alt="DTNews editorial"
        />
        <div className="art-inner">
          <div className="top">
            <span className="badge-tag">TODAY&apos;S LEAD</span>
            <span className="credit">Photo · Vipin Kumar / DTNews</span>
          </div>
          <div>
            <div className="kicker">Why DTNews</div>
            <blockquote className="quote">
              News, told straight. Reported on the ground. Without the noise.
            </blockquote>
            <div className="byline">
              <span className="av">AV</span>
              <div className="meta">
                <b>Anjali Verma</b>
                <span className="role">Editor-in-Chief · since 2014</span>
              </div>
            </div>
            <div className="stats">
              <div className="stat">
                <div className="n">312</div>
                <div className="l">Journalists</div>
              </div>
              <div className="stat">
                <div className="n">14</div>
                <div className="l">Bureaus</div>
              </div>
              <div className="stat">
                <div className="n">1.8M</div>
                <div className="l">Subscribers</div>
              </div>
              <div className="stat">
                <div className="n">26M</div>
                <div className="l">Readers / mo</div>
              </div>
            </div>
          </div>
        </div>
      </aside>

      {/* ── Form panel ── */}
      <section className="auth-form-side">
        <div className="auth-form">
          <Link href={`/home`} className="auth-mini-logo">
            <span className="dt">DT</span>
            <span className="news">News</span>
            <span className="dot" />
          </Link>

          <div className="auth-eyebrow">{t("login.eyebrow")}</div>
          <h1 className="auth-h1">
            {t("login.h1_prefix")} <em>{t("login.h1_em")}</em>.
          </h1>
          <p className="auth-sub">
            {t("login.no_account")}{" "}
            <Link href={`/signup`}>{t("login.signup_link")}</Link>{" "}
            {t("login.sub_suffix")}
          </p>

          {/* Social SSO — Facebook replaced with Mobile OTP */}
          <div className="auth-social-row">
            <button className="auth-social-btn" type="button">
              <svg viewBox="0 0 24 24">
                <path
                  fill="#4285F4"
                  d="M22 12.1c0-.7-.1-1.4-.2-2H12v3.8h5.6c-.2 1.3-1 2.4-2.1 3.2v2.6h3.4c2-1.8 3.1-4.5 3.1-7.6z"
                />
                <path
                  fill="#34A853"
                  d="M12 22c2.7 0 5-.9 6.7-2.4l-3.4-2.6c-.9.6-2 1-3.3 1-2.5 0-4.7-1.7-5.5-4H3v2.6C4.7 19.7 8 22 12 22z"
                />
                <path
                  fill="#FBBC05"
                  d="M6.5 14c-.2-.6-.3-1.3-.3-2s.1-1.4.3-2V7.3H3C2.4 8.7 2 10.3 2 12s.4 3.3 1 4.7L6.5 14z"
                />
                <path
                  fill="#EA4335"
                  d="M12 6c1.4 0 2.7.5 3.7 1.4l2.8-2.8C16.9 3.1 14.7 2 12 2 8 2 4.7 4.3 3 7.3L6.5 10c.8-2.3 3-4 5.5-4z"
                />
              </svg>
              Google
            </button>
            <button className="auth-social-btn" type="button">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path d="M17.5 12.5a4.5 4.5 0 0 1 2.2-3.8 4.6 4.6 0 0 0-3.6-2c-1.5-.2-3 .9-3.8.9-.8 0-2-.9-3.3-.9A4.8 4.8 0 0 0 5 9c-1.7 3-.4 7.4 1.2 9.8.8 1.2 1.7 2.5 3 2.5s1.7-.8 3.3-.8 2 .8 3.3.8 2.3-1.2 3.1-2.4a10 10 0 0 0 1.4-2.9 4.4 4.4 0 0 1-2.8-3.5zM15 5.4A4.5 4.5 0 0 0 16 2a4.5 4.5 0 0 0-3 1.5 4.2 4.2 0 0 0-1 3.3 3.7 3.7 0 0 0 3-1.4z" />
              </svg>
              Apple
            </button>
            {/* Mobile OTP — replaces Facebook */}
            <button
              className="auth-social-btn"
              type="button"
              onClick={() => setOtpStep(otpStep === "idle" ? "phone" : "idle")}
            >
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <rect x="5" y="2" width="14" height="20" rx="2" />
                <circle
                  cx="12"
                  cy="18"
                  r="1"
                  fill="currentColor"
                  stroke="none"
                />
              </svg>
              Mobile
            </button>
          </div>

          {/* ── Inline OTP panel (appears below social row when active) ── */}
          {otpStep !== "idle" && (
            <div style={{ marginBottom: "20px" }}>
              {otpStep === "phone" ? (
                <>
                  <div className="auth-field" style={{ marginBottom: "12px" }}>
                    <div className="auth-field-label">
                      <span>
                        Mobile Number{" "}
                        <span className="req" style={{ color: "var(--brand)" }}>
                          *
                        </span>
                      </span>
                    </div>
                    <div className="phone-row">
                      <select
                        aria-label="Country code"
                        value={otpCountryCode}
                        onChange={(e) => setOtpCountryCode(e.target.value)}
                      >
                        <option value="+91">🇮🇳 +91</option>
                        <option value="+1">🇺🇸 +1</option>
                        <option value="+44">🇬🇧 +44</option>
                        <option value="+971">🇦🇪 +971</option>
                      </select>
                      <div className="auth-field-wrap">
                        <input
                          type="tel"
                          placeholder="Enter mobile number"
                          value={otpPhone}
                          onChange={(e) => {
                            setOtpError(null);
                            setOtpPhone(e.target.value);
                          }}
                          autoComplete="tel"
                        />
                      </div>
                    </div>
                  </div>
                  {otpError && (
                    <p
                      style={{
                        color: "var(--brand)",
                        fontSize: "13px",
                        marginBottom: "10px",
                        fontWeight: 500,
                      }}
                    >
                      {otpError}
                    </p>
                  )}
                  <div style={{ display: "flex", gap: "10px" }}>
                    <button
                      type="button"
                      className="auth-btn-primary"
                      style={{
                        flex: 1,
                        padding: "11px 16px",
                        fontSize: "14px",
                      }}
                      disabled={otpLoading}
                      onClick={handleSendOtp}
                    >
                      {otpLoading ? "Sending…" : "Send OTP"}
                    </button>
                    <button
                      type="button"
                      className="auth-social-btn"
                      style={{ flex: "0 0 auto", padding: "11px 14px" }}
                      onClick={resetOtp}
                    >
                      Cancel
                    </button>
                  </div>
                </>
              ) : (
                <>
                  <div className="auth-field" style={{ marginBottom: "12px" }}>
                    <div className="auth-field-label">
                      <span>
                        Enter OTP{" "}
                        <span className="req" style={{ color: "var(--brand)" }}>
                          *
                        </span>
                      </span>
                      <span
                        style={{
                          fontSize: "11.5px",
                          color: "var(--text-secondary)",
                        }}
                      >
                        Sent to {otpCountryCode} {otpPhone}
                      </span>
                    </div>
                    <div className="auth-field-wrap">
                      <span className="auth-field-ico">
                        <svg viewBox="0 0 24 24">
                          <rect x="5" y="11" width="14" height="10" rx="2" />
                          <path d="M8 11V7a4 4 0 0 1 8 0v4" />
                        </svg>
                      </span>
                      <input
                        type="text"
                        inputMode="numeric"
                        maxLength={6}
                        placeholder="6-digit code"
                        value={otpCode}
                        onChange={(e) => {
                          setOtpError(null);
                          setOtpCode(
                            e.target.value.replace(/\D/g, "").slice(0, 6),
                          );
                        }}
                        autoComplete="one-time-code"
                        style={{
                          letterSpacing: "0.25em",
                          fontFamily: "var(--font-geist-mono)",
                          fontSize: "18px",
                        }}
                      />
                    </div>
                  </div>
                  {otpError && (
                    <p
                      style={{
                        color: "var(--brand)",
                        fontSize: "13px",
                        marginBottom: "10px",
                        fontWeight: 500,
                      }}
                    >
                      {otpError}
                    </p>
                  )}
                  <div style={{ display: "flex", gap: "10px" }}>
                    <button
                      type="button"
                      className="auth-btn-primary"
                      style={{
                        flex: 1,
                        padding: "11px 16px",
                        fontSize: "14px",
                      }}
                      disabled={otpLoading || isLoading}
                      onClick={handleVerifyOtp}
                    >
                      {otpLoading || isLoading ? "Verifying…" : "Verify OTP"}
                    </button>
                    <button
                      type="button"
                      className="auth-social-btn"
                      style={{ flex: "0 0 auto", padding: "11px 14px" }}
                      onClick={() => {
                        setOtpStep("phone");
                        setOtpCode("");
                        setOtpError(null);
                      }}
                    >
                      Resend
                    </button>
                  </div>
                </>
              )}
            </div>
          )}

          {otpStep === "idle" && (
            <>
              <div className="auth-divider">
                <span className="ln" />
                <span>or with email</span>
                <span className="ln" />
              </div>

              <form onSubmit={handleEmailSubmit}>
                <div className="auth-field">
                  <div className="auth-field-label">
                    <span>
                      {t("login.email")}{" "}
                      <span className="req" style={{ color: "var(--brand)" }}>
                        *
                      </span>
                    </span>
                  </div>
                  <div className="auth-field-wrap">
                    <span className="auth-field-ico">
                      <svg viewBox="0 0 24 24">
                        <rect x="3" y="5" width="18" height="14" rx="2" />
                        <path d="M3 7l9 7 9-7" />
                      </svg>
                    </span>
                    <input
                      type="email"
                      placeholder={t("login.email_placeholder")}
                      autoComplete="email"
                      required
                      value={email}
                      onChange={(e) => {
                        setEmailError(null);
                        setEmail(e.target.value);
                      }}
                    />
                  </div>
                </div>

                <div className="auth-field">
                  <div className="auth-field-label">
                    <span>
                      {t("login.password")}{" "}
                      <span className="req" style={{ color: "var(--brand)" }}>
                        *
                      </span>
                    </span>
                    <a href="#" className="auth-link-r">
                      {t("login.forgot")}
                    </a>
                  </div>
                  <div className="auth-field-wrap auth-no-pad-right">
                    <span className="auth-field-ico">
                      <svg viewBox="0 0 24 24">
                        <rect x="5" y="11" width="14" height="10" rx="2" />
                        <path d="M8 11V7a4 4 0 0 1 8 0v4" />
                      </svg>
                    </span>
                    <input
                      type={showPw ? "text" : "password"}
                      placeholder={t("login.password_placeholder")}
                      autoComplete="current-password"
                      required
                      value={password}
                      onChange={(e) => {
                        setEmailError(null);
                        setPassword(e.target.value);
                      }}
                    />
                    <button
                      type="button"
                      className="auth-field-eye"
                      aria-label="Toggle password visibility"
                      onClick={() => setShowPw((v) => !v)}
                    >
                      {showPw ? (
                        <svg
                          width="18"
                          height="18"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        >
                          <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
                          <line x1="1" y1="1" x2="23" y2="23" />
                        </svg>
                      ) : (
                        <svg
                          width="18"
                          height="18"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        >
                          <circle cx="12" cy="12" r="3" />
                          <path d="M2 12s4-8 10-8 10 8 10 8-4 8-10 8S2 12 2 12z" />
                        </svg>
                      )}
                    </button>
                  </div>
                </div>

                <div className="auth-row-split">
                  <label className="auth-check">
                    <input
                      type="checkbox"
                      className="auth-check-box"
                      checked={keepSignedIn}
                      onChange={(e) => setKeepSignedIn(e.target.checked)}
                    />
                    <span>{t("login.keep_signed_in")}</span>
                  </label>
                </div>

                {emailError && (
                  <p
                    style={{
                      color: "var(--brand)",
                      fontSize: "13px",
                      marginBottom: "12px",
                      fontWeight: 500,
                    }}
                  >
                    {emailError}
                  </p>
                )}

                <button
                  type="submit"
                  className="auth-btn-primary"
                  disabled={isLoading}
                >
                  {isLoading ? "Signing in…" : t("login.submit")}
                  {!isLoading && (
                    <svg viewBox="0 0 24 24">
                      <path d="M5 12h14M13 6l6 6-6 6" />
                    </svg>
                  )}
                </button>

                <div className="auth-foot-link">
                  {t("login.no_account_cta")}{" "}
                  <Link href={`/signup`}>{t("login.signup_link_cta")}</Link>
                </div>

                <div className="trust-strip">
                  <span className="item">
                    <svg viewBox="0 0 24 24">
                      <rect x="5" y="11" width="14" height="10" rx="2" />
                      <path d="M8 11V7a4 4 0 0 1 8 0v4" />
                    </svg>
                    <b>Secure</b> — 256-bit TLS
                  </span>
                  <span className="item">
                    <svg viewBox="0 0 24 24">
                      <path d="M12 2L4 5v7c0 5 4 9 8 10 4-1 8-5 8-10V5z" />
                      <path d="M9 12l2 2 4-4" />
                    </svg>
                    <b>Sources</b> protected
                  </span>
                  <span className="item">
                    <svg viewBox="0 0 24 24">
                      <circle cx="12" cy="12" r="9" />
                      <path d="M9 12l2 2 4-4" />
                    </svg>
                    No password reuse
                  </span>
                </div>

                <p className="auth-policy">
                  By signing in you agree to DTNews&apos;s{" "}
                  <a href="#">Terms of Service</a> and{" "}
                  <a href="#">Privacy Policy</a>. We do not sell your data — see
                  our <a href="#">data charter</a>.
                </p>
              </form>
            </>
          )}
        </div>
      </section>

      {/* Invisible reCAPTCHA anchor required by Firebase Phone Auth */}
      <div id="recaptcha-container" />
    </main>
  );
}
