import React, { useState, useEffect } from 'react';
import { 
  CogIcon, 
  ArrowPathIcon, 
  CheckIcon, 
  XMarkIcon,
  InformationCircleIcon 
} from '@heroicons/react/24/outline';
import { AiClassification } from '../../types/aiClassification';
import { TemplateSegmentWeightHelper } from '../../types/template';
import { TemplateSegmentWeightService } from '../../services/templateSegmentWeightService';
import { AiClassificationService } from '../../services/aiClassificationService';

interface TemplateSegmentWeightEditorProps {
  /** 模板ID */
  templateId: string;
  /** 轨道片段ID */
  trackSegmentId: string;
  /** 片段名称 */
  segmentName: string;
  /** 是否禁用编辑 */
  disabled?: boolean;
  /** 权重更新回调 */
  onWeightsUpdated?: (weights: Record<string, number>) => void;
  /** 自定义样式类名 */
  className?: string;
}

/**
 * 模板片段权重配置编辑器组件
 * 遵循前端开发规范的组件设计，提供直观的权重配置界面
 */
export const TemplateSegmentWeightEditor: React.FC<TemplateSegmentWeightEditorProps> = ({
  templateId,
  trackSegmentId,
  segmentName,
  disabled = false,
  onWeightsUpdated,
  className = '',
}) => {
  const [isEditing, setIsEditing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [aiClassifications, setAiClassifications] = useState<AiClassification[]>([]);
  const [currentWeights, setCurrentWeights] = useState<Record<string, number>>({});
  const [editingWeights, setEditingWeights] = useState<Record<string, number>>({});
  const [hasCustomWeights, setHasCustomWeights] = useState(false);

  // 加载AI分类和当前权重配置
  useEffect(() => {
    loadData();
  }, [templateId, trackSegmentId]);

  const loadData = async () => {
    try {
      setLoading(true);
      setError(null);

      const [classifications, weights, hasCustom] = await Promise.all([
        AiClassificationService.getAllClassifications(),
        TemplateSegmentWeightService.getSegmentWeightsWithDefaults(templateId, trackSegmentId),
        TemplateSegmentWeightService.hasCustomSegmentWeights(templateId, trackSegmentId),
      ]);

      setAiClassifications(classifications.filter(c => c.is_active));
      setCurrentWeights(weights);
      setEditingWeights(weights);
      setHasCustomWeights(hasCustom);
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载权重配置失败');
    } finally {
      setLoading(false);
    }
  };

  const handleStartEdit = () => {
    if (disabled) return;
    setIsEditing(true);
    setEditingWeights({ ...currentWeights });
    setError(null);
  };

  const handleSave = async () => {
    try {
      setLoading(true);
      setError(null);

      // 验证权重值
      for (const [classificationId, weight] of Object.entries(editingWeights)) {
        if (!TemplateSegmentWeightHelper.validateWeight(weight)) {
          setError(`分类 ${classificationId} 的权重值必须在 0-100 之间`);
          return;
        }
      }

      // 保存权重配置
      await TemplateSegmentWeightService.setSegmentWeights(
        templateId,
        trackSegmentId,
        editingWeights
      );

      setCurrentWeights({ ...editingWeights });
      setHasCustomWeights(true);
      setIsEditing(false);
      
      onWeightsUpdated?.(editingWeights);
    } catch (err) {
      setError(err instanceof Error ? err.message : '保存权重配置失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    setIsEditing(false);
    setEditingWeights({ ...currentWeights });
    setError(null);
  };

  const handleResetToGlobal = async () => {
    try {
      setLoading(true);
      setError(null);

      await TemplateSegmentWeightService.resetSegmentWeightsToGlobal(templateId, trackSegmentId);
      await loadData(); // 重新加载数据
      
      onWeightsUpdated?.(currentWeights);
    } catch (err) {
      setError(err instanceof Error ? err.message : '重置权重配置失败');
    } finally {
      setLoading(false);
    }
  };

  const handleWeightChange = (classificationId: string, weight: number) => {
    setEditingWeights(prev => ({
      ...prev,
      [classificationId]: weight,
    }));
  };

  const getWeightDisplayInfo = (weight: number) => {
    return {
      text: TemplateSegmentWeightHelper.getWeightDisplayText(weight),
      colorClass: TemplateSegmentWeightHelper.getWeightColorClass(weight),
    };
  };

  if (loading && !isEditing) {
    return (
      <div className={`flex items-center space-x-2 ${className}`}>
        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
        <span className="text-sm text-gray-600">加载权重配置...</span>
      </div>
    );
  }

  if (!isEditing) {
    return (
      <div className={`space-y-2 ${className}`}>
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <span className="text-sm font-medium text-gray-700">
              片段权重配置
            </span>
            {hasCustomWeights && (
              <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                自定义
              </span>
            )}
          </div>
          
          <div className="flex items-center space-x-1">
            {!disabled && (
              <>
                <button
                  onClick={handleStartEdit}
                  className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
                  title="编辑权重配置"
                >
                  <CogIcon className="w-4 h-4" />
                </button>
                {hasCustomWeights && (
                  <button
                    onClick={handleResetToGlobal}
                    className="p-1 text-gray-400 hover:text-orange-600 transition-colors"
                    title="重置为全局权重"
                  >
                    <ArrowPathIcon className="w-4 h-4" />
                  </button>
                )}
              </>
            )}
          </div>
        </div>

        {/* 权重预览 */}
        <div className="grid grid-cols-2 gap-2 text-xs">
          {aiClassifications.slice(0, 4).map((classification) => {
            const weight = currentWeights[classification.id] || 0;
            const displayInfo = getWeightDisplayInfo(weight);
            
            return (
              <div key={classification.id} className="flex justify-between items-center">
                <span className="text-gray-600 truncate">{classification.name}</span>
                <span className={`font-medium ${displayInfo.colorClass}`}>
                  {weight}
                </span>
              </div>
            );
          })}
          {aiClassifications.length > 4 && (
            <div className="col-span-2 text-center text-gray-500">
              +{aiClassifications.length - 4} 个分类...
            </div>
          )}
        </div>

        {error && (
          <div className="text-xs text-red-700 bg-red-100 border border-red-200 p-2 rounded-md">
            ⚠️ {error}
          </div>
        )}
      </div>
    );
  }

  return (
    <div className={`space-y-4 ${className}`}>
      <div className="flex items-center justify-between">
        <div>
          <h4 className="text-sm font-medium text-gray-900">
            配置片段权重: {segmentName}
          </h4>
          <p className="text-xs text-gray-500 mt-1">
            设置不同AI分类的匹配权重，权重越高优先级越高
          </p>
        </div>
        
        <div className="flex items-center space-x-2">
          <button
            onClick={handleSave}
            disabled={loading}
            className="inline-flex items-center px-3 py-1 bg-blue-600 text-white text-xs font-medium rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
          >
            <CheckIcon className="w-3 h-3 mr-1" />
            {loading ? '保存中...' : '保存'}
          </button>
          <button
            onClick={handleCancel}
            disabled={loading}
            className="inline-flex items-center px-3 py-1 bg-gray-100 text-gray-700 text-xs font-medium rounded-md hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
          >
            <XMarkIcon className="w-3 h-3 mr-1" />
            取消
          </button>
        </div>
      </div>

      {/* 权重配置表单 */}
      <div className="space-y-3 max-h-64 overflow-y-auto border border-gray-200 rounded-md p-3 bg-gray-50">
        {aiClassifications.map((classification) => {
          const weight = editingWeights[classification.id] || 0;
          const displayInfo = getWeightDisplayInfo(weight);
          
          return (
            <div key={classification.id} className="space-y-2">
              <div className="flex items-center justify-between">
                <div className="flex-1">
                  <label className="block text-xs font-medium text-gray-700">
                    {classification.name}
                  </label>
                  {classification.description && (
                    <p className="text-xs text-gray-500 mt-1">
                      {classification.description}
                    </p>
                  )}
                </div>
                <div className="flex items-center space-x-2">
                  <span className={`text-xs font-medium ${displayInfo.colorClass}`}>
                    {displayInfo.text}
                  </span>
                  <span className="text-xs text-gray-500">({weight})</span>
                </div>
              </div>
              
              <div className="flex items-center space-x-2">
                <input
                  type="range"
                  min="0"
                  max="100"
                  step="1"
                  value={weight}
                  onChange={(e) => handleWeightChange(classification.id, parseInt(e.target.value))}
                  className="flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
                />
                <input
                  type="number"
                  min="0"
                  max="100"
                  value={weight}
                  onChange={(e) => handleWeightChange(classification.id, parseInt(e.target.value) || 0)}
                  className="w-16 px-2 py-1 text-xs border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
            </div>
          );
        })}
      </div>

      {/* 帮助信息 */}
      <div className="flex items-start space-x-2 text-xs text-gray-600 bg-blue-50 border border-blue-200 p-2 rounded-md">
        <InformationCircleIcon className="w-4 h-4 text-blue-500 mt-0.5 flex-shrink-0" />
        <div>
          <p className="font-medium">权重配置说明：</p>
          <ul className="mt-1 space-y-1 list-disc list-inside">
            <li>权重范围：0-100，数值越大优先级越高</li>
            <li>在按顺序匹配时，系统会优先使用高权重分类的素材</li>
            <li>如果不设置自定义权重，将使用全局默认权重</li>
          </ul>
        </div>
      </div>

      {error && (
        <div className="text-xs text-red-700 bg-red-100 border border-red-200 p-2 rounded-md">
          ⚠️ {error}
        </div>
      )}
    </div>
  );
};
