"use client";

import { useEffect, useState } from "react";
import { format } from "date-fns";

interface Edition {
  id: string;
  date: string;
  pdfPath: string;
  generatedAt: string;
}

export function EditionsView() {
  const [editions, setEditions] = useState<Edition[]>([]);
  const [generating, setGenerating] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function load() {
    const res = await fetch("/api/editions");
    if (res.ok) setEditions((await res.json()).editions);
  }
  useEffect(() => {
    void load();
  }, []);

  async function generate() {
    setGenerating(true);
    setError(null);
    try {
      const res = await fetch("/api/edition", { method: "POST" });
      if (!res.ok) {
        const msg = await res.json().catch(() => null);
        throw new Error(msg?.error?.message ?? `Generation failed (HTTP ${res.status})`);
      }
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setGenerating(false);
    }
  }

  async function remove(id: string) {
    const res = await fetch(`/api/editions/${id}`, { method: "DELETE" });
    if (res.ok) setEditions((prev) => prev.filter((e) => e.id !== id));
  }

  return (
    <main className="max-w-3xl mx-auto px-6 py-8 space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl" style={{ fontFamily: "var(--font-display)" }}>
          The Paper
        </h1>
        <div className="flex gap-2">
          <a
            href="/print"
            target="_blank"
            rel="noreferrer"
            className="px-3 py-2 text-sm"
            style={{
              background: "var(--bg-elevated)",
              color: "var(--text)",
              border: "1px solid var(--border-strong)",
              borderRadius: 6,
            }}
          >
            Preview
          </a>
          <button
            onClick={generate}
            disabled={generating}
            className="px-3 py-2 text-sm font-medium"
            style={{
              background: "var(--accent)",
              color: "var(--text-on-accent)",
              border: "1px solid var(--accent)",
              borderRadius: 6,
              opacity: generating ? 0.6 : 1,
            }}
          >
            {generating ? "Generating…" : "Generate edition"}
          </button>
        </div>
      </div>

      {error && (
        <p
          className="px-4 py-3 text-sm"
          style={{
            background: "var(--bg-card)",
            color: "var(--red)",
            border: "1px solid var(--red)",
            borderRadius: 8,
          }}
        >
          {error}
        </p>
      )}

      {editions.length === 0 ? (
        <p style={{ color: "var(--text-faint)" }}>
          No editions yet. Generate one — it builds a printable PDF from your current dashboard.
        </p>
      ) : (
        <ul className="space-y-2">
          {editions.map((e) => (
            <li
              key={e.id}
              className="flex items-center justify-between p-4"
              style={{ background: "var(--bg-card)", border: "1px solid var(--border)", borderRadius: 8 }}
            >
              <div>
                <div className="text-sm font-medium">
                  {format(new Date(e.generatedAt), "EEEE, MMMM d, yyyy")}
                </div>
                <div className="text-xs" style={{ color: "var(--text-faint)" }}>
                  {format(new Date(e.generatedAt), "h:mm a")}
                </div>
              </div>
              <div className="flex gap-2">
                <a
                  href={`/api/editions/${e.id}/file`}
                  target="_blank"
                  rel="noreferrer"
                  className="px-3 py-1.5 text-sm"
                  style={{
                    background: "var(--bg-elevated)",
                    color: "var(--text)",
                    border: "1px solid var(--border-strong)",
                    borderRadius: 6,
                  }}
                >
                  Open PDF
                </a>
                <button
                  onClick={() => remove(e.id)}
                  aria-label="Delete edition"
                  title="Delete edition"
                  className="px-3 py-1.5 text-sm"
                  style={{
                    background: "var(--bg-elevated)",
                    color: "var(--text-faint)",
                    border: "1px solid var(--border-strong)",
                    borderRadius: 6,
                  }}
                >
                  ✕
                </button>
              </div>
            </li>
          ))}
        </ul>
      )}
    </main>
  );
}
