import { Component, createMemo, For, Show } from 'solid-js';
import { useProjectCharacterStats, useCharacters } from '../../../lib/api/trpc-hooks';

export interface CharacterStatsPanelProps {
  projectId: string;
}

export const CharacterStatsPanel: Component<CharacterStatsPanelProps> = (props) => {
  const stats = useProjectCharacterStats(props.projectId);
  const characters = useCharacters(props.projectId);

  const characterMap = createMemo(() => {
    const map = new Map<string, string>();
    characters.data()?.forEach(c => map.set(c.id, c.name));
    return map;
  });

  return (
    <div class="character-stats-panel">
       <h3>Character Statistics</h3>
       <Show when={stats.isLoading()}>
        <div class="loading-state">Loading statistics...</div>
      </Show>
      <Show when={stats.error()}>
        <div class="error-state">
          <p>Error loading stats: {stats.error()?.message}</p>
          <button onClick={() => stats.refetch()}>Retry</button>
        </div>
      </Show>
      <Show when={stats.data() && stats.data()!.length > 0}>
        <div class="stats-table-container">
          <table class="stats-table">
            <thead>
              <tr>
                <th>Character</th>
                <th>Scenes</th>
                <th>Dialogue Lines</th>
                <th>Screen Time</th>
                <th>Relationships</th>
              </tr>
            </thead>
            <tbody>
              <For each={stats.data()}>
                {(stat) => (
                  <tr>
                    <td>{characterMap().get(stat.characterId) || stat.characterId}</td>
                    <td>{stat.sceneCount}</td>
                    <td>{stat.totalDialogueLines}</td>
                    <td>{stat.totalScreenTime} min</td>
                    <td>{stat.relationshipCount}</td>
                  </tr>
                )}
              </For>
            </tbody>
          </table>
        </div>
      </Show>
      <Show when={!stats.data() || stats.data()!.length === 0}>
        <div class="no-stats">No statistics available.</div>
      </Show>
    </div>
  );
};
