"use client";

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

export default function ResetPasswordPage() {
  const { t } = useLanguage();
  const router = useRouter();
  const searchParams = useSearchParams();
  const token = searchParams.get("token");
  const emailParam = searchParams.get("email");

  const [email, setEmail] = useState(emailParam ?? "");
  const [password, setPassword] = useState("");
  const [passwordConfirmation, setPasswordConfirmation] = useState("");
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (emailParam) setEmail(emailParam);
  }, [emailParam]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    if (!token) {
      setError(t.auth.resetError);
      return;
    }
    if (password !== passwordConfirmation) {
      setError(t.auth.confirmPassword + " does not match.");
      return;
    }
    setLoading(true);
    try {
      const res = await fetch("/api/storefront-proxy/auth/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          token,
          email,
          password,
          password_confirmation: passwordConfirmation,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.message || t.auth.resetError);
        setLoading(false);
        return;
      }
      setSuccess(true);
    } catch {
      setError(t.common.error);
    } finally {
      setLoading(false);
    }
  };

  if (success) {
    return (
      <div className="max-w-md mx-auto px-4 py-16">
        <h1 className="text-2xl font-bold text-gray-900 mb-2">
          {t.auth.resetTitle}
        </h1>
        <p className="text-gray-600 mb-8">{t.auth.resetSuccess}</p>
        <Link
          href="/login"
          className="btn-primary inline-block py-3.5 px-6 rounded-xl text-sm font-bold"
        >
          {t.auth.login}
        </Link>
      </div>
    );
  }

  if (!token) {
    return (
      <div className="max-w-md mx-auto px-4 py-16">
        <p className="text-gray-600 mb-4">{t.auth.resetError}</p>
        <Link
          href="/forgot-password"
          className="btn-primary inline-block py-3.5 px-6 rounded-xl text-sm font-bold"
        >
          {t.auth.forgotPassword}
        </Link>
      </div>
    );
  }

  return (
    <div className="max-w-md mx-auto px-4 py-16">
      <h1 className="text-2xl font-bold text-gray-900 mb-2">
        {t.auth.resetTitle}
      </h1>
      <p className="text-gray-500 text-sm mb-8">{t.auth.resetHint}</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
            minLength={8}
            className="input-base"
          />
        </div>
        <div>
          <label className="block text-xs font-semibold text-gray-500 mb-1.5">
            {t.auth.confirmPassword}
          </label>
          <input
            type="password"
            value={passwordConfirmation}
            onChange={(e) => setPasswordConfirmation(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.resetButton}
        </button>
      </form>
      <p className="mt-6 text-center">
        <Link
          href="/login"
          className="text-sm"
          style={{ color: "var(--color-primary)" }}
        >
          {t.auth.backToLogin}
        </Link>
      </p>
    </div>
  );
}
