// 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";

type BuildDto = {
  id: string;
  uuid: string; // UUID string
  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";

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 { user, loading, getAuthHeaders } = useAuth();

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

  const authed = !!user;

  useEffect(() => {
    if (!loading && !authed) {
      router.replace("/login");
    }
  }, [loading, authed, router]);

  const headers = useMemo(() => getAuthHeaders(), [getAuthHeaders]);

  useEffect(() => {
    if (loading || !authed) return;

    let cancelled = false;

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

      try {
        const res = await fetch(`${API_BASE_URL}/api/v1/products/me/builds`, {
          method: "GET",
          headers,
        });

        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;
    };
  }, [loading, authed, headers]);

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

  // If not authed, we already redirected; render nothing.
  if (!authed) return null;

  return (
    <div className="mx-auto max-w-6xl px-4 py-6">
      <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. Load one into the builder or publish it later.
          </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"
          >
            New Build
          </Link>
          <Link
            href="/account"
            className="text-sm opacity-80 hover:underline"
          >
            Account →
          </Link>
        </div>
      </div>

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

      <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 to Vault”.
          </div>
        ) : (
          <ul className="divide-y divide-white/10">
            {builds.map((b) => (
              <li key={b.uuid} className="p-4 flex items-start justify-between gap-4">
                <div className="min-w-0">
                  <div className="font-medium truncate">{b.title}</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>
                  ) : null}
                </div>

                <div className="flex shrink-0 items-center gap-2">
                  {/* Placeholder: wire this to "load into builder" next */}
                  <Link
                    href={`/builder?build=${b.uuid}`}
                    className="rounded-md border border-white/10 bg-white/5 px-3 py-1.5 text-xs hover:bg-white/10"
                  >
                    Open
                  </Link>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}