"use client";

import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useState, type ReactNode, type SubmitEvent } from "react";
import { api, errorMessage } from "@/app/(admin)/_lib/api";
import { PASSWORD_HINT, passwordProblem } from "@/app/(admin)/_lib/validation";
import { Icon } from "./Icon";

function AuthCard({ title, sub, children }: { title: string; sub: string; children: ReactNode }) {
  return (
    <div className="auth-page">
      <div className="auth-card card">
        <div className="auth-brand">
          <div className="sb-mark">U</div>
          <span className="logo">Unionists</span>
        </div>
        <h1>{title}</h1>
        <p className="sub">{sub}</p>
        {children}
        <Link href="/login" className="link auth-back">
          ← Back to sign in
        </Link>
      </div>
    </div>
  );
}

export function ForgotPasswordView() {
  const [email, setEmail] = useState("");
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const submit = async (e: SubmitEvent) => {
    e.preventDefault();
    setBusy(true);
    setError(null);
    try {
      const d = await api<{ message: string }>("/auth/forgot-password", { method: "POST", body: { email: email.trim() }, auth: false });
      setDone(d.message);
    } catch (err) {
      setError(errorMessage(err));
    } finally {
      setBusy(false);
    }
  };

  return (
    <AuthCard title="Forgot password" sub="Enter your admin email. If an account exists, we'll send a reset link that works for 30 minutes.">
      {done ? (
        <div className="form-ok" role="status">
          <Icon name="mail" size={16} />
          {done}
        </div>
      ) : (
        <form onSubmit={submit}>
          <div className="field">
            <label htmlFor="fp-email">Email address</label>
            <input id="fp-email" className="input" type="email" autoComplete="username" required maxLength={254} value={email} onChange={(e) => setEmail(e.target.value)} />
          </div>
          {error && (
            <div className="form-error" role="alert">
              {error}
            </div>
          )}
          <button className="btn btn-primary btn-block" type="submit" disabled={busy}>
            {busy ? <span className="spin" aria-label="Sending" /> : "Send reset link"}
          </button>
        </form>
      )}
    </AuthCard>
  );
}

/** Shared by reset-password and the account page. */
export function NewPasswordFields({ value, onChange, confirm, onConfirm, idPrefix }: { value: string; onChange: (v: string) => void; confirm: string; onConfirm: (v: string) => void; idPrefix: string }) {
  const problem = value ? passwordProblem(value) : null;
  const mismatch = confirm && confirm !== value;
  return (
    <>
      <div className="field">
        <label htmlFor={`${idPrefix}-new`}>New password</label>
        <input id={`${idPrefix}-new`} className="input" type="password" autoComplete="new-password" required value={value} onChange={(e) => onChange(e.target.value)} aria-describedby={`${idPrefix}-hint`} />
        <div id={`${idPrefix}-hint`} className={`hint${problem ? " bad" : ""}`}>
          {problem ?? PASSWORD_HINT}
        </div>
      </div>
      <div className="field">
        <label htmlFor={`${idPrefix}-confirm`}>Confirm new password</label>
        <input id={`${idPrefix}-confirm`} className="input" type="password" autoComplete="new-password" required value={confirm} onChange={(e) => onConfirm(e.target.value)} />
        {mismatch && <div className="hint bad">Passwords don&apos;t match.</div>}
      </div>
    </>
  );
}

export function ResetPasswordView() {
  const token = useSearchParams().get("token") ?? "";
  const [pw, setPw] = useState("");
  const [confirm, setConfirm] = useState("");
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const submit = async (e: SubmitEvent) => {
    e.preventDefault();
    const problem = passwordProblem(pw);
    if (problem) return setError(problem);
    if (pw !== confirm) return setError("Passwords don't match.");
    setBusy(true);
    setError(null);
    try {
      await api<void>("/auth/reset-password", { method: "POST", body: { token, newPassword: pw }, auth: false });
      setDone(true);
    } catch (err) {
      setError(errorMessage(err));
    } finally {
      setBusy(false);
    }
  };

  if (!token)
    return (
      <AuthCard title="Reset password" sub="This link is missing its token.">
        <div className="form-error">Open the link from the reset email again, or request a new one.</div>
        <Link href="/forgot-password" className="btn btn-primary btn-block">
          Request a new link
        </Link>
      </AuthCard>
    );

  return (
    <AuthCard title="Reset password" sub="Choose a new password. This signs you out everywhere.">
      {done ? (
        <div className="form-ok" role="status">
          <Icon name="check" size={16} />
          Password changed. Sign in with your new password.
        </div>
      ) : (
        <form onSubmit={submit}>
          <NewPasswordFields value={pw} onChange={setPw} confirm={confirm} onConfirm={setConfirm} idPrefix="rp" />
          {error && (
            <div className="form-error" role="alert">
              {error}
            </div>
          )}
          <button className="btn btn-primary btn-block" type="submit" disabled={busy}>
            {busy ? <span className="spin" aria-label="Saving" /> : "Set new password"}
          </button>
        </form>
      )}
    </AuthCard>
  );
}
