// app/vault/page.tsx
"use client";

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

import { useAuth } from "@/context/AuthContext";
import { useApi } from "@/lib/api";

type BuildDto = {
  id: string; // internal numeric id (not used by UI)
  uuid: string; // public identifier
  title: string;
  description?: string | null;
  isPublic?: boolean | null;
  createdAt?: string | null;
  updatedAt?: string | null;
};

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";

// UUID validator (defensive)
const isUuid = (v: string) =>
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
    v
  );

function fmt(d?: string | null) {
  if (!d) return "—";
  const dt = new Date(d);
  if (Number.isNaN(dt.getTime())) return d;
  return dt.toLocaleString();
}

export default function VaultPage() {
  const router = useRouter();
  const api = useApi();

  // NOTE:
  // - `loading` here is AuthContext hydration, not network.
  // - `token` is the real gate for /me endpoints.
  const { user, token, loading: authLoading } = useAuth();

  const [builds, setBuilds] = useState<BuildDto[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const authed = !!user && !!token;

  // Redirect if not logged in (after auth hydrates)
  useEffect(() => {
    if (!authLoading && !authed) {
      router.replace("/login");
    }
  }, [authLoading, authed, router]);

  // When auth identity changes, clear stale list to avoid “ghost builds”
  useEffect(() => {
    if (authLoading) return;
    setBuilds([]);
    setError(null);
  }, [authLoading, user?.uuid, token]);

  // Fetch user builds
  useEffect(() => {
    if (authLoading || !authed) return;

    let cancelled = false;

    (async () => {
      setBusy(true);
      setError(null);

      try {
        // IMPORTANT:
        // Use api wrapper so Authorization: Bearer <token> is consistently applied.
        const res = await api.get("/api/v1/builds/me");

        if (!res.ok) {
          const text = await res.text().catch(() => "");
          throw new Error(text || `Request failed (${res.status})`);
        }

        const data = (await res.json()) as BuildDto[];
        if (!cancelled) setBuilds(Array.isArray(data) ? data : []);
      } catch (e: any) {
        if (!cancelled) setError(e?.message || "Failed to load builds");
      } finally {
        if (!cancelled) setBusy(false);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [authLoading, authed, api]);

  if (authLoading) {
    return (
      <div className="mx-auto max-w-6xl px-4 py-6">
        <div className="text-sm opacity-70">Loading…</div>
      </div>
    );
  }

  // Already redirected
  if (!authed) return null;

  return (
    <div className="mx-auto max-w-6xl px-4 py-6">
      {/* Header */}
      <div className="mb-6 flex items-start justify-between gap-4">
        <div>
          <h1 className="text-2xl font-semibold">Vault</h1>
          <p className="text-sm opacity-70">
            Your saved builds. Open one to keep tweaking parts, or add details
            to submit it to the community.
          </p>
        </div>

        <div className="flex items-center gap-3">
          <Link
            href="/builder"
            className="rounded-md border border-white/10 bg-white/5 px-3 py-1.5 text-sm hover:bg-white/10"
            title="Create a new build in the builder"
          >
            New Build
          </Link>
          <Link href="/account" className="text-sm opacity-80 hover:underline" title={"Your account info"}>
            Account →
          </Link>
        </div>
      </div>

      {/* Error */}
      {error && (
        <div className="mb-4 rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm">
          {error}
        </div>
      )}

      {/* Builds list */}
      <div className="rounded-xl border border-white/10 bg-white/5">
        <div className="flex items-center justify-between border-b border-white/10 px-4 py-3">
          <div className="text-sm font-medium">My Builds</div>
          <div className="text-xs opacity-70">
            {busy ? "Refreshing…" : `${builds.length} total`}
          </div>
        </div>

        {builds.length === 0 ? (
          <div className="p-4 text-sm opacity-70">
            No builds yet. Create one in the builder and hit “Save As…”
          </div>
        ) : (
          <ul className="divide-y divide-white/10">
            {builds.map((b) => {
              const valid = !!b?.uuid && isUuid(String(b.uuid));
              const published = Boolean(b.isPublic);

              const openHref = valid
                ? `/builder?load=${encodeURIComponent(b.uuid)}`
                : "#";

              const detailsHref = valid
                ? `/vault/${encodeURIComponent(b.uuid)}/edit`
                : "#";

              return (
                <li
                  key={b.uuid}
                  className="p-4 flex items-start justify-between gap-4"
                >
                  <div className="min-w-0">
                    <div className="flex items-center gap-2">
                      <div className="font-medium truncate">{b.title}</div>

                      {/* Status chip */}
                      <span
                        className={`shrink-0 rounded-full border px-2 py-0.5 text-[11px] ${
                          published
                            ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-200"
                            : "border-white/10 bg-white/5 text-white/70"
                        }`}
                        title={
                          published
                            ? "This build is public (community-visible)."
                            : "Draft (only visible in your Vault)."
                        }
                      >
                        {published ? "Published" : "Draft"}
                      </span>

                      {!valid && (
                        <span
                          className="shrink-0 rounded-full border border-red-500/30 bg-red-500/10 px-2 py-0.5 text-[11px] text-red-200"
                          title="This build record has an invalid UUID."
                        >
                          Invalid UUID
                        </span>
                      )}
                    </div>

                    <div className="mt-1 text-xs opacity-70">
                      Updated: {fmt(b.updatedAt)} • UUID:{" "}
                      <span className="font-mono">{b.uuid}</span>
                    </div>

                    {b.description && (
                      <div className="mt-2 text-sm opacity-80 line-clamp-2">
                        {b.description}
                      </div>
                    )}
                  </div>

                  <div className="flex shrink-0 items-center gap-2">
                    <Link
                      href={openHref}
                      aria-disabled={!valid}
                      tabIndex={!valid ? -1 : 0}
                      className={`rounded-md border px-3 py-1.5 text-xs transition-colors ${
                        valid
                          ? "border-white/10 bg-white/5 hover:bg-white/10"
                          : "border-white/10 bg-white/5 opacity-40 pointer-events-none"
                      }`}
                      title={valid ? "Load this build into the builder" : "Invalid build id"}
                    >
                      View in Builder
                    </Link>

                    <Link
                      href={detailsHref}
                      aria-disabled={!valid}
                      tabIndex={!valid ? -1 : 0}
                      className={`rounded-md border px-3 py-1.5 text-xs transition-colors ${
                        valid
                          ? "border-white/10 bg-white/5 hover:bg-white/10"
                          : "border-white/10 bg-white/5 opacity-40 pointer-events-none"
                      }`}
                      title={valid ? "Edit details / publish later" : "Invalid build id"}
                    >
                      View / Edit
                    </Link>
                  </div>
                </li>
              );
            })}
          </ul>
        )}
      </div>
    </div>
  );
}