/**
 * TagSelector component for selecting and managing tags
 */

import { useState } from 'react';
import { useTags } from '../hooks/useTags';
import { useToastContext } from '../App';
import { colors } from '../theme';
import type { Tag } from '../types/recipe';

interface TagSelectorProps {
  selectedTags: Tag[];
  onTagsChange: (tags: Tag[]) => void;
}

export function TagSelector({ selectedTags, onTagsChange }: TagSelectorProps) {
  const { tags, loading, error, addTag } = useTags();
  const toast = useToastContext();
  const [showNewTagForm, setShowNewTagForm] = useState(false);
  const [newTagName, setNewTagName] = useState('');
  const [newTagColor, setNewTagColor] = useState<string>(colors.primary);
  const [creating, setCreating] = useState(false);

  const handleToggleTag = (tag: Tag) => {
    const isSelected = selectedTags.some((t) => t.id === tag.id);

    if (isSelected) {
      onTagsChange(selectedTags.filter((t) => t.id !== tag.id));
    } else {
      onTagsChange([...selectedTags, tag]);
    }
  };

  const handleCreateTag = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!newTagName.trim()) return;

    setCreating(true);
    try {
      const newTag = await addTag(newTagName.trim(), newTagColor);
      onTagsChange([...selectedTags, newTag]);
      setNewTagName('');
      setNewTagColor(colors.primary);
      setShowNewTagForm(false);
      toast.success(`Tag "${newTag.name}" created!`);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to create tag';
      toast.error(errorMessage);
    } finally {
      setCreating(false);
    }
  };

  if (loading) {
    return <div className="text-[var(--text-dim)]">Loading tags...</div>;
  }

  if (error) {
    return (
      <div className="rounded-md border border-[var(--color-error)]/25 bg-[var(--color-error-light)] p-3">
        <p className="text-sm text-[var(--color-error)]">Error loading tags: {error}</p>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      <div className="flex flex-wrap gap-2">
        {tags.map((tag) => {
          const isSelected = selectedTags.some((t) => t.id === tag.id);
          return (
            <button
              key={tag.id}
              type="button"
              onClick={() => handleToggleTag(tag)}
              className={`
                ui-chip px-3 py-1 text-sm font-medium transition-colors
                ${isSelected ? 'text-white' : 'text-[var(--text)] hover:bg-[var(--surface-muted)]'}
              `}
              style={isSelected ? { backgroundColor: tag.color || 'var(--color-primary)' } : {}}
            >
              {tag.name}
            </button>
          );
        })}
      </div>

      {!showNewTagForm ? (
        <button
          type="button"
          onClick={() => setShowNewTagForm(true)}
          className="ui-btn ui-btn-secondary min-h-0 px-2 py-1 text-sm font-medium text-[var(--color-primary-dark)]"
        >
          + Create new tag
        </button>
      ) : (
        <form onSubmit={handleCreateTag} className="flex items-end gap-2">
          <div className="flex-1">
            <input
              type="text"
              value={newTagName}
              onChange={(e) => setNewTagName(e.target.value)}
              placeholder="Tag name"
              className="ui-input"
              autoFocus
            />
          </div>
          <div>
            <input
              type="color"
              value={newTagColor}
              onChange={(e) => setNewTagColor(e.target.value)}
              className="h-10 w-16 cursor-pointer rounded-md border border-[var(--border)] bg-[var(--surface)]"
              title="Tag color"
            />
          </div>
          <button
            type="submit"
            disabled={creating || !newTagName.trim()}
            className="ui-btn ui-btn-primary px-4 py-2 disabled:cursor-not-allowed disabled:opacity-60"
          >
            {creating ? 'Creating...' : 'Add'}
          </button>
          <button
            type="button"
            onClick={() => {
              setShowNewTagForm(false);
              setNewTagName('');
              setNewTagColor(colors.primary);
            }}
            className="ui-btn ui-btn-secondary px-4 py-2"
          >
            Cancel
          </button>
        </form>
      )}
    </div>
  );
}
