import {
  Map,
  User,
  Swords,
  Dice5,
  Volume2,
  Timer,
  Calendar,
  Wand2,
  ImagePlus,
  BookOpen,
  Shuffle,
  Flag,
  ScrollText,
  type LucideIcon,
} from "lucide-react";
import { useEffect, useState } from "react";
import type { View } from "../App";
import {
  listGenerations,
  relativeTime,
  type GenerationKind,
  type GenerationSummary,
} from "../lib/generations";

interface DashboardProps {
  onNavigate: (view: View) => void;
}

// ponytail: a launcher tile is ONE button — the whole card is the click target
// (the old dashboard only wired the tiny "Open" link, so the boxes felt dead).
// No redundant double-header; just icon, title, one-line description, and an
// optional "last used" footer. Grouped into sections so 13 tools stop being a
// wall of identical tiles.
interface Tile {
  icon: LucideIcon;
  title: string;
  description: string;
  view: View;
  kind?: GenerationKind;
}

interface Section {
  label: string;
  hint: string;
  tiles: Tile[];
}

const SECTIONS: Section[] = [
  {
    label: "At the table",
    hint: "Live-session tools",
    tiles: [
      { icon: Timer, title: "Initiative", description: "Track combatants, HP, conditions, and turns.", view: "initiative" },
      { icon: Dice5, title: "Dice Roller", description: "Roll with advantage, modifiers, and templates.", view: "dice" },
      { icon: Volume2, title: "Soundboard", description: "Synthesized ambience and SFX.", view: "sound" },
      { icon: ScrollText, title: "Session Log", description: "Take notes and generate an AI summary.", view: "session", kind: "session" },
    ],
  },
  {
    label: "Prep & create",
    hint: "Generators for your next session",
    tiles: [
      { icon: Swords, title: "Encounter", description: "Build balanced encounters with an XP budget.", view: "encounter", kind: "encounter" },
      { icon: User, title: "NPC Generator", description: "Generate NPCs with portraits and stat blocks.", view: "npcs", kind: "npc" },
      { icon: Flag, title: "Quest Designer", description: "Multi-step quests with twists and rewards.", view: "quest", kind: "quest" },
      { icon: Wand2, title: "Item Forge", description: "Forge magic items with art and mechanics.", view: "items", kind: "item" },
      { icon: ImagePlus, title: "Image Generator", description: "Portraits, maps, and scene art (macOS).", view: "image", kind: "image" },
    ],
  },
  {
    label: "World & reference",
    hint: "Your campaign bible",
    tiles: [
      { icon: Map, title: "World Builder", description: "Generate a world with regions and a map.", view: "world", kind: "world" },
      { icon: BookOpen, title: "Lore (RAG)", description: "Index your world bible and ground generations.", view: "lore" },
      { icon: Calendar, title: "Calendar", description: "Track the in-world date, events, and moon phases.", view: "calendar" },
      { icon: Shuffle, title: "Random Tables", description: "Roll on built-in and custom tables.", view: "tables" },
    ],
  },
];

export function Dashboard({ onNavigate }: DashboardProps) {
  // ponytail: one fetch on mount → newest generation per kind, for the
  // "Last: …" footer. listGenerations returns newest-first per kind.
  const [latest, setLatest] = useState<Partial<Record<GenerationKind, GenerationSummary>>>({});
  useEffect(() => {
    (async () => {
      try {
        const all = await listGenerations();
        const byKind: Partial<Record<GenerationKind, GenerationSummary>> = {};
        for (const g of all) {
          if (!byKind[g.kind]) byKind[g.kind] = g; // first occurrence is newest
        }
        setLatest(byKind);
      } catch {
        // generations backend unavailable — footer just stays hidden.
      }
    })();
  }, []);

  return (
    <div className="h-full overflow-y-auto bg-[var(--color-bg-deep)]">
      <div className="max-w-6xl mx-auto px-6 py-6 flex flex-col gap-7">
        {SECTIONS.map((section) => (
          <section key={section.label} className="flex flex-col gap-3">
            <div className="flex items-baseline gap-3">
              <h2 className="font-heading text-[var(--color-gold-bright)] text-sm font-semibold tracking-widest uppercase">
                {section.label}
              </h2>
              <span className="text-[10px] text-[var(--color-text-dim)] tracking-wide">
                {section.hint}
              </span>
              <div className="flex-1 h-px bg-[var(--color-border-subtle)]" />
            </div>

            <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 gap-3">
              {section.tiles.map((tile) => {
                const last = tile.kind ? latest[tile.kind] : undefined;
                const Icon = tile.icon;
                return (
                  <button
                    key={tile.view}
                    onClick={() => onNavigate(tile.view)}
                    className="glass-card group text-left p-4 rounded-2xl flex flex-col gap-2 min-h-[112px] cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-gold-bright)]"
                    aria-label={`Open ${tile.title}`}
                  >
                    <div className="flex items-center gap-2.5">
                      <span className="shrink-0 w-9 h-9 rounded-lg bg-[var(--color-gold-glow)] flex items-center justify-center text-[var(--color-gold-bright)] transition-colors group-hover:bg-[var(--color-gold-bright)] group-hover:text-[var(--color-bg-deep)]">
                        <Icon size={18} />
                      </span>
                      <h3 className="font-heading text-[var(--color-text-primary)] text-sm font-semibold leading-tight">
                        {tile.title}
                      </h3>
                    </div>
                    <p className="text-xs text-[var(--color-text-secondary)] leading-relaxed line-clamp-2 flex-1">
                      {tile.description}
                    </p>
                    {last ? (
                      <p className="text-[10px] text-[var(--color-text-dim)] truncate">
                        Last: <span className="text-[var(--color-text-secondary)]">{last.title}</span> · {relativeTime(last.createdAt)}
                      </p>
                    ) : (
                      <span className="text-[10px] text-[var(--color-gold-bright)] opacity-0 group-hover:opacity-100 transition-opacity">
                        Open →
                      </span>
                    )}
                  </button>
                );
              })}
            </div>
          </section>
        ))}

        <p className="text-center text-[10px] text-[var(--color-text-dim)] pt-1">
          Press <kbd className="px-1 py-0.5 rounded border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] font-mono text-[9px]">⌘K</kbd> to jump to any tool.
        </p>
      </div>
    </div>
  );
}