import React, { useState, useEffect } from 'react';
import { CogIcon, ArrowPathIcon } from '@heroicons/react/24/outline';
import { TemplateSegmentWeightHelper, SegmentMatchingRuleHelper } from '../../types/template';
import { TemplateSegmentWeightService } from '../../services/templateSegmentWeightService';

interface SegmentWeightIndicatorProps {
  /** 模板ID */
  templateId: string;
  /** 轨道片段ID */
  trackSegmentId: string;
  /** 片段匹配规则 - 用于确定实际选择的分类 */
  segmentMatchingRule?: any;
  /** 是否禁用编辑 */
  disabled?: boolean;
  /** 点击编辑按钮的回调 */
  onEditClick?: () => void;
  /** 权重更新回调 */
  onWeightsUpdated?: () => void;
  /** 自定义样式类名 */
  className?: string;
}

/**
 * 片段权重指示器组件
 * 用于在列表中显示片段的权重配置状态
 */
export const SegmentWeightIndicator: React.FC<SegmentWeightIndicatorProps> = ({
  templateId,
  trackSegmentId,
  segmentMatchingRule,
  disabled = false,
  onEditClick,
  onWeightsUpdated,
  className = '',
}) => {
  const [loading, setLoading] = useState(false);
  const [hasCustomWeights, setHasCustomWeights] = useState(false);
  const [weightSummary, setWeightSummary] = useState<{
    totalClassifications: number;
    averageWeight: number;
    maxWeight: number;
  } | null>(null);

  useEffect(() => {
    loadWeightInfo();
  }, [templateId, trackSegmentId]);

  const loadWeightInfo = async () => {
    try {
      setLoading(true);

      const hasCustom = await TemplateSegmentWeightService.hasCustomSegmentWeights(templateId, trackSegmentId);
      setHasCustomWeights(hasCustom);

      // 计算权重摘要 - 只统计实际选择的分类
      let relevantWeights: Record<string, number> = {};

      if (segmentMatchingRule && SegmentMatchingRuleHelper.isPriorityOrder(segmentMatchingRule)) {
        // 对于按顺序匹配规则，只获取选择的分类权重
        const selectedCategoryIds = typeof segmentMatchingRule === 'object' && 'PriorityOrder' in segmentMatchingRule
          ? segmentMatchingRule.PriorityOrder.category_ids
          : [];

        if (selectedCategoryIds.length > 0) {
          relevantWeights = await TemplateSegmentWeightService.getSegmentWeightsForCategories(
            templateId,
            trackSegmentId,
            selectedCategoryIds
          );
        }
      } else {
        // 对于其他规则类型，不显示权重信息（因为不相关）
        relevantWeights = {};
      }

      const weightValues = Object.values(relevantWeights);
      if (weightValues.length > 0) {
        const totalClassifications = weightValues.length;
        const averageWeight = weightValues.reduce((sum, weight) => sum + weight, 0) / totalClassifications;
        const maxWeight = Math.max(...weightValues);

        setWeightSummary({
          totalClassifications,
          averageWeight: Math.round(averageWeight * 10) / 10,
          maxWeight,
        });
      } else {
        setWeightSummary(null);
      }
    } catch (error) {
      console.error('加载权重信息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleResetToGlobal = async (e: React.MouseEvent) => {
    e.stopPropagation();
    
    try {
      setLoading(true);
      await TemplateSegmentWeightService.resetSegmentWeightsToGlobal(templateId, trackSegmentId);
      await loadWeightInfo();
      onWeightsUpdated?.();
    } catch (error) {
      console.error('重置权重配置失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleEditClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onEditClick?.();
  };

  const getWeightStatusColor = () => {
    if (!weightSummary) return 'text-gray-400';
    
    if (hasCustomWeights) {
      return 'text-blue-600';
    }
    
    if (weightSummary.averageWeight > 50) {
      return 'text-green-600';
    } else if (weightSummary.averageWeight > 20) {
      return 'text-yellow-600';
    } else {
      return 'text-gray-600';
    }
  };

  const getWeightStatusText = () => {
    if (!weightSummary) return '未配置';
    
    if (hasCustomWeights) {
      return `自定义 (平均: ${weightSummary.averageWeight})`;
    }
    
    return `全局 (平均: ${weightSummary.averageWeight})`;
  };

  if (loading) {
    return (
      <div className={`flex items-center space-x-1 ${className}`}>
        <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-blue-600"></div>
        <span className="text-xs text-gray-500">加载中...</span>
      </div>
    );
  }

  return (
    <div className={`flex items-center space-x-2 ${className}`}>
      {/* 权重状态指示器 */}
      <div className="flex items-center space-x-1">
        <div className={`w-2 h-2 rounded-full ${hasCustomWeights ? 'bg-blue-500' : 'bg-gray-400'}`}></div>
        <span className={`text-xs font-medium ${getWeightStatusColor()}`}>
          {getWeightStatusText()}
        </span>
      </div>

      {/* 权重详情 */}
      {weightSummary && (
        <div className="flex items-center space-x-1 text-xs text-gray-500">
          <span>最高: {weightSummary.maxWeight}</span>
          <span>•</span>
          <span>{weightSummary.totalClassifications} 分类</span>
        </div>
      )}

      {/* 操作按钮 */}
      {!disabled && (
        <div className="flex items-center space-x-1">
          <button
            onClick={handleEditClick}
            className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
            title="编辑权重配置"
          >
            <CogIcon className="w-3 h-3" />
          </button>
          
          {hasCustomWeights && (
            <button
              onClick={handleResetToGlobal}
              className="p-1 text-gray-400 hover:text-orange-600 transition-colors"
              title="重置为全局权重"
            >
              <ArrowPathIcon className="w-3 h-3" />
            </button>
          )}
        </div>
      )}
    </div>
  );
};

/**
 * 权重配置快速预览组件
 * 用于在悬停时显示详细的权重信息
 */
interface WeightPreviewTooltipProps {
  templateId: string;
  trackSegmentId: string;
  segmentMatchingRule?: any; // 添加匹配规则参数
  children: React.ReactNode;
}

export const WeightPreviewTooltip: React.FC<WeightPreviewTooltipProps> = ({
  templateId,
  trackSegmentId,
  segmentMatchingRule,
  children,
}) => {
  const [showTooltip, setShowTooltip] = useState(false);
  const [weights, setWeights] = useState<Record<string, number>>({});
  const [loading, setLoading] = useState(false);

  const loadWeights = async () => {
    if (loading) return;

    try {
      setLoading(true);

      // 只获取实际选中的分类权重
      let relevantWeights: Record<string, number> = {};

      if (segmentMatchingRule && SegmentMatchingRuleHelper.isPriorityOrder(segmentMatchingRule)) {
        // 对于按顺序匹配规则，只获取选择的分类权重
        const selectedCategoryIds = typeof segmentMatchingRule === 'object' && 'PriorityOrder' in segmentMatchingRule
          ? segmentMatchingRule.PriorityOrder.category_ids
          : [];

        if (selectedCategoryIds.length > 0) {
          relevantWeights = await TemplateSegmentWeightService.getSegmentWeightsForCategories(
            templateId,
            trackSegmentId,
            selectedCategoryIds
          );
        }
      } else {
        // 对于其他规则类型，不显示权重信息
        relevantWeights = {};
      }

      setWeights(relevantWeights);
    } catch (error) {
      console.error('加载权重预览失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleMouseEnter = () => {
    setShowTooltip(true);
    loadWeights();
  };

  const handleMouseLeave = () => {
    setShowTooltip(false);
  };

  return (
    <div 
      className="relative"
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      {children}
      
      {showTooltip && (
        <div className="absolute z-50 bottom-full left-0 mb-2 p-3 bg-white border border-gray-200 rounded-lg shadow-lg min-w-48">
          <div className="text-xs font-medium text-gray-900 mb-2">权重配置预览</div>
          
          {loading ? (
            <div className="flex items-center space-x-2">
              <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-blue-600"></div>
              <span className="text-xs text-gray-500">加载中...</span>
            </div>
          ) : (
            <div className="space-y-1">
              {Object.entries(weights).slice(0, 5).map(([classificationId, weight]) => {
                const displayInfo = TemplateSegmentWeightHelper.getWeightDisplayText(weight);
                const colorClass = TemplateSegmentWeightHelper.getWeightColorClass(weight);
                
                return (
                  <div key={classificationId} className="flex justify-between items-center text-xs">
                    <span className="text-gray-600 truncate">{classificationId}</span>
                    <span className={`font-medium ${colorClass}`}>
                      {weight} ({displayInfo})
                    </span>
                  </div>
                );
              })}
              
              {Object.keys(weights).length > 5 && (
                <div className="text-xs text-gray-500 text-center pt-1 border-t border-gray-100">
                  +{Object.keys(weights).length - 5} 个分类...
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
};
