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

import { useState } from 'react';
import { useTags } from '../hooks/useTags';
import { useToastContext } from '../App';
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('#3B82F6');
  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('#3B82F6');
      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-gray-600">Loading tags...</div>;
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-md p-3">
        <p className="text-red-700 text-sm">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={`
                px-3 py-1 rounded-full text-sm font-medium transition-colors
                ${isSelected 
                  ? 'bg-blue-500 text-white' 
                  : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                }
              `}
              style={
                isSelected && tag.color 
                  ? { backgroundColor: tag.color } 
                  : {}
              }
            >
              {tag.name}
            </button>
          );
        })}
      </div>

      {!showNewTagForm ? (
        <button
          type="button"
          onClick={() => setShowNewTagForm(true)}
          className="text-blue-600 hover:text-blue-700 text-sm font-medium"
        >
          + Create new tag
        </button>
      ) : (
        <form onSubmit={handleCreateTag} className="flex gap-2 items-end">
          <div className="flex-1">
            <input
              type="text"
              value={newTagName}
              onChange={(e) => setNewTagName(e.target.value)}
              placeholder="Tag name"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              autoFocus
            />
          </div>
          <div>
            <input
              type="color"
              value={newTagColor}
              onChange={(e) => setNewTagColor(e.target.value)}
              className="h-10 w-16 border border-gray-300 rounded-md cursor-pointer"
              title="Tag color"
            />
          </div>
          <button
            type="submit"
            disabled={creating || !newTagName.trim()}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
          >
            {creating ? 'Creating...' : 'Add'}
          </button>
          <button
            type="button"
            onClick={() => {
              setShowNewTagForm(false);
              setNewTagName('');
              setNewTagColor('#3B82F6');
            }}
            className="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300"
          >
            Cancel
          </button>
        </form>
      )}
    </div>
  );
}
