import { useMemo, useState } from 'react';
import type { Campaign, Character, Encounter, Note, Quest } from '@/lib/schemas';
import { buildCampaignContext } from '@/lib/assistant/context';
import { detectThemes, type CampaignTheme } from '@/lib/assistant/patterns';
import { complete } from '@/lib/llm/client';
import { getLlmConfig, useAssistantStore } from '@/stores/assistantStore';
import { Button } from '@/components/ui/Button';
import { cn } from '@/lib/cn';

const SEV_CLS = { info: 'border-line', warn: 'border-warning/50', danger: 'border-danger/50' } as const;

/** Deterministic campaign themes as cards, with an optional AI "expand" affordance. */
export function CampaignInsights({ campaign, characters, encounters, quests, notes }: {
  campaign: Campaign;
  characters: Character[];
  encounters: Encounter[];
  quests: Quest[];
  notes: Note[];
}) {
  const llmEnabled = useAssistantStore((s) => s.enabled);
  const hasKey = useAssistantStore((s) => !!s.apiKey);
  const canUseLlm = llmEnabled && hasKey;

  const ctx = useMemo(
    () => buildCampaignContext({ campaign, characters, encounters, quests, notes }),
    [campaign, characters, encounters, quests, notes],
  );
  const themes = useMemo(() => detectThemes(ctx), [ctx]);

  if (themes.length === 0) {
    return <p className="text-sm text-muted">No trends detected yet — play a few more sessions.</p>;
  }
  return (
    <ul className="space-y-2">
      {themes.map((t) => (
        <InsightCard key={t.kind} theme={t} ctx={ctx} canUseLlm={canUseLlm} />
      ))}
    </ul>
  );
}

function InsightCard({ theme, ctx, canUseLlm }: { theme: CampaignTheme; ctx: ReturnType<typeof buildCampaignContext>; canUseLlm: boolean }) {
  const [expanded, setExpanded] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const expand = async () => {
    setLoading(true);
    const res = await complete(getLlmConfig(), {
      system: `${ctx.systemConstraint}\n\nYou are a concise ${ctx.systemLabel} GM coach. Give 2–3 sentences of practical advice.`,
      user: `Trend: ${theme.tendency} ${theme.evidence} How should the GM respond?`,
      maxTokens: 400,
    });
    setExpanded(res.ok && 'text' in res ? res.text : 'Could not reach the assistant.');
    setLoading(false);
  };

  return (
    <li className={cn('rounded-lg border bg-panel p-3', SEV_CLS[theme.severity])}>
      <div className="text-sm font-medium text-ink">{theme.tendency}</div>
      <div className="text-xs text-muted">{theme.evidence}</div>
      {theme.recommendation && <div className="mt-1 text-sm text-ink">{theme.recommendation}</div>}
      {canUseLlm && (
        <div className="mt-2">
          <Button size="sm" variant="ghost" onClick={expand} disabled={loading}>
            {loading ? 'Thinking…' : 'Ask the assistant to expand'}
          </Button>
        </div>
      )}
      {expanded && <p className="mt-2 whitespace-pre-wrap rounded-md border border-line bg-surface p-2 text-sm text-ink">{expanded}</p>}
    </li>
  );
}
