// Path: src/components/admin/auth/AdminPasswordForms.tsx
"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";

const inputStyle: React.CSSProperties = {
  background: "var(--color-surface-alt)",
  border: "1.5px solid var(--color-border)",
  color: "var(--color-text)",
};

function Message({ kind, text }: { kind: "error" | "success"; text: string }) {
  if (!text) return null;
  const error = kind === "error";
  return (
    <div
      role={error ? "alert" : "status"}
      className="px-4 py-3 rounded-xl text-sm"
      style={{
        background: error ? "rgba(239,68,68,0.1)" : "rgba(5,150,105,0.1)",
        color: error ? "var(--color-danger)" : "var(--color-success)",
        border: `1px solid ${error ? "rgba(239,68,68,0.2)" : "rgba(5,150,105,0.2)"}`,
      }}
    >
      {text}
    </div>
  );
}

function Submit({ loading, label }: { loading: boolean; label: string }) {
  return (
    <button
      type="submit"
      disabled={loading}
      className="w-full py-3.5 rounded-2xl text-sm font-semibold text-white transition-opacity disabled:opacity-70"
      style={{ background: "linear-gradient(90deg, var(--color-cta), var(--color-cta-hover))" }}
    >
      {loading ? "Please wait..." : label}
    </button>
  );
}

function BackToLogin() {
  return (
    <Link href="/admin/login" className="block text-xs text-center hover:opacity-80" style={{ color: "var(--color-text-muted)" }}>
      ← Back to sign in
    </Link>
  );
}

// ─── Forgot password ──────────────────────────────────────────────────────────

export function AdminForgotPasswordForm() {
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [sent, setSent] = useState("");

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      const res = await fetch("/api/auth/forgot-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (!res.ok || !data.success) {
        setError(data.message ?? "Something went wrong");
        return;
      }
      setSent(data.message);
    } catch {
      setError("Network error — please try again");
    } finally {
      setLoading(false);
    }
  }

  if (sent) {
    return (
      <div className="flex flex-col gap-5">
        <Message kind="success" text={sent} />
        <p className="text-xs text-center" style={{ color: "var(--color-text-muted)" }}>
          The link expires in 30 minutes. Check your spam folder if it doesn&apos;t arrive.
        </p>
        <BackToLogin />
      </div>
    );
  }

  return (
    <form onSubmit={submit} className="flex flex-col gap-5">
      <div className="flex flex-col gap-1.5">
        <label htmlFor="email" className="text-sm font-medium" style={{ color: "var(--color-text-secondary)" }}>
          Work Email
        </label>
        <input
          id="email"
          type="email"
          required
          autoComplete="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="you@company.com"
          className="w-full px-4 py-3 rounded-xl text-sm outline-none"
          style={inputStyle}
        />
      </div>
      <Message kind="error" text={error} />
      <Submit loading={loading} label="Send reset link" />
      <BackToLogin />
    </form>
  );
}

// ─── Reset password ───────────────────────────────────────────────────────────

export function AdminResetPasswordForm({ token }: { token: string }) {
  const router = useRouter();
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [done, setDone] = useState("");

  if (!/^[a-f0-9]{64}$/.test(token)) {
    return (
      <div className="flex flex-col gap-5">
        <Message kind="error" text="This reset link is invalid. Please request a new one." />
        <Link href="/admin/forgot-password" className="text-sm text-center font-medium hover:opacity-80" style={{ color: "var(--color-cta)" }}>
          Request a new link
        </Link>
        <BackToLogin />
      </div>
    );
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    if (password.length < 8) return setError("Password must be at least 8 characters");
    if (password !== confirmPassword) return setError("Passwords do not match");
    setLoading(true);
    try {
      const res = await fetch("/api/auth/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, password, confirmPassword }),
      });
      const data = await res.json();
      if (!res.ok || !data.success) {
        setError(data.message ?? "Something went wrong");
        return;
      }
      setDone(data.message);
      setTimeout(() => router.replace("/admin/login"), 2500);
    } catch {
      setError("Network error — please try again");
    } finally {
      setLoading(false);
    }
  }

  if (done) {
    return (
      <div className="flex flex-col gap-5">
        <Message kind="success" text={done} />
        <BackToLogin />
      </div>
    );
  }

  return (
    <form onSubmit={submit} className="flex flex-col gap-5">
      <div className="flex flex-col gap-1.5">
        <label htmlFor="password" className="text-sm font-medium" style={{ color: "var(--color-text-secondary)" }}>
          New password
        </label>
        <input
          id="password"
          type="password"
          required
          minLength={8}
          autoComplete="new-password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          className="w-full px-4 py-3 rounded-xl text-sm outline-none"
          style={inputStyle}
        />
        <span className="text-xs" style={{ color: "var(--color-text-muted)" }}>At least 8 characters.</span>
      </div>
      <div className="flex flex-col gap-1.5">
        <label htmlFor="confirmPassword" className="text-sm font-medium" style={{ color: "var(--color-text-secondary)" }}>
          Confirm new password
        </label>
        <input
          id="confirmPassword"
          type="password"
          required
          autoComplete="new-password"
          value={confirmPassword}
          onChange={(e) => setConfirmPassword(e.target.value)}
          className="w-full px-4 py-3 rounded-xl text-sm outline-none"
          style={inputStyle}
        />
      </div>
      <Message kind="error" text={error} />
      <Submit loading={loading} label="Reset password" />
      <BackToLogin />
    </form>
  );
}

// ─── Tester registration (only rendered when enabled, see testRegistration.ts) ─

export function AdminRegisterForm() {
  const router = useRouter();
  const [form, setForm] = useState({ first_name: "", last_name: "", email: "", password: "", confirmPassword: "" });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [done, setDone] = useState("");

  const set = (key: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) =>
    setForm((f) => ({ ...f, [key]: e.target.value }));

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    if (form.password.length < 8) return setError("Password must be at least 8 characters");
    if (form.password !== form.confirmPassword) return setError("Passwords do not match");
    setLoading(true);
    try {
      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok || !data.success) {
        setError(data.message ?? "Something went wrong");
        return;
      }
      setDone(data.message);
      setTimeout(() => router.replace("/admin/login"), 3500);
    } catch {
      setError("Network error — please try again");
    } finally {
      setLoading(false);
    }
  }

  if (done) {
    return (
      <div className="flex flex-col gap-5">
        <Message kind="success" text={done} />
        <BackToLogin />
      </div>
    );
  }

  const field = (id: keyof typeof form, label: string, type: string, autoComplete: string, extra?: React.ReactNode) => (
    <div className="flex flex-col gap-1.5">
      <label htmlFor={id} className="text-sm font-medium" style={{ color: "var(--color-text-secondary)" }}>
        {label}
      </label>
      <input
        id={id}
        type={type}
        required
        autoComplete={autoComplete}
        value={form[id]}
        onChange={set(id)}
        className="w-full px-4 py-3 rounded-xl text-sm outline-none"
        style={inputStyle}
      />
      {extra}
    </div>
  );

  return (
    <form onSubmit={submit} className="flex flex-col gap-5">
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
        {field("first_name", "First name", "text", "given-name")}
        {field("last_name", "Last name", "text", "family-name")}
      </div>
      {field("email", "Email", "email", "email",
        <span className="text-xs" style={{ color: "var(--color-text-muted)" }}>Use a real inbox — a sign-in code is emailed to it.</span>)}
      {field("password", "Password", "password", "new-password",
        <span className="text-xs" style={{ color: "var(--color-text-muted)" }}>At least 8 characters.</span>)}
      {field("confirmPassword", "Confirm password", "password", "new-password")}
      <Message kind="error" text={error} />
      <Submit loading={loading} label="Create testing account" />
      <BackToLogin />
    </form>
  );
}
