"use client";

import Image from "next/image";
import Link from "next/link";
import { useState, useRef, Suspense, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { LanguageToggle } from "@/components/language-toggle";
import { useLanguage } from "@/lib/i18n-context";

function VerifyContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const email = searchParams.get("email") || "";
  const { t } = useLanguage();
  const v = t.auth.verify;

  const [otp, setOtp] = useState(["", "", "", "", "", ""]);
  const [loading, setLoading] = useState(false);
  const [resending, setResending] = useState(false);
  const [error, setError] = useState("");
  const [errorStep, setErrorStep] = useState("");
  const [success, setSuccess] = useState("");
  const [countdown, setCountdown] = useState(0);

  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);

  useEffect(() => {
    inputRefs.current[0]?.focus();
  }, []);

  useEffect(() => {
    if (countdown <= 0) return;
    const timer = setTimeout(() => setCountdown((c) => c - 1), 1000);
    return () => clearTimeout(timer);
  }, [countdown]);

  function handleOtpChange(index: number, value: string) {
    if (!/^\d*$/.test(value)) return;
    const newOtp = [...otp];
    newOtp[index] = value.slice(-1);
    setOtp(newOtp);
    if (value && index < 5) {
      inputRefs.current[index + 1]?.focus();
    }
  }

  function handleKeyDown(index: number, e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Backspace" && !otp[index] && index > 0) {
      inputRefs.current[index - 1]?.focus();
    }
  }

  function handlePaste(e: React.ClipboardEvent) {
    e.preventDefault();
    const pasted = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, 6);
    if (!pasted) return;
    const newOtp = [...otp];
    pasted.split("").forEach((char, i) => { if (i < 6) newOtp[i] = char; });
    setOtp(newOtp);
    const nextIndex = Math.min(pasted.length, 5);
    inputRefs.current[nextIndex]?.focus();
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setErrorStep("");
    const otpCode = otp.join("");

    if (otpCode.length < 6) {
      setError(v.otpTooShort);
      return;
    }

    const rawData = sessionStorage.getItem("registerData");
    if (!rawData) {
      setError(v.noData);
      return;
    }

    const { role } = JSON.parse(rawData);
    setLoading(true);

    try {
      const res = await fetch("/api/auth/verify-otp", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, otp: otpCode }),
      });

      const data = await res.json();

      if (!res.ok) {
        const backendMessage = data?.error || data?.responseDesc || data?.message || v.verifyFail;
        setError(backendMessage);
        setErrorStep(data?.step || "");
        return;
      }

      const parsedData = JSON.parse(rawData);

      if (role === "seller") {
        const registerData = { ...parsedData, email, otpVerified: true };

        const registerRes = await fetch("/api/auth/finalize-register", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ role: "seller", registerData }),
        });

        const registerResult = await registerRes.json();

        if (!registerRes.ok) {
          setError(registerResult?.error || v.registerFail);
          setErrorStep(registerResult?.step || "");
          return;
        }

        if (registerResult?.token) {
          sessionStorage.setItem("token", registerResult.token);
          sessionStorage.setItem("role", "seller");
        }

        sessionStorage.removeItem("registerData");
        sessionStorage.removeItem("otpVerified");
        sessionStorage.removeItem("otpVerifiedEmail");
        setSuccess(v.successSeller);
        setTimeout(() => { router.push("/dashboard"); }, 1000);
        return;
      }

      sessionStorage.setItem("registerData", JSON.stringify({ ...parsedData, email, otpVerified: true }));
      sessionStorage.setItem("otpVerified", "true");
      sessionStorage.setItem("otpVerifiedEmail", email);
      setSuccess(v.successBuyer);
      setTimeout(() => { router.push("/register/complete"); }, 1000);
    } catch {
      setError(t.common.connectionError);
    } finally {
      setLoading(false);
    }
  }

  async function handleResend() {
    if (countdown > 0) return;
    setError("");
    setErrorStep("");
    setResending(true);

    try {
      const res = await fetch("/api/auth/send-otp", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });

      if (res.ok) {
        setOtp(["", "", "", "", "", ""]);
        inputRefs.current[0]?.focus();
        setCountdown(60);
      } else {
        const data = await res.json();
        setError(data.error || t.common.connectionError);
      }
    } catch {
      setError(t.common.connectionError);
    } finally {
      setResending(false);
    }
  }

  return (
    <main className="flex flex-col md:flex-row min-h-screen md:h-screen md:overflow-hidden">
      {/* Left Side */}
      <section className="hidden md:flex md:w-5/12 lg:w-1/2 relative bg-primary overflow-hidden items-center justify-center p-12">
        <div className="absolute inset-0 z-0 opacity-20 bg-gradient-to-br from-primary-container to-primary" />
        <div className="absolute inset-0 bg-gradient-to-br from-primary via-primary to-primary-container opacity-90 z-10" />
        <div className="relative z-20 max-w-lg">
          <h1 className="text-5xl lg:text-7xl font-headline font-extrabold text-on-primary leading-none tracking-tight mb-8 whitespace-pre-line">
            {v.secureYourFuture}
          </h1>
          <div className="h-1 w-24 bg-on-primary mb-8" />
          <p className="text-on-primary/80 text-xl font-medium leading-relaxed max-w-sm">
            {v.verifyIdentity}
          </p>
          <div className="mt-16 grid grid-cols-2 gap-8">
            <div>
              <p className="text-on-primary font-bold text-3xl font-headline tracking-tighter">99.9%</p>
              <p className="text-on-primary/60 text-sm">{v.transactionSecurity}</p>
            </div>
            <div>
              <p className="text-on-primary font-bold text-3xl font-headline tracking-tighter">256-bit</p>
              <p className="text-on-primary/60 text-sm">{v.bankLevelEncryption}</p>
            </div>
          </div>
        </div>
      </section>

      {/* Right Side */}
      <section className="flex-1 bg-surface flex items-center justify-center p-6 md:p-12 lg:p-24 relative md:overflow-y-auto">
        {/* Logo */}
        <div className="absolute top-8 left-8">
          <Image src="/ina_logo.png" alt="Ina Trading" width={160} height={48} priority />
        </div>

        <div className="w-full max-w-md">
          <header className="mb-12">
            <div className="inline-flex items-center justify-center w-12 h-12 bg-tertiary/10 rounded-xl mb-6">
              <span className="material-symbols-outlined text-tertiary" style={{ fontVariationSettings: "'FILL' 1" }}>
                mark_email_read
              </span>
            </div>
            <h2 className="text-4xl font-headline font-extrabold text-on-surface tracking-tight mb-4">
              {v.title}
            </h2>
            <p className="text-on-surface-variant leading-relaxed">
              {v.subtitle}{" "}
              <span className="font-semibold text-on-surface">{email}</span>
              {v.subtitleSuffix}
            </p>
          </header>

          <form className="space-y-8" onSubmit={handleSubmit}>
            {error && (
              <div className="p-3 bg-error-container text-on-error-container rounded-lg text-sm font-medium">
                <div>{error}</div>
                {errorStep ? (
                  <div className="mt-1 text-[11px] font-semibold uppercase tracking-wider opacity-70">
                    Step: {errorStep}
                  </div>
                ) : null}
              </div>
            )}
            {success && (
              <div className="p-3 bg-tertiary/10 text-tertiary rounded-lg text-sm font-medium">
                {success}
              </div>
            )}

            {/* OTP Grid */}
            <div className="flex gap-3 justify-between" onPaste={handlePaste}>
              {otp.map((digit, index) => (
                <input
                  key={index}
                  ref={(el) => { inputRefs.current[index] = el; }}
                  type="text"
                  inputMode="numeric"
                  maxLength={1}
                  value={digit}
                  onChange={(e) => handleOtpChange(index, e.target.value)}
                  onKeyDown={(e) => handleKeyDown(index, e)}
                  placeholder="•"
                  className="otp-input w-14 h-16 text-center text-2xl font-bold rounded-xl border-none bg-surface-container-highest text-on-surface transition-all focus:bg-surface-container-lowest focus:ring-0"
                />
              ))}
            </div>

            <div className="flex items-center justify-between text-sm">
              <span className="text-on-surface-variant">{v.noCode}</span>
              <button
                type="button"
                onClick={handleResend}
                disabled={countdown > 0 || resending}
                className="text-tertiary font-bold hover:underline transition-all active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {resending
                  ? v.resending
                  : countdown > 0
                  ? `${v.resendCountdown} (${countdown}s)`
                  : v.resend}
              </button>
            </div>

            <div className="pt-4">
              <button
                type="submit"
                disabled={loading || otp.join("").length < 6}
                className="w-full bg-gradient-to-br from-primary to-primary-container text-on-primary font-headline font-bold py-5 px-8 rounded-xl shadow-lg shadow-primary/20 hover:opacity-90 active:scale-[0.98] transition-all flex items-center justify-center gap-3 disabled:opacity-60 disabled:scale-100"
              >
                <span>{loading ? v.submitting : v.submit}</span>
                {!loading && <span className="material-symbols-outlined text-lg">arrow_forward</span>}
              </button>
            </div>
          </form>

          <footer className="mt-16 pt-8 border-t border-outline-variant/20">
            <div className="flex flex-col gap-4">
              <div className="flex items-center gap-3">
                <span className="material-symbols-outlined text-outline text-sm">shield</span>
                <span className="text-xs text-on-surface-variant uppercase tracking-widest font-semibold">
                  {v.securityTitle}
                </span>
              </div>
              <p className="text-xs text-on-surface-variant/70 leading-relaxed">{v.securityDesc}</p>
            </div>
          </footer>
        </div>

        <Link
          href="/register"
          className="absolute top-8 right-8 flex items-center gap-2 text-on-surface-variant hover:text-primary transition-colors font-medium"
        >
          <span className="material-symbols-outlined text-lg">close</span>
          <span className="hidden md:inline font-label">{t.common.cancel}</span>
        </Link>

        <div className="absolute top-8 right-24">
          <LanguageToggle />
        </div>
      </section>
    </main>
  );
}

export default function VerifyPage() {
  return (
    <Suspense>
      <VerifyContent />
    </Suspense>
  );
}
