"use client";

import { useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useLanguage } from "@/lib/language-context";
import PhoneInput from "@/components/ui/PhoneInput";

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 SignupPage() {
  const { t } = useLanguage();
  const searchParams = useSearchParams();
  const redirectTo = safeRedirectPath(searchParams.get("redirect"));

  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [signupSuccess, setSignupSuccess] = useState(false);

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      const payload = {
        name,
        phone,
        email,
        password,
      };
      const res = await fetch("/api/storefront-proxy/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.message || t.auth.signupError);
        return;
      }
      setSignupSuccess(true);
    } catch {
      setError(t.common.error);
    } finally {
      setLoading(false);
    }
  };

  if (signupSuccess) {
    const verifyUrl = `/verify-email?email=${encodeURIComponent(email)}${redirectTo ? `&redirect=${encodeURIComponent(redirectTo)}` : ""}`;
    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">
        <div className="bg-green-50 border border-green-200 rounded-2xl p-6 text-center">
          <h1 className="text-xl font-bold text-green-800 mb-2">
            {t.auth.signupTitle}
          </h1>
          <p className="text-green-700 text-sm mb-6">
            {t.auth.signupSuccess}
          </p>
          <Link
            href={verifyUrl}
            className="btn-primary inline-block w-full py-3.5 rounded-xl text-sm font-bold text-center"
          >
            {t.auth.verifyTitle}
          </Link>
        </div>
        <p className="mt-6 text-center text-sm text-gray-500">
          <Link href={loginHref} className="underline" style={{ color: "var(--color-primary)" }}>
            {t.auth.backToLogin}
          </Link>
        </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.signupTitle}
      </h1>
      <p className="text-gray-500 text-sm mb-8">
        {t.auth.noAccount}{" "}
        <Link
          href={loginHref}
          className="underline"
          style={{ color: "var(--color-primary)" }}
        >
          {t.auth.login}
        </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.name} <span className="text-red-400">*</span>
          </label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
            className="input-base"
            placeholder="Ahmed Mohamed"
          />
        </div>
        <div>
          <label className="block text-xs font-semibold text-gray-500 mb-1.5">
            {t.auth.phone} <span className="text-red-400">*</span>
          </label>
          <PhoneInput
            value={phone}
            onChange={setPhone}
            placeholder="1234567890"
            required
          />
        </div>
        <div>
          <label className="block text-xs font-semibold text-gray-500 mb-1.5">
            {t.auth.email} <span className="text-red-400">*</span>
          </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} <span className="text-red-400">*</span>
          </label>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            minLength={8}
            className="input-base"
          />
        </div>
        {error && <p className="text-sm text-red-600">{error}</p>}
        <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.signup}
        </button>
      </form>
      <p className="mt-6 text-center text-sm text-gray-500">
        {t.auth.haveAccount}{" "}
        <Link
          href={loginHref}
          className="font-semibold"
          style={{ color: "var(--color-primary)" }}
        >
          {t.auth.login}
        </Link>
      </p>
    </div>
  );
}
