import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Search, Plus, X, ChevronDown } from 'lucide-react';
import {
  CustomTagWithCategory,
  CustomTagCategory,
  TagSelectorProps,
  CreateCustomTagRequest,
  CreateCustomTagCategoryRequest,
} from '../types/customTag';
import { CustomTagService } from '../services/customTagService';

/**
 * 自定义标签选择器组件
 * 遵循 Tauri 开发规范和前端开发标准
 */
export const CustomTagSelector: React.FC<TagSelectorProps> = ({
  selectedTagIds,
  onSelectionChange,
  multiple = true,
  showCategoryFilter = true,
  showSearch = true,
  allowCreate = true,
  placeholder = '选择标签...',
  disabled = false,
}) => {
  const [tags, setTags] = useState<CustomTagWithCategory[]>([]);
  const [categories, setCategories] = useState<CustomTagCategory[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategoryId, setSelectedCategoryId] = useState<string>('');
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isCreating, setIsCreating] = useState(false);
  const [newTagName, setNewTagName] = useState('');
  const [newCategoryName, setNewCategoryName] = useState('');
  const [showCreateCategory, setShowCreateCategory] = useState(false);

  // 加载数据
  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      const [tagsData, categoriesData] = await Promise.all([
        CustomTagService.getTags({ active_only: true }),
        CustomTagService.getCategories(true),
      ]);
      setTags(tagsData);
      setCategories(categoriesData);
    } catch (error) {
      console.error('Failed to load tag data:', error);
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // 过滤标签
  const filteredTags = useMemo(() => {
    let filtered = tags;

    // 按分类过滤
    if (selectedCategoryId) {
      filtered = filtered.filter(tag => tag.category.id === selectedCategoryId);
    }

    // 按搜索查询过滤
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(tag =>
        tag.tag.name.toLowerCase().includes(query) ||
        tag.category.name.toLowerCase().includes(query) ||
        (tag.tag.description && tag.tag.description.toLowerCase().includes(query))
      );
    }

    return filtered;
  }, [tags, selectedCategoryId, searchQuery]);

  // 获取选中的标签
  const selectedTags = useMemo(() => {
    return tags.filter(tag => selectedTagIds.includes(tag.tag.id));
  }, [tags, selectedTagIds]);

  // 处理标签选择
  const handleTagToggle = useCallback((tagId: string) => {
    if (disabled) return;

    let newSelectedIds: string[];
    if (multiple) {
      newSelectedIds = selectedTagIds.includes(tagId)
        ? selectedTagIds.filter(id => id !== tagId)
        : [...selectedTagIds, tagId];
    } else {
      newSelectedIds = selectedTagIds.includes(tagId) ? [] : [tagId];
      setIsDropdownOpen(false);
    }
    onSelectionChange(newSelectedIds);
  }, [selectedTagIds, onSelectionChange, multiple, disabled]);

  // 移除标签
  const handleRemoveTag = useCallback((tagId: string, event: React.MouseEvent) => {
    event.stopPropagation();
    if (disabled) return;
    
    const newSelectedIds = selectedTagIds.filter(id => id !== tagId);
    onSelectionChange(newSelectedIds);
  }, [selectedTagIds, onSelectionChange, disabled]);

  // 创建新标签
  const handleCreateTag = useCallback(async () => {
    if (!newTagName.trim() || !selectedCategoryId) return;

    setIsCreating(true);
    try {
      const request: CreateCustomTagRequest = {
        category_id: selectedCategoryId,
        name: newTagName.trim(),
      };

      const newTag = await CustomTagService.createTag(request);
      
      // 重新加载数据
      await loadData();
      
      // 自动选择新创建的标签
      if (multiple) {
        onSelectionChange([...selectedTagIds, newTag.id]);
      } else {
        onSelectionChange([newTag.id]);
        setIsDropdownOpen(false);
      }

      setNewTagName('');
    } catch (error) {
      console.error('Failed to create tag:', error);
    } finally {
      setIsCreating(false);
    }
  }, [newTagName, selectedCategoryId, selectedTagIds, onSelectionChange, multiple, loadData]);

  // 创建新分类
  const handleCreateCategory = useCallback(async () => {
    if (!newCategoryName.trim()) return;

    setIsCreating(true);
    try {
      const request: CreateCustomTagCategoryRequest = {
        name: newCategoryName.trim(),
      };

      const newCategory = await CustomTagService.createCategory(request);
      
      // 重新加载数据
      await loadData();
      
      // 自动选择新创建的分类
      setSelectedCategoryId(newCategory.id);
      setNewCategoryName('');
      setShowCreateCategory(false);
    } catch (error) {
      console.error('Failed to create category:', error);
    } finally {
      setIsCreating(false);
    }
  }, [newCategoryName, loadData]);

  return (
    <div className="custom-tag-selector">
      {/* 选中的标签显示 */}
      <div 
        className={`tag-selector-input ${disabled ? 'disabled' : ''} ${isDropdownOpen ? 'open' : ''}`}
        onClick={() => !disabled && setIsDropdownOpen(!isDropdownOpen)}
      >
        <div className="selected-tags">
          {selectedTags.length > 0 ? (
            selectedTags.map(tag => (
              <span
                key={tag.tag.id}
                className="selected-tag"
                style={{ backgroundColor: CustomTagService.getTagColor(tag) }}
              >
                {tag.tag.name}
                {!disabled && (
                  <button
                    className="remove-tag-btn"
                    onClick={(e) => handleRemoveTag(tag.tag.id, e)}
                    type="button"
                  >
                    <X className="w-3 h-3" />
                  </button>
                )}
              </span>
            ))
          ) : (
            <span className="placeholder">{placeholder}</span>
          )}
        </div>
        {!disabled && (
          <ChevronDown className={`dropdown-icon ${isDropdownOpen ? 'open' : ''}`} />
        )}
      </div>

      {/* 下拉选择面板 */}
      {isDropdownOpen && !disabled && (
        <div className="tag-dropdown">
          {/* 搜索和过滤 */}
          <div className="dropdown-header">
            {showSearch && (
              <div className="search-box">
                <Search className="w-4 h-4 search-icon" />
                <input
                  type="text"
                  placeholder="搜索标签..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="search-input"
                />
              </div>
            )}

            {showCategoryFilter && (
              <div className="category-filter">
                <select
                  value={selectedCategoryId}
                  onChange={(e) => setSelectedCategoryId(e.target.value)}
                  className="category-select"
                >
                  <option value="">所有分类</option>
                  {categories.map(category => (
                    <option key={category.id} value={category.id}>
                      {category.icon} {category.name}
                    </option>
                  ))}
                </select>
                {allowCreate && (
                  <button
                    className="create-category-btn"
                    onClick={() => setShowCreateCategory(true)}
                    type="button"
                  >
                    <Plus className="w-4 h-4" />
                  </button>
                )}
              </div>
            )}
          </div>

          {/* 标签列表 */}
          <div className="tag-list">
            {isLoading ? (
              <div className="loading">加载中...</div>
            ) : filteredTags.length > 0 ? (
              filteredTags.map(tag => (
                <div
                  key={tag.tag.id}
                  className={`tag-item ${selectedTagIds.includes(tag.tag.id) ? 'selected' : ''}`}
                  onClick={() => handleTagToggle(tag.tag.id)}
                >
                  <div className="tag-content">
                    <span
                      className="tag-color"
                      style={{ backgroundColor: CustomTagService.getTagColor(tag) }}
                    />
                    <span className="tag-name">{tag.tag.name}</span>
                    <span className="tag-category">{tag.category.name}</span>
                  </div>
                  <span className="tag-usage">{tag.tag.usage_count}</span>
                </div>
              ))
            ) : (
              <div className="no-tags">
                {searchQuery ? '未找到匹配的标签' : '暂无标签'}
              </div>
            )}
          </div>

          {/* 创建新标签 */}
          {allowCreate && selectedCategoryId && (
            <div className="create-tag-section">
              <div className="create-tag-input">
                <input
                  type="text"
                  placeholder="输入新标签名称..."
                  value={newTagName}
                  onChange={(e) => setNewTagName(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && handleCreateTag()}
                  className="new-tag-input"
                />
                <button
                  className="create-tag-btn"
                  onClick={handleCreateTag}
                  disabled={!newTagName.trim() || isCreating}
                  type="button"
                >
                  {isCreating ? '创建中...' : '创建'}
                </button>
              </div>
            </div>
          )}

          {/* 创建新分类 */}
          {showCreateCategory && (
            <div className="create-category-section">
              <div className="create-category-input">
                <input
                  type="text"
                  placeholder="输入新分类名称..."
                  value={newCategoryName}
                  onChange={(e) => setNewCategoryName(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && handleCreateCategory()}
                  className="new-category-input"
                />
                <button
                  className="create-category-btn"
                  onClick={handleCreateCategory}
                  disabled={!newCategoryName.trim() || isCreating}
                  type="button"
                >
                  {isCreating ? '创建中...' : '创建'}
                </button>
                <button
                  className="cancel-btn"
                  onClick={() => setShowCreateCategory(false)}
                  type="button"
                >
                  取消
                </button>
              </div>
            </div>
          )}
        </div>
      )}

      <style>{`
        .custom-tag-selector {
          position: relative;
          width: 100%;
        }

        .tag-selector-input {
          min-height: 40px;
          padding: 8px 12px;
          border: 1px solid #e2e8f0;
          border-radius: 6px;
          background: white;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: space-between;
          transition: all 0.2s ease;
        }

        .tag-selector-input:hover {
          border-color: #cbd5e1;
        }

        .tag-selector-input.open {
          border-color: #3b82f6;
          box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        .tag-selector-input.disabled {
          background: #f8fafc;
          cursor: not-allowed;
          opacity: 0.6;
        }

        .selected-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 4px;
          flex: 1;
        }

        .selected-tag {
          display: inline-flex;
          align-items: center;
          gap: 4px;
          padding: 2px 8px;
          background: #3b82f6;
          color: white;
          border-radius: 12px;
          font-size: 12px;
          font-weight: 500;
        }

        .remove-tag-btn {
          background: none;
          border: none;
          color: white;
          cursor: pointer;
          padding: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          transition: background-color 0.2s;
        }

        .remove-tag-btn:hover {
          background: rgba(255, 255, 255, 0.2);
        }

        .placeholder {
          color: #9ca3af;
          font-size: 14px;
        }

        .dropdown-icon {
          width: 16px;
          height: 16px;
          color: #6b7280;
          transition: transform 0.2s ease;
        }

        .dropdown-icon.open {
          transform: rotate(180deg);
        }

        .tag-dropdown {
          position: absolute;
          top: 100%;
          left: 0;
          right: 0;
          z-index: 50;
          background: white;
          border: 1px solid #e2e8f0;
          border-radius: 6px;
          box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
          margin-top: 4px;
          max-height: 300px;
          overflow: hidden;
          display: flex;
          flex-direction: column;
        }

        .dropdown-header {
          padding: 12px;
          border-bottom: 1px solid #f1f5f9;
          display: flex;
          flex-direction: column;
          gap: 8px;
        }

        .search-box {
          position: relative;
        }

        .search-icon {
          position: absolute;
          left: 8px;
          top: 50%;
          transform: translateY(-50%);
          color: #9ca3af;
        }

        .search-input {
          width: 100%;
          padding: 6px 8px 6px 32px;
          border: 1px solid #e2e8f0;
          border-radius: 4px;
          font-size: 14px;
        }

        .category-filter {
          display: flex;
          gap: 8px;
          align-items: center;
        }

        .category-select {
          flex: 1;
          padding: 6px 8px;
          border: 1px solid #e2e8f0;
          border-radius: 4px;
          font-size: 14px;
        }

        .create-category-btn {
          padding: 6px;
          border: 1px solid #e2e8f0;
          border-radius: 4px;
          background: white;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.2s ease;
        }

        .create-category-btn:hover {
          background: #f8fafc;
          border-color: #cbd5e1;
        }

        .tag-list {
          flex: 1;
          overflow-y: auto;
          max-height: 200px;
        }

        .tag-item {
          padding: 8px 12px;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: space-between;
          transition: background-color 0.2s ease;
        }

        .tag-item:hover {
          background: #f8fafc;
        }

        .tag-item.selected {
          background: #eff6ff;
          color: #1d4ed8;
        }

        .tag-content {
          display: flex;
          align-items: center;
          gap: 8px;
          flex: 1;
        }

        .tag-color {
          width: 12px;
          height: 12px;
          border-radius: 50%;
          flex-shrink: 0;
        }

        .tag-name {
          font-weight: 500;
          font-size: 14px;
        }

        .tag-category {
          font-size: 12px;
          color: #6b7280;
        }

        .tag-usage {
          font-size: 12px;
          color: #9ca3af;
          background: #f1f5f9;
          padding: 2px 6px;
          border-radius: 8px;
        }

        .loading, .no-tags {
          padding: 16px;
          text-align: center;
          color: #6b7280;
          font-size: 14px;
        }

        .create-tag-section, .create-category-section {
          padding: 12px;
          border-top: 1px solid #f1f5f9;
        }

        .create-tag-input, .create-category-input {
          display: flex;
          gap: 8px;
          align-items: center;
        }

        .new-tag-input, .new-category-input {
          flex: 1;
          padding: 6px 8px;
          border: 1px solid #e2e8f0;
          border-radius: 4px;
          font-size: 14px;
        }

        .create-tag-btn, .create-category-btn {
          padding: 6px 12px;
          background: #3b82f6;
          color: white;
          border: none;
          border-radius: 4px;
          font-size: 12px;
          cursor: pointer;
          transition: background-color 0.2s;
        }

        .create-tag-btn:hover, .create-category-btn:hover {
          background: #2563eb;
        }

        .create-tag-btn:disabled, .create-category-btn:disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }

        .cancel-btn {
          padding: 6px 12px;
          background: #6b7280;
          color: white;
          border: none;
          border-radius: 4px;
          font-size: 12px;
          cursor: pointer;
          transition: background-color 0.2s;
        }

        .cancel-btn:hover {
          background: #4b5563;
        }
      `}</style>
    </div>
  );
};

export default CustomTagSelector;
