"use client";

import { useEffect, useState } from "react";
import { LockKeyhole, ShieldCheck, UserCircle } from "lucide-react";
import { AdminGuard } from "@/components/admin/AdminGuard";
import { AdminShell } from "@/components/admin/AdminShell";
import { adminRequest, clearAdminToken } from "@/lib/admin-api";
import { useRouter } from "next/navigation";

type AdminProfileResponse = {
  user: {
    email: string;
  };
};

export default function AdminProfilePage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState<"idle" | "loading" | "success" | "error">("idle");
  const [message, setMessage] = useState("");

  useEffect(() => {
    adminRequest<AdminProfileResponse>("/api/admin/me")
      .then((data) => setEmail(data.user.email))
      .catch(() => setEmail("Admin"));
  }, []);

  async function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setStatus("loading");
    setMessage("");

    const form = event.currentTarget;
    const formData = new FormData(form);
    const currentPassword = String(formData.get("currentPassword") ?? "");
    const newPassword = String(formData.get("newPassword") ?? "");
    const confirmPassword = String(formData.get("confirmPassword") ?? "");

    if (newPassword !== confirmPassword) {
      setStatus("error");
      setMessage("New password and confirmation do not match.");
      return;
    }

    try {
      await adminRequest("/api/admin/profile/password", {
        method: "PATCH",
        body: JSON.stringify({
          currentPassword,
          newPassword,
          confirmPassword,
        }),
      });

      form.reset();
      setStatus("success");
      setMessage("Password updated. Please sign in again with your new password.");
      clearAdminToken();
      window.setTimeout(() => router.replace("/admin/login"), 1200);
    } catch (error) {
      setStatus("error");
      setMessage(error instanceof Error ? error.message : "Could not change password");
    }
  }

  return (
    <AdminGuard>
      <AdminShell title="Profile" lead="View your admin account and update your password securely.">
        <div className="grid gap-5 lg:grid-cols-[0.8fr_1.2fr]">
          <section className="rounded-lg border border-border bg-white p-6 shadow-sm">
            <div className="grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
              <UserCircle className="h-6 w-6" />
            </div>
            <h2 className="mt-5 text-2xl font-black tracking-tight text-foreground">
              Admin account
            </h2>
            <p className="mt-2 text-sm font-semibold leading-6 text-muted-foreground">
              This profile controls access to the Ride N Revive admin panel.
            </p>

            <div className="mt-6 rounded-md border border-border bg-slate-50 p-4">
              <p className="text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
                Signed in as
              </p>
              <p className="mt-2 break-words text-base font-black text-foreground">{email}</p>
            </div>

            <div className="mt-4 flex items-start gap-3 rounded-md border border-primary/20 bg-primary/5 p-4">
              <ShieldCheck className="mt-0.5 h-5 w-5 shrink-0 text-primary" />
              <p className="text-sm font-semibold leading-6 text-muted-foreground">
                After changing your password, this session will end and you will need to sign in
                again.
              </p>
            </div>
          </section>

          <section className="rounded-lg border border-border bg-white p-6 shadow-sm">
            <div className="flex items-start gap-3">
              <div className="grid h-11 w-11 place-items-center rounded-md bg-primary/10 text-primary">
                <LockKeyhole className="h-5 w-5" />
              </div>
              <div>
                <h2 className="text-2xl font-black tracking-tight text-foreground">
                  Change password
                </h2>
                <p className="mt-1 text-sm font-semibold leading-6 text-muted-foreground">
                  Use at least 8 characters for the new password.
                </p>
              </div>
            </div>

            <form onSubmit={submit} className="mt-6 grid gap-4">
              <PasswordField
                label="Current password"
                name="currentPassword"
                autoComplete="current-password"
                minLength={1}
              />
              <PasswordField label="New password" name="newPassword" autoComplete="new-password" />
              <PasswordField
                label="Confirm new password"
                name="confirmPassword"
                autoComplete="new-password"
              />

              {message ? (
                <p
                  className={`rounded-md border px-3 py-2 text-sm font-bold ${
                    status === "success"
                      ? "border-emerald-200 bg-emerald-50 text-emerald-700"
                      : "border-destructive/30 bg-destructive/10 text-destructive"
                  }`}
                >
                  {message}
                </p>
              ) : null}

              <button
                type="submit"
                disabled={status === "loading"}
                className="mt-1 inline-flex h-11 items-center justify-center rounded-md bg-primary px-5 text-sm font-black text-primary-foreground transition hover:opacity-95 disabled:opacity-70"
              >
                {status === "loading" ? "Updating password..." : "Update password"}
              </button>
            </form>
          </section>
        </div>
      </AdminShell>
    </AdminGuard>
  );
}

function PasswordField({
  autoComplete,
  label,
  minLength = 8,
  name,
}: {
  autoComplete: string;
  label: string;
  minLength?: number;
  name: string;
}) {
  return (
    <label className="grid gap-1.5">
      <span className="text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
        {label}
      </span>
      <input
        required
        minLength={minLength}
        name={name}
        type="password"
        autoComplete={autoComplete}
        className="h-11 rounded-md border border-border bg-white px-3 text-sm font-semibold outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/15"
      />
    </label>
  );
}
