import React, { useState, useEffect } from 'react';
import { 
  Filter, 
  X, 
  Clock, 
  Tag, 
  Users, 
  ArrowUpDown, 
  ArrowUp, 
  ArrowDown,
  RotateCcw
} from 'lucide-react';
import { 
  MaterialSegmentQuery, 
  SegmentSortField, 
  SortDirection 
} from '../types/materialSegmentView';
import { CustomSelect } from './CustomSelect';

interface MaterialSegmentFiltersProps {
  currentQuery: MaterialSegmentQuery | null;
  onQueryUpdate: (updates: Partial<MaterialSegmentQuery>) => void;
  onClearQuery: () => void;
  onSort: (sortBy: SegmentSortField, direction: SortDirection) => void;
}

/**
 * MaterialSegment过滤器组件
 * 遵循 Tauri 开发规范的组件设计模式
 */
export const MaterialSegmentFilters: React.FC<MaterialSegmentFiltersProps> = ({
  currentQuery,
  onQueryUpdate,
  onClearQuery,
}) => {
  const [localFilters, setLocalFilters] = useState({
    categoryFilter: currentQuery?.category_filter || '',
    modelIdFilter: currentQuery?.model_id_filter || '',
    minDuration: currentQuery?.min_duration?.toString() || '',
    maxDuration: currentQuery?.max_duration?.toString() || '',
    sortBy: currentQuery?.sort_by || SegmentSortField.CreatedAt,
    sortDirection: currentQuery?.sort_direction || SortDirection.Descending,
    pageSize: currentQuery?.page_size?.toString() || '20',
  });

  // 同步外部查询状态到本地状态
  useEffect(() => {
    if (currentQuery) {
      setLocalFilters({
        categoryFilter: currentQuery.category_filter || '',
        modelIdFilter: currentQuery.model_id_filter || '',
        minDuration: currentQuery.min_duration?.toString() || '',
        maxDuration: currentQuery.max_duration?.toString() || '',
        sortBy: currentQuery.sort_by || SegmentSortField.CreatedAt,
        sortDirection: currentQuery.sort_direction || SortDirection.Descending,
        pageSize: currentQuery.page_size?.toString() || '20',
      });
    }
  }, [currentQuery]);

  // 应用过滤器
  const applyFilters = () => {
    const updates: Partial<MaterialSegmentQuery> = {};

    if (localFilters.categoryFilter) {
      updates.category_filter = localFilters.categoryFilter;
    }

    if (localFilters.modelIdFilter) {
      updates.model_id_filter = localFilters.modelIdFilter;
    }

    if (localFilters.minDuration) {
      const minDuration = parseFloat(localFilters.minDuration);
      if (!isNaN(minDuration) && minDuration > 0) {
        updates.min_duration = minDuration;
      }
    }

    if (localFilters.maxDuration) {
      const maxDuration = parseFloat(localFilters.maxDuration);
      if (!isNaN(maxDuration) && maxDuration > 0) {
        updates.max_duration = maxDuration;
      }
    }

    if (localFilters.sortBy) {
      updates.sort_by = localFilters.sortBy;
    }

    if (localFilters.sortDirection) {
      updates.sort_direction = localFilters.sortDirection;
    }

    if (localFilters.pageSize) {
      const pageSize = parseInt(localFilters.pageSize);
      if (!isNaN(pageSize) && pageSize > 0) {
        updates.page_size = pageSize;
      }
    }

    onQueryUpdate(updates);
  };

  // 清除所有过滤器
  const clearAllFilters = () => {
    setLocalFilters({
      categoryFilter: '',
      modelIdFilter: '',
      minDuration: '',
      maxDuration: '',
      sortBy: SegmentSortField.CreatedAt,
      sortDirection: SortDirection.Descending,
      pageSize: '20',
    });
    onClearQuery();
  };

  // 处理排序
  // const handleSort = (sortBy: SegmentSortField) => {
  //   const newDirection = localFilters.sortBy === sortBy && localFilters.sortDirection === SortDirection.Ascending
  //     ? SortDirection.Descending
  //     : SortDirection.Ascending;
    
  //   setLocalFilters(prev => ({
  //     ...prev,
  //     sortBy,
  //     sortDirection: newDirection,
  //   }));

  //   onSort(sortBy, newDirection);
  // };

  // 排序选项
  const sortOptions = [
    { value: SegmentSortField.CreatedAt, label: '创建时间' },
    { value: SegmentSortField.Duration, label: '时长' },
    { value: SegmentSortField.Category, label: '分类' },
    { value: SegmentSortField.Model, label: '模特' },
    { value: SegmentSortField.Confidence, label: '置信度' },
  ];

  // 页面大小选项
  const pageSizeOptions = [
    { value: '10', label: '10 条/页' },
    { value: '20', label: '20 条/页' },
    { value: '50', label: '50 条/页' },
    { value: '100', label: '100 条/页' },
  ];

  // 检查是否有活动的过滤器
  const hasActiveFilters = localFilters.categoryFilter || 
                          localFilters.modelIdFilter || 
                          localFilters.minDuration || 
                          localFilters.maxDuration;

  return (
    <div className="space-y-4">
      {/* 过滤器标题 */}
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium text-gray-900 flex items-center">
          <Filter className="w-4 h-4 mr-2" />
          过滤条件
        </h3>
        {hasActiveFilters && (
          <button
            onClick={clearAllFilters}
            className="text-sm text-red-600 hover:text-red-800 flex items-center transition-colors"
          >
            <RotateCcw className="w-4 h-4 mr-1" />
            清除所有
          </button>
        )}
      </div>

      {/* 过滤器网格 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* 分类过滤 */}
        <div>
          <label className="block text-xs font-medium text-gray-700 mb-1">
            <Tag className="w-3 h-3 inline mr-1" />
            分类
          </label>
          <input
            type="text"
            placeholder="输入分类名称"
            value={localFilters.categoryFilter}
            onChange={(e) => setLocalFilters(prev => ({ ...prev, categoryFilter: e.target.value }))}
            className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>

        {/* 模特过滤 */}
        <div>
          <label className="block text-xs font-medium text-gray-700 mb-1">
            <Users className="w-3 h-3 inline mr-1" />
            模特ID
          </label>
          <input
            type="text"
            placeholder="输入模特ID"
            value={localFilters.modelIdFilter}
            onChange={(e) => setLocalFilters(prev => ({ ...prev, modelIdFilter: e.target.value }))}
            className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>

        {/* 最小时长 */}
        <div>
          <label className="block text-xs font-medium text-gray-700 mb-1">
            <Clock className="w-3 h-3 inline mr-1" />
            最小时长(秒)
          </label>
          <input
            type="number"
            placeholder="0"
            min="0"
            step="0.1"
            value={localFilters.minDuration}
            onChange={(e) => setLocalFilters(prev => ({ ...prev, minDuration: e.target.value }))}
            className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>

        {/* 最大时长 */}
        <div>
          <label className="block text-xs font-medium text-gray-700 mb-1">
            <Clock className="w-3 h-3 inline mr-1" />
            最大时长(秒)
          </label>
          <input
            type="number"
            placeholder="无限制"
            min="0"
            step="0.1"
            value={localFilters.maxDuration}
            onChange={(e) => setLocalFilters(prev => ({ ...prev, maxDuration: e.target.value }))}
            className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>
      </div>

      {/* 排序和分页 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 pt-4 border-t border-gray-200">
        {/* 排序字段 */}
        <div>
          <label className="block text-xs font-medium text-gray-700 mb-1">
            <ArrowUpDown className="w-3 h-3 inline mr-1" />
            排序字段
          </label>
          <CustomSelect
            value={localFilters.sortBy}
            onChange={(value) => setLocalFilters(prev => ({ ...prev, sortBy: value as SegmentSortField }))}
            options={sortOptions}
            placeholder="选择排序字段"
          />
        </div>

        {/* 排序方向 */}
        <div>
          <label className="block text-xs font-medium text-gray-700 mb-1">
            排序方向
          </label>
          <div className="flex space-x-2">
            <button
              onClick={() => setLocalFilters(prev => ({ ...prev, sortDirection: SortDirection.Ascending }))}
              className={`flex-1 px-3 py-2 text-sm rounded-md border transition-colors ${
                localFilters.sortDirection === SortDirection.Ascending
                  ? 'bg-blue-50 text-blue-600 border-blue-200'
                  : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'
              }`}
            >
              <ArrowUp className="w-4 h-4 inline mr-1" />
              升序
            </button>
            <button
              onClick={() => setLocalFilters(prev => ({ ...prev, sortDirection: SortDirection.Descending }))}
              className={`flex-1 px-3 py-2 text-sm rounded-md border transition-colors ${
                localFilters.sortDirection === SortDirection.Descending
                  ? 'bg-blue-50 text-blue-600 border-blue-200'
                  : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'
              }`}
            >
              <ArrowDown className="w-4 h-4 inline mr-1" />
              降序
            </button>
          </div>
        </div>

        {/* 页面大小 */}
        <div>
          <label className="block text-xs font-medium text-gray-700 mb-1">
            每页显示
          </label>
          <CustomSelect
            value={localFilters.pageSize}
            onChange={(value) => setLocalFilters(prev => ({ ...prev, pageSize: value }))}
            options={pageSizeOptions}
            placeholder="选择页面大小"
          />
        </div>
      </div>

      {/* 操作按钮 */}
      <div className="flex items-center justify-end space-x-3 pt-4 border-t border-gray-200">
        <button
          onClick={clearAllFilters}
          className="px-4 py-2 text-sm text-gray-600 hover:text-gray-800 transition-colors"
        >
          重置
        </button>
        <button
          onClick={applyFilters}
          className="px-4 py-2 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
        >
          应用过滤器
        </button>
      </div>

      {/* 活动过滤器显示 */}
      {hasActiveFilters && (
        <div className="flex flex-wrap gap-2 pt-2">
          {localFilters.categoryFilter && (
            <span className="inline-flex items-center px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded-full">
              分类: {localFilters.categoryFilter}
              <button
                onClick={() => {
                  setLocalFilters(prev => ({ ...prev, categoryFilter: '' }));
                  onQueryUpdate({ category_filter: undefined });
                }}
                className="ml-1 text-blue-600 hover:text-blue-800"
              >
                <X className="w-3 h-3" />
              </button>
            </span>
          )}
          {localFilters.modelIdFilter && (
            <span className="inline-flex items-center px-2 py-1 text-xs bg-green-100 text-green-800 rounded-full">
              模特: {localFilters.modelIdFilter}
              <button
                onClick={() => {
                  setLocalFilters(prev => ({ ...prev, modelIdFilter: '' }));
                  onQueryUpdate({ model_id_filter: undefined });
                }}
                className="ml-1 text-green-600 hover:text-green-800"
              >
                <X className="w-3 h-3" />
              </button>
            </span>
          )}
          {localFilters.minDuration && (
            <span className="inline-flex items-center px-2 py-1 text-xs bg-purple-100 text-purple-800 rounded-full">
              最小时长: {localFilters.minDuration}s
              <button
                onClick={() => {
                  setLocalFilters(prev => ({ ...prev, minDuration: '' }));
                  onQueryUpdate({ min_duration: undefined });
                }}
                className="ml-1 text-purple-600 hover:text-purple-800"
              >
                <X className="w-3 h-3" />
              </button>
            </span>
          )}
          {localFilters.maxDuration && (
            <span className="inline-flex items-center px-2 py-1 text-xs bg-purple-100 text-purple-800 rounded-full">
              最大时长: {localFilters.maxDuration}s
              <button
                onClick={() => {
                  setLocalFilters(prev => ({ ...prev, maxDuration: '' }));
                  onQueryUpdate({ max_duration: undefined });
                }}
                className="ml-1 text-purple-600 hover:text-purple-800"
              >
                <X className="w-3 h-3" />
              </button>
            </span>
          )}
        </div>
      )}
    </div>
  );
};
