"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useLanguage } from "@/lib/language-context";
import { useAuthStore } from "@/lib/auth-store";

function safeRedirectPath(raw: string | null): string | null {
  if (!raw || typeof raw !== "string") return null;
  const path = raw.startsWith("/") ? raw : `/${raw}`;
  if (path.startsWith("//")) return null;
  return path;
}

export default function VerifyEmailPage() {
  const { t } = useLanguage();
  const router = useRouter();
  const searchParams = useSearchParams();
  const setTokenAndCustomer = useAuthStore((s) => s.setTokenAndCustomer);

  const emailFromUrl = searchParams.get("email") ?? "";
  const tokenFromUrl = searchParams.get("token") ?? "";
  const redirectTo = safeRedirectPath(searchParams.get("redirect"));

  const [email, setEmail] = useState(emailFromUrl);
  const [otp, setOtp] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [resendLoading, setResendLoading] = useState(false);
  const [resendSent, setResendSent] = useState(false);

  // If we have token + email in URL (from verification link), verify immediately
  useEffect(() => {
    if (!tokenFromUrl || !emailFromUrl) return;
    let cancelled = false;
    (async () => {
      setLoading(true);
      setError("");
      try {
        const res = await fetch("/api/storefront-proxy/auth/verify-email", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email: emailFromUrl, token: tokenFromUrl }),
        });
        const data = await res.json();
        if (cancelled) return;
        if (!res.ok) {
          setError(data.message || t.auth.resetError);
          return;
        }
        if (data.already_verified) {
          router.push(`/login${redirectTo ? `?redirect=${encodeURIComponent(redirectTo)}` : ""}`);
          return;
        }
        if (data.token && data.customer) {
          setTokenAndCustomer(data.token, data.customer);
          router.push(redirectTo ?? "/");
          router.refresh();
        }
      } catch {
        if (!cancelled) setError(t.common.error);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [tokenFromUrl, emailFromUrl, redirectTo, setTokenAndCustomer, router, t.auth.resetError, t.common.error]);

  const handleVerifyOtp = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email.trim() || otp.length !== 6) {
      setError("Please enter your email and the 6-digit code.");
      return;
    }
    setError("");
    setLoading(true);
    try {
      const res = await fetch("/api/storefront-proxy/auth/verify-email", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: email.trim(), otp: otp.trim() }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.message || t.auth.resetError);
        return;
      }
      if (data.already_verified) {
        router.push(`/login${redirectTo ? `?redirect=${encodeURIComponent(redirectTo)}` : ""}`);
        return;
      }
      if (data.token && data.customer) {
        setTokenAndCustomer(data.token, data.customer);
        router.push(redirectTo ?? "/");
        router.refresh();
      }
    } catch {
      setError(t.common.error);
    } finally {
      setLoading(false);
    }
  };

  const handleResend = async () => {
    const mail = email.trim() || emailFromUrl;
    if (!mail) {
      setError("Please enter your email to resend the verification email.");
      return;
    }
    setError("");
    setResendLoading(true);
    setResendSent(false);
    try {
      const res = await fetch("/api/storefront-proxy/auth/resend-verification", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: mail }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.message || t.common.error);
        return;
      }
      setResendSent(true);
    } catch {
      setError(t.common.error);
    } finally {
      setResendLoading(false);
    }
  };

  if (tokenFromUrl && emailFromUrl && loading) {
    return (
      <div className="max-w-md mx-auto px-4 sm:px-6 py-8 sm:py-12 md:py-16 min-h-[60vh] flex flex-col justify-center text-center">
        <p className="text-gray-600">{t.common.loading}</p>
      </div>
    );
  }

  return (
    <div className="max-w-md mx-auto px-4 sm:px-6 py-8 sm:py-12 md:py-16 min-h-[60vh] flex flex-col justify-center">
      <h1 className="text-2xl font-bold text-gray-900 mb-2">
        {t.auth.verifyTitle}
      </h1>
      <p className="text-gray-500 text-sm mb-6">
        {t.auth.verifyHint}
      </p>
      <form onSubmit={handleVerifyOtp} className="space-y-5">
        <div>
          <label className="block text-xs font-semibold text-gray-500 mb-1.5">
            {t.auth.email}
          </label>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            className="input-base"
            placeholder="you@example.com"
          />
        </div>
        <div>
          <label className="block text-xs font-semibold text-gray-500 mb-1.5">
            6-digit code
          </label>
          <input
            type="text"
            inputMode="numeric"
            pattern="[0-9]{6}"
            maxLength={6}
            value={otp}
            onChange={(e) => setOtp(e.target.value.replace(/\D/g, "").slice(0, 6))}
            className="input-base font-mono text-lg tracking-widest"
            placeholder={t.auth.verifyCodePlaceholder}
          />
        </div>
        {error && <p className="text-sm text-red-600">{error}</p>}
        {resendSent && (
          <p className="text-sm text-green-600">{t.auth.resendSent}</p>
        )}
        <button
          type="submit"
          disabled={loading || otp.length !== 6}
          className="btn-primary w-full py-3.5 rounded-xl text-sm font-bold"
        >
          {loading ? t.common.loading : t.auth.verifyButton}
        </button>
        <button
          type="button"
          onClick={handleResend}
          disabled={resendLoading}
          className="w-full py-2.5 text-sm font-medium text-gray-600 hover:text-gray-900 disabled:opacity-50"
        >
          {resendLoading ? t.common.loading : t.auth.resendVerification}
        </button>
      </form>
      <p className="mt-6 text-center text-sm text-gray-500">
        <Link href="/login" className="underline" style={{ color: "var(--color-primary)" }}>
          {t.auth.backToLogin}
        </Link>
      </p>
    </div>
  );
}
