import { Component, createSignal, Show } from 'solid-js';
import { useCharacterStats, useUpdateCharacter, useDeleteCharacter } from '../../../lib/api/trpc-hooks';
import { CharacterRelationships } from './CharacterRelationships';
import type { Character } from '../../../../server/types/project';

export interface CharacterProfileProps {
  character: Character;
  onClose?: () => void;
}

export const CharacterProfile: Component<CharacterProfileProps> = (props) => {
  const stats = useCharacterStats(props.character.id);
  const updateCharacter = useUpdateCharacter();
  const deleteCharacter = useDeleteCharacter();
  const [editing, setEditing] = createSignal(false);
  const [editData, setEditData] = createSignal(props.character);

  const handleSave = async () => {
    await updateCharacter.mutateAsync(editData());
    setEditing(false);
  };

  const handleDelete = async () => {
    if (!confirm(`Are you sure you want to delete "${props.character.name}"? This action cannot be undone.`)) return;
    await deleteCharacter.mutateAsync(props.character.id);
    props.onClose?.();
  };

  return (
    <div class="character-profile" role="dialog" aria-label={`Profile of ${props.character.name}`}>
      <div class="character-profile__header">
        <Show when={props.character.imageUrl}>
          <img src={props.character.imageUrl} alt={props.character.name} class="character-profile__image" />
        </Show>
        <div class="character-profile__header-info">
          <Show when={!editing()}>
            <h2>{props.character.name}</h2>
          </Show>
          <Show when={editing()}>
            <input
              type="text"
              value={editData().name}
              onInput={(e) => setEditData({ ...editData(), name: e.currentTarget.value })}
            />
          </Show>
          <span class="character-profile__role">{props.character.role}</span>
        </div>
        <div class="character-profile__actions">
          <button onClick={() => setEditing(!editing())} class="edit-btn">
            {editing() ? 'Discard' : 'Edit'}
          </button>
          <button onClick={props.onClose} class="close-btn">&times;</button>
        </div>
      </div>

      <div class="character-profile__body">
        <div class="character-profile__sections">
          <section class="profile-section">
            <h3>Bio</h3>
            <Show when={!editing()}>
              <p>{props.character.bio || 'No bio yet.'}</p>
            </Show>
            <Show when={editing()}>
              <textarea
                value={editData().bio || ''}
                onInput={(e) => setEditData({ ...editData(), bio: e.currentTarget.value })}
              />
            </Show>
          </section>

          <section class="profile-section">
            <h3>Character Arc</h3>
            <Show when={props.character.arcType}>
              <span class="arc-type-badge">{props.character.arcType} arc</span>
            </Show>
            <Show when={!editing()}>
              <p>{props.character.arc || 'No arc defined.'}</p>
            </Show>
            <Show when={editing()}>
              <textarea
                value={editData().arc || ''}
                onInput={(e) => setEditData({ ...editData(), arc: e.currentTarget.value })}
              />
            </Show>
          </section>

          <section class="profile-section">
            <h3>Traits & Voice</h3>
            <Show when={props.character.traits}>
              <p><strong>Traits:</strong> {props.character.traits}</p>
            </Show>
            <Show when={props.character.voice}>
              <p><strong>Voice:</strong> {props.character.voice}</p>
            </Show>
          </section>

          <section class="profile-section">
            <h3>Motivation & Conflict</h3>
            <Show when={props.character.motivation}>
              <p><strong>Motivation:</strong> {props.character.motivation}</p>
            </Show>
            <Show when={props.character.conflict}>
              <p><strong>Conflict:</strong> {props.character.conflict}</p>
            </Show>
            <Show when={props.character.secret}>
              <p><strong>Secret:</strong> {props.character.secret}</p>
            </Show>
          </section>

          <section class="profile-section">
            <h3>Statistics</h3>
            <div class="stats-grid">
              <div class="stat-item">
                <span class="stat-value">{stats.data()?.sceneCount || 0}</span>
                <span class="stat-label">Scenes</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{stats.data()?.totalDialogueLines || 0}</span>
                <span class="stat-label">Dialogue Lines</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{stats.data()?.totalScreenTime || 0}</span>
                <span class="stat-label">Screen Time (est. min)</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{stats.data()?.relationshipCount || 0}</span>
                <span class="stat-label">Relationships</span>
              </div>
            </div>
          </section>
        </div>

        <CharacterRelationships characterId={props.character.id} />
      </div>

      <Show when={editing()}>
        <div class="character-profile__footer">
          <button onClick={handleSave} class="save-btn">Save Changes</button>
          <button onClick={handleDelete} class="delete-btn">Delete Character</button>
        </div>
      </Show>
    </div>
  );
};
