import { Component, createSignal, For, Show } from 'solid-js';
import {
  useCharacterRelationships,
  useCreateRelationship,
  useUpdateRelationship,
  useDeleteRelationship,
} from '../../../lib/api/trpc-hooks';
import type { CharacterRelationship } from '../../../../server/types/project';

export interface CharacterRelationshipsProps {
  characterId: string;
}

const relationshipLabels: Record<string, string> = {
  family: '👨‍👩‍👧‍👦 Family',
  romantic: '❤️ Romantic',
  friendship: '🤝 Friendship',
  rivalry: '⚔️ Rivalry',
  mentor: '🎓 Mentor',
  alliance: '🤝 Alliance',
  conflict: '💥 Conflict',
  professional: '💼 Professional',
  other: '📌 Other',
};

export const CharacterRelationships: Component<CharacterRelationshipsProps> = (props) => {
  const relationships = useCharacterRelationships(props.characterId);
  const createRelationship = useCreateRelationship();
  const deleteRelationship = useDeleteRelationship();
  const [showForm, setShowForm] = createSignal(false);
  const [newRel, setNewRel] = createSignal({
    characterIdB: '',
    relationshipType: 'friendship' as CharacterRelationship['relationshipType'],
    description: '',
    strength: 50,
    isAntagonistic: false,
  });

  const handleCreate = async () => {
    if (!newRel().characterIdB) return;
    await createRelationship.mutateAsync({
      characterIdA: props.characterId,
      ...newRel(),
    });
    setShowForm(false);
    setNewRel({
      characterIdB: '',
      relationshipType: 'friendship',
      description: '',
      strength: 50,
      isAntagonistic: false,
    });
  };

  return (
    <div class="character-relationships">
      <div class="relationships-header">
        <h3>Relationships</h3>
        <button onClick={() => setShowForm(!showForm())} class="add-relationship-btn">
          {showForm() ? 'Cancel' : '+ Add Relationship'}
        </button>
      </div>

      <Show when={showForm()}>
        <div class="relationship-form">
          <input
            type="text"
            placeholder="Other character ID"
            value={newRel().characterIdB}
            onInput={(e) => setNewRel({ ...newRel(), characterIdB: e.currentTarget.value })}
          />
          <select
            value={newRel().relationshipType}
            onChange={(e) => setNewRel({ ...newRel(), relationshipType: e.currentTarget.value as CharacterRelationship['relationshipType'] })}
          >
            <For each={Object.entries(relationshipLabels)}>
              {([key, label]) => (
                <option value={key}>{label}</option>
              )}
            </For>
          </select>
          <input
            type="range"
            min="0"
            max="100"
            value={newRel().strength}
            onChange={(e) => setNewRel({ ...newRel(), strength: parseInt(e.currentTarget.value) })}
          />
          <label>
            <input
              type="checkbox"
              checked={newRel().isAntagonistic}
              onChange={(e) => setNewRel({ ...newRel(), isAntagonistic: e.currentTarget.checked })}
            />
            Antagonistic
          </label>
          <textarea
            placeholder="Description"
            value={newRel().description}
            onInput={(e) => setNewRel({ ...newRel(), description: e.currentTarget.value })}
          />
          <button onClick={handleCreate} class="create-relationship-btn">Create</button>
        </div>
      </Show>

      <div class="relationship-list">
        <For each={relationships.data()}>
          {(rel) => (
            <div class={`relationship-item ${rel.isAntagonistic ? 'antagonistic' : 'positive'}`}>
              <div class="relationship-info">
                <span class="relationship-type">{relationshipLabels[rel.relationshipType]}</span>
                <span class="relationship-strength">
                  Strength: {rel.strength}%
                </span>
              </div>
              <div class="relationship-detail">
                <Show when={rel.description}>
                  <span>{rel.description}</span>
                </Show>
              </div>
              <button
                onClick={() => {
                  if (!confirm('Are you sure you want to remove this relationship?')) return;
                  deleteRelationship.mutateAsync(rel.id);
                }}
                class="delete-relationship-btn"
              >
                Remove
              </button>
            </div>
          )}
        </For>
        <Show when={!relationships.data() || relationships.data()!.length === 0}>
          <div class="no-relationships">No relationships defined yet.</div>
        </Show>
      </div>
    </div>
  );
};
