// @File: src/pages/ResetPassword.tsx
// @Desc: Complete a password reset using the token delivered by email.
//        Submits to the backend which verifies the JWT and syncs the new
//        password to the linked WHMCS client via UpdateClient(password2).
import { useMemo, useState } from "react";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { ArrowLeft, Check, Eye, EyeOff, Loader2, Lock } from "lucide-react";
import { createClient } from "@metagptx/web-sdk";
import { useBranding } from "./admin/cms/useBranding";

const client = createClient();

function passwordStrength(pw: string): {
  score: number;
  label: string;
  color: string;
} {
  let score = 0;
  if (pw.length >= 8) score++;
  if (/[A-Z]/.test(pw)) score++;
  if (/[a-z]/.test(pw)) score++;
  if (/\d/.test(pw)) score++;
  if (/[^A-Za-z0-9]/.test(pw)) score++;
  const labels = ["Too weak", "Weak", "Fair", "Good", "Strong", "Excellent"];
  const colors = [
    "#ef4444",
    "#f97316",
    "#eab308",
    "#84cc16",
    "#22c55e",
    "#16a34a",
  ];
  return { score, label: labels[score], color: colors[score] };
}

export default function ResetPassword() {
  const brand = useBranding();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const token = searchParams.get("token") || "";

  const [password, setPassword] = useState("");
  const [confirm, setConfirm] = useState("");
  const [show, setShow] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [done, setDone] = useState(false);
  const [whmcsSynced, setWhmcsSynced] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const strength = useMemo(() => passwordStrength(password), [password]);
  const tokenMissing = !token || token.length < 10;

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (tokenMissing) {
      setError(
        "This reset link is incomplete. Please request a new one from the Forgot password page."
      );
      return;
    }
    if (password.length < 8) {
      setError("Your new password must be at least 8 characters long.");
      return;
    }
    if (password !== confirm) {
      setError("The two passwords do not match.");
      return;
    }

    setSubmitting(true);
    try {
      const resp = await client.apiCall.invoke({
        url: "/api/v1/whmcs/reset-password",
        method: "POST",
        data: { token, new_password: password },
      });
      const data = (resp?.data ?? {}) as {
        success?: boolean;
        whmcs_synced?: boolean;
        message?: string;
      };
      setWhmcsSynced(Boolean(data.whmcs_synced));
      setDone(true);
    } catch (e) {
      // Surface the backend detail message when available.
      const anyErr = e as {
        response?: { data?: { detail?: string } };
        message?: string;
      };
      const detail =
        anyErr?.response?.data?.detail ||
        anyErr?.message ||
        "We could not reset your password. Please request a new reset link.";
      setError(detail);
    } 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 }}
              >
                Choose a new password
              </h1>
              <p className="text-sm text-slate-500 mb-6">
                Your new password will be synced to your billing account so you
                can sign in everywhere with the same credentials.
              </p>

              {tokenMissing && (
                <div className="text-xs text-amber-700 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 mb-4">
                  This link is missing a reset token. Please request a new one.
                </div>
              )}

              <form onSubmit={onSubmit} className="space-y-4">
                <div>
                  <label className="text-sm font-semibold text-slate-700 mb-1.5 block">
                    New password
                  </label>
                  <div className="relative">
                    <Lock className="w-4 h-4 absolute left-3 top-3.5 text-slate-400" />
                    <input
                      type={show ? "text" : "password"}
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      required
                      minLength={8}
                      placeholder="At least 8 characters"
                      className="w-full pl-9 pr-10 py-2.5 rounded-lg border border-slate-300 bg-white text-slate-900 text-sm focus:outline-none focus:ring-2 transition"
                    />
                    <button
                      type="button"
                      onClick={() => setShow(!show)}
                      className="absolute right-3 top-3 text-slate-400 hover:text-slate-700"
                      aria-label="Toggle password visibility"
                    >
                      {show ? (
                        <EyeOff className="w-4 h-4" />
                      ) : (
                        <Eye className="w-4 h-4" />
                      )}
                    </button>
                  </div>
                  {password && (
                    <div className="mt-2">
                      <div className="h-1.5 w-full bg-slate-100 rounded-full overflow-hidden">
                        <div
                          className="h-full transition-all"
                          style={{
                            width: `${(strength.score / 5) * 100}%`,
                            backgroundColor: strength.color,
                          }}
                        />
                      </div>
                      <div
                        className="text-[11px] mt-1 font-semibold"
                        style={{ color: strength.color }}
                      >
                        {strength.label}
                      </div>
                    </div>
                  )}
                </div>

                <div>
                  <label className="text-sm font-semibold text-slate-700 mb-1.5 block">
                    Confirm new password
                  </label>
                  <div className="relative">
                    <Lock className="w-4 h-4 absolute left-3 top-3.5 text-slate-400" />
                    <input
                      type={show ? "text" : "password"}
                      value={confirm}
                      onChange={(e) => setConfirm(e.target.value)}
                      required
                      minLength={8}
                      placeholder="Re-enter your new password"
                      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 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 || tokenMissing}
                  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" />
                      Updating password…
                    </>
                  ) : (
                    <>Update password</>
                  )}
                </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 }}
              >
                Password updated
              </h1>
              <p className="text-sm text-slate-500 mb-2">
                Your password has been updated successfully.
              </p>
              <p className="text-xs text-slate-400 mb-6">
                {whmcsSynced
                  ? "Your billing account has been synced — use your new password everywhere."
                  : "Your portal password is updated. If you also use the billing system, please try signing in again."}
              </p>
              <button
                onClick={() => navigate("/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 }}
              >
                Go to sign in
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}