import { Component, createSignal, For, Show } from 'solid-js';
import { useSearchCharacters } from '../../../lib/api/trpc-hooks';
import { CharacterCard } from './CharacterCard';
import type { Character } from '../../../../server/types/project';

export interface CharacterSearchProps {
  projectId: string;
  onCharacterSelect?: (character: Character) => void;
}

export const CharacterSearch: Component<CharacterSearchProps> = (props) => {
  const [query, setQuery] = createSignal('');
  const [role, setRole] = createSignal<string>('');
  const [arcType, setArcType] = createSignal<string>('');
  const results = useSearchCharacters(props.projectId, query, role, arcType);

  const handleSearch = () => {
    results.refetch();
  };

  const handleClear = () => {
    setQuery('');
    setRole('');
    setArcType('');
  };

  return (
    <div class="character-search">
      <div class="search-controls">
        <input
          type="text"
          placeholder="Search characters by name, bio, traits..."
          value={query()}
          onInput={(e) => setQuery(e.currentTarget.value)}
          onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
          class="search-input"
        />
        <select value={role()} onChange={(e) => setRole(e.currentTarget.value)} class="filter-select">
          <option value="">All Roles</option>
          <option value="protagonist">Protagonist</option>
          <option value="antagonist">Antagonist</option>
          <option value="supporting">Supporting</option>
          <option value="background">Background</option>
          <option value="ensemble">Ensemble</option>
        </select>
        <select value={arcType()} onChange={(e) => setArcType(e.currentTarget.value)} class="filter-select">
          <option value="">All Arcs</option>
          <option value="positive">Positive Arc</option>
          <option value="negative">Negative Arc</option>
          <option value="flat">Flat Arc</option>
          <option value="complex">Complex Arc</option>
        </select>
        <button onClick={handleSearch} class="search-btn">Search</button>
        <button onClick={handleClear} class="clear-btn">Clear</button>
      </div>
      <Show when={results.isLoading()}>
        <div class="loading-state">Searching...</div>
      </Show>
      <Show when={results.error()}>
        <div class="error-state">
          <p>Error: {results.error()?.message}</p>
          <button onClick={() => results.refetch()}>Retry</button>
        </div>
      </Show>
      <div class="search-results">
        <For each={results.data()}>
          {(character) => (
            <CharacterCard
              character={character}
              onSelect={props.onCharacterSelect}
            />
          )}
        </For>
        <Show when={!results.data() || results.data()!.length === 0}>
          <div class="no-results">No characters found</div>
        </Show>
      </div>
    </div>
  );
};
