"use client";

import { useState } 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 LoginPage() {
  const { t } = useLanguage();
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirectTo = safeRedirectPath(searchParams.get("redirect"));
  const setTokenAndCustomer = useAuthStore((s) => s.setTokenAndCustomer);

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [emailNotVerified, setEmailNotVerified] = useState(false);
  const [resendLoading, setResendLoading] = useState(false);
  const [resendSent, setResendSent] = useState(false);

  const signupHref = redirectTo
    ? `/signup?redirect=${encodeURIComponent(redirectTo)}`
    : "/signup";

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setEmailNotVerified(false);
    setResendSent(false);
    setLoading(true);
    try {
      const res = await fetch("/api/storefront-proxy/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json();
      if (!res.ok) {
        if (res.status === 403 && data.code === "email_not_verified") {
          setEmailNotVerified(true);
          setError(t.auth.emailNotVerified);
        } else {
          setError(data.message || t.auth.loginError);
        }
        return;
      }
      setTokenAndCustomer(data.token, data.customer);
      router.push(redirectTo ?? "/");
      router.refresh();
    } catch {
      setError(t.common.error);
    } finally {
      setLoading(false);
    }
  };

  const handleResendVerification = async () => {
    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 }),
      });
      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);
    }
  };

  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.loginTitle}
      </h1>
      <p className="text-gray-500 text-sm mb-8">
        {t.auth.haveAccount}{" "}
        <Link
          href={signupHref}
          className="underline"
          style={{ color: "var(--color-primary)" }}
        >
          {t.auth.signup}
        </Link>
      </p>
      <form onSubmit={handleSubmit} 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">
            {t.auth.password}
          </label>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            className="input-base"
          />
        </div>
        <div className="flex justify-end">
          <Link
            href="/forgot-password"
            className="text-sm"
            style={{ color: "var(--color-primary)" }}
          >
            {t.auth.forgotPassword}
          </Link>
        </div>
        {error && <p className="text-sm text-red-600">{error}</p>}
        {emailNotVerified && (
          <div className="flex flex-col gap-2">
            <Link
              href={`/verify-email?email=${encodeURIComponent(email)}${redirectTo ? `&redirect=${encodeURIComponent(redirectTo)}` : ""}`}
              className="text-sm font-medium text-center py-2 rounded-lg border border-gray-200 hover:bg-gray-50"
              style={{ color: "var(--color-primary)" }}
            >
              {t.auth.verifyTitle}
            </Link>
            <button
              type="button"
              onClick={handleResendVerification}
              disabled={resendLoading}
              className="text-sm text-gray-600 hover:text-gray-900 disabled:opacity-50"
            >
              {resendLoading ? t.common.loading : t.auth.resendVerification}
            </button>
            {resendSent && <p className="text-sm text-green-600">{t.auth.resendSent}</p>}
          </div>
        )}
        <button
          type="submit"
          disabled={loading}
          className="btn-primary w-full py-3.5 rounded-xl text-sm font-bold"
        >
          {loading ? t.common.loading : t.auth.login}
        </button>
      </form>
      <p className="mt-6 text-center text-sm text-gray-500">
        {t.auth.noAccount}{" "}
        <Link
          href={signupHref}
          className="font-semibold"
          style={{ color: "var(--color-primary)" }}
        >
          {t.auth.signup}
        </Link>
      </p>
    </div>
  );
}
