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

export interface CharacterListProps {
  projectId: string;
}

export const CharacterList: Component<CharacterListProps> = (props) => {
  const charactersQuery = useCharacters(props.projectId);
  const createCharacter = useCreateCharacter();
  const [selectedCharacter, setSelectedCharacter] = createSignal<Character | null>(null);
  const [showForm, setShowForm] = createSignal(false);

  const [formData, setFormData] = createSignal({
    name: '',
    description: '',
    bio: '',
    role: 'supporting' as 'protagonist' | 'antagonist' | 'supporting' | 'background' | 'ensemble',
    arc: '',
    arcType: undefined as 'positive' | 'negative' | 'flat' | 'complex' | undefined,
    age: undefined as number | undefined,
    gender: '',
    voice: '',
    traits: '',
    motivation: '',
    conflict: '',
    secret: '',
  });

  const handleCreate = async () => {
    if (!formData().name.trim()) return;
    await createCharacter.mutateAsync({
      ...formData(),
      projectId: props.projectId,
    });
    setShowForm(false);
    setFormData({
      name: '',
      description: '',
      bio: '',
      role: 'supporting',
      arc: '',
      arcType: undefined,
      age: undefined,
      gender: '',
      voice: '',
      traits: '',
      motivation: '',
      conflict: '',
      secret: '',
    });
  };

  return (
    <div class="character-list">
      <div class="character-list__header">
        <h2>Characters</h2>
        <button onClick={() => setShowForm(!showForm())} class="add-character-btn">
          {showForm() ? 'Cancel' : '+ Add Character'}
        </button>
      </div>

      <Show when={showForm()}>
        <div class="character-form">
          <div class="form-row">
            <input
              type="text"
              placeholder="Name *"
              value={formData().name}
              onInput={(e) => setFormData({ ...formData(), name: e.currentTarget.value })}
              required
            />
            <select
              value={formData().role}
              onChange={(e) => setFormData({ ...formData(), role: e.currentTarget.value as Character['role'] })}
            >
              <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>
          </div>
          <textarea
            placeholder="Bio"
            value={formData().bio}
            onInput={(e) => setFormData({ ...formData(), bio: e.currentTarget.value })}
          />
          <textarea
            placeholder="Description"
            value={formData().description}
            onInput={(e) => setFormData({ ...formData(), description: e.currentTarget.value })}
          />
          <div class="form-row">
            <input
              type="text"
              placeholder="Traits (comma-separated)"
              value={formData().traits}
              onInput={(e) => setFormData({ ...formData(), traits: e.currentTarget.value })}
            />
            <input
              type="text"
              placeholder="Voice description"
              value={formData().voice}
              onInput={(e) => setFormData({ ...formData(), voice: e.currentTarget.value })}
            />
          </div>
          <div class="form-row">
            <input
              type="text"
              placeholder="Motivation"
              value={formData().motivation}
              onInput={(e) => setFormData({ ...formData(), motivation: e.currentTarget.value })}
            />
            <input
              type="text"
              placeholder="Conflict"
              value={formData().conflict}
              onInput={(e) => setFormData({ ...formData(), conflict: e.currentTarget.value })}
            />
          </div>
          <textarea
            placeholder="Character arc"
            value={formData().arc}
            onInput={(e) => setFormData({ ...formData(), arc: e.currentTarget.value })}
          />
          <select
            value={formData().arcType || ''}
            onChange={(e) => setFormData({ ...formData(), arcType: e.currentTarget.value as Character['arcType'] || undefined })}
          >
            <option value="">No arc type</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>
          <input
            type="button"
            value="Create Character"
            onClick={handleCreate}
            class="create-btn"
          />
        </div>
      </Show>

      <Show when={charactersQuery.isLoading()}>
        <div class="loading-state">Loading characters...</div>
      </Show>
      <Show when={charactersQuery.error()}>
        <div class="error-state">
          <p>Error loading characters: {charactersQuery.error()?.message}</p>
          <button onClick={() => charactersQuery.refetch()}>Retry</button>
        </div>
      </Show>
      <div class="character-grid">
        <For each={charactersQuery.data()}>
          {(character) => (
            <CharacterCard
              character={character}
              onSelect={setSelectedCharacter}
            />
          )}
        </For>
      </div>

      <Show when={selectedCharacter()}>
        <CharacterProfile
          character={selectedCharacter()!}
          onClose={() => setSelectedCharacter(null)}
        />
      </Show>
    </div>
  );
};
