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

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

// ponytail: launcher cards — icon, title, one-line description, Open CTA.
// No embedded mini-tools: the dashboard is a launcher, not an ant farm.
interface Card {
  icon: typeof Map;
  title: string;
  description: string;
  view: View;
  span?: string;
  // when set, the card shows "Last: {title} · {relativeTime}" from history.
  kind?: GenerationKind;
}

const CARDS: Card[] = [
  {
    icon: Map,
    title: "World Builder",
    description: "Generate a world with regions, landmarks, and conflicts.",
    view: "world",
    span: "sm:col-span-2",
    kind: "world",
  },
  {
    icon: Timer,
    title: "Initiative",
    description: "Track combatants, HP, conditions, and turn order.",
    view: "initiative",
    kind: undefined,
  },
  {
    icon: Dice5,
    title: "Dice Roller",
    description: "Roll with advantage, modifiers, and roll templates.",
    view: "dice",
  },
  {
    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, personality, and goals.",
    view: "npcs",
    kind: "npc",
  },
  {
    icon: Flag,
    title: "Quest Designer",
    description: "Design 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: ScrollText,
    title: "Session Log",
    description: "Take notes and generate an AI session summary.",
    view: "session",
    kind: "session",
  },
  {
    icon: BookOpen,
    title: "Lore (RAG)",
    description: "Index your world bible and ground generations in it.",
    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 random tables.",
    view: "tables",
  },
  {
    icon: ImagePlus,
    title: "Image Generator",
    description: "Generate portraits, maps, and scene art (macOS).",
    view: "image",
    span: "sm:col-span-2",
    kind: "image",
  },
  {
    icon: Volume2,
    title: "Soundboard",
    description: "Synthesized ambience and SFX for the table.",
    view: "sound",
  },
];

export function Dashboard({ onNavigate }: DashboardProps) {
  // ponytail: one fetch on mount → most-recent 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="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4 auto-rows-fr gap-3 p-4 h-full bg-[var(--color-bg-deep)] overflow-y-auto">
      {CARDS.map((card) => {
        const last = card.kind ? latest[card.kind] : undefined;
        return (
          <BentoCard
            key={card.view}
            title={card.title}
            icon={<card.icon size={16} />}
            span={card.span}
          >
            <div className="flex flex-col h-full min-h-[120px]">
              <div className="flex items-start gap-3 flex-1">
                <div className="shrink-0 w-9 h-9 rounded-lg bg-[var(--color-gold-glow)] flex items-center justify-center text-[var(--color-gold-bright)]">
                  <card.icon size={18} />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-xs text-[var(--color-text-secondary)] leading-relaxed line-clamp-2">
                    {card.description}
                  </p>
                </div>
              </div>

              {last && (
                <p className="text-[10px] text-[var(--color-text-dim)] mt-2 truncate">
                  Last:{" "}
                  <span className="text-[var(--color-text-secondary)]">{last.title}</span>{" "}
                  · {relativeTime(last.createdAt)}
                </p>
              )}

              <button
                onClick={() => onNavigate(card.view)}
                className="mt-2 self-start text-xs font-medium text-[var(--color-gold-bright)] hover:text-[var(--color-gold-muted)] flex items-center gap-1 cursor-pointer transition-colors"
                aria-label={`Open ${card.title}`}
              >
                Open <ArrowRight size={12} />
              </button>
            </div>
          </BentoCard>
        );
      })}
    </div>
  );
}