// @File: src/pages/ForgotPassword.tsx
// @Desc: Request a password reset email. Calls the backend which mints a signed
//        reset token and delivers it to the user through WHMCS's SMTP.
import { useState } from "react";
import { Link } from "react-router-dom";
import { ArrowLeft, Check, Loader2, Mail } from "lucide-react";
import { createClient } from "@metagptx/web-sdk";
import { useBranding } from "./admin/cms/useBranding";

const client = createClient();

export default function ForgotPassword() {
  const brand = useBranding();
  const [email, setEmail] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email) return;
    setSubmitting(true);
    setError(null);
    try {
      await client.apiCall.invoke({
        url: "/api/v1/whmcs/forgot-password",
        method: "POST",
        data: { email: email.trim().toLowerCase() },
      });
      setDone(true);
    } catch (e) {
      setError(
        e instanceof Error
          ? e.message
          : "We could not send the reset email right now. Please try again."
      );
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div
      className="min-h-screen flex items-center justify-center p-4"
      style={{
        fontFamily: brand.fontBody,
        background: `linear-gradient(135deg, ${brand.bg}, ${brand.secondary})`,
      }}
    >
      <div className="w-full max-w-md">
        <div className="bg-white rounded-3xl shadow-2xl p-8 md:p-10">
          <Link
            to="/login"
            className="inline-flex items-center gap-1.5 text-sm font-semibold text-slate-500 hover:text-slate-800 mb-6"
          >
            <ArrowLeft className="w-4 h-4" /> Back to sign in
          </Link>

          {!done ? (
            <>
              <h1
                className="text-2xl font-extrabold text-slate-900 mb-1"
                style={{ fontFamily: brand.fontHeading }}
              >
                Forgot your password?
              </h1>
              <p className="text-sm text-slate-500 mb-6">
                Enter the email address on your account. We&apos;ll send you a
                secure link to choose a new password. The link will expire in
                30&nbsp;minutes.
              </p>

              <form onSubmit={onSubmit} className="space-y-4">
                <div>
                  <label className="text-sm font-semibold text-slate-700 mb-1.5 block">
                    Email
                  </label>
                  <div className="relative">
                    <Mail className="w-4 h-4 absolute left-3 top-3.5 text-slate-400" />
                    <input
                      type="email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      required
                      placeholder="you@company.com"
                      className="w-full pl-9 pr-3 py-2.5 rounded-lg border border-slate-300 bg-white text-slate-900 text-sm focus:outline-none focus:ring-2 focus:border-transparent transition"
                    />
                  </div>
                </div>

                {error && (
                  <div className="text-xs text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2">
                    {error}
                  </div>
                )}

                <button
                  type="submit"
                  disabled={submitting}
                  className="w-full py-2.5 rounded-lg text-white font-bold text-sm transition hover:opacity-95 flex items-center justify-center gap-2 disabled:opacity-70 disabled:cursor-not-allowed"
                  style={{ backgroundColor: brand.primary }}
                >
                  {submitting ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" />
                      Sending reset link…
                    </>
                  ) : (
                    <>Send reset link</>
                  )}
                </button>
              </form>
            </>
          ) : (
            <div className="text-center py-4">
              <div
                className="w-14 h-14 rounded-full mx-auto flex items-center justify-center mb-4"
                style={{ backgroundColor: `${brand.primary}1a` }}
              >
                <Check
                  className="w-7 h-7"
                  style={{ color: brand.primary }}
                  strokeWidth={3}
                />
              </div>
              <h1
                className="text-2xl font-extrabold text-slate-900 mb-2"
                style={{ fontFamily: brand.fontHeading }}
              >
                Check your inbox
              </h1>
              <p className="text-sm text-slate-500 mb-6">
                If an account exists for <strong>{email}</strong>, we&apos;ve
                sent a password reset link. It will expire in 30&nbsp;minutes.
                Don&apos;t forget to check your spam folder.
              </p>
              <Link
                to="/login"
                className="inline-flex items-center justify-center w-full py-2.5 rounded-lg text-white font-bold text-sm hover:opacity-95"
                style={{ backgroundColor: brand.primary }}
              >
                Back to sign in
              </Link>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}