import React, { useState, useEffect } from 'react';
import {
  XMarkIcon,
  DocumentDuplicateIcon,
  ArrowPathIcon,
  CheckIcon,
  ExclamationTriangleIcon,
} 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 BatchWeightConfigModalProps {
  /** 是否显示模态框 */
  isOpen: boolean;
  /** 关闭模态框回调 */
  onClose: () => void;
  /** 目标片段列表 */
  targetSegments: Array<{
    templateId: string;
    trackSegmentId: string;
    segmentName: string;
  }>;
  /** 操作完成回调 */
  onComplete?: () => void;
}

type BatchOperation = 'copy' | 'reset' | 'custom';

/**
 * 批量权重配置模态框组件
 * 支持批量复制、重置和自定义权重配置
 */
export const BatchWeightConfigModal: React.FC<BatchWeightConfigModalProps> = ({
  isOpen,
  onClose,
  targetSegments,
  onComplete,
}) => {
  const [operation, setOperation] = useState<BatchOperation>('copy');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  
  // 复制操作相关状态
  const [sourceTemplateId, setSourceTemplateId] = useState('');
  const [sourceTrackSegmentId, setSourceTrackSegmentId] = useState('');
  
  // 自定义权重相关状态
  const [aiClassifications, setAiClassifications] = useState<AiClassification[]>([]);
  const [customWeights, setCustomWeights] = useState<Record<string, number>>({});

  useEffect(() => {
    if (isOpen) {
      loadAiClassifications();
      resetForm();
    }
  }, [isOpen]);

  const loadAiClassifications = async () => {
    try {
      const classifications = await AiClassificationService.getAllClassifications();
      const activeClassifications = classifications.filter(c => c.is_active);
      setAiClassifications(activeClassifications);
      
      // 初始化自定义权重为全局权重
      const initialWeights: Record<string, number> = {};
      activeClassifications.forEach(classification => {
        initialWeights[classification.id] = classification.weight || 0;
      });
      setCustomWeights(initialWeights);
    } catch (err) {
      setError('加载AI分类失败');
    }
  };

  const resetForm = () => {
    setOperation('copy');
    setError(null);
    setSuccess(null);
    setSourceTemplateId('');
    setSourceTrackSegmentId('');
  };

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

      switch (operation) {
        case 'copy':
          await handleCopyOperation();
          break;
        case 'reset':
          await handleResetOperation();
          break;
        case 'custom':
          await handleCustomOperation();
          break;
      }

      setSuccess(`成功处理 ${targetSegments.length} 个片段的权重配置`);
      onComplete?.();
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCopyOperation = async () => {
    if (!sourceTemplateId || !sourceTrackSegmentId) {
      throw new Error('请指定源片段');
    }

    await TemplateSegmentWeightService.copyWeightsToSegments(
      sourceTemplateId,
      sourceTrackSegmentId,
      targetSegments
    );
  };

  const handleResetOperation = async () => {
    await TemplateSegmentWeightService.resetMultipleSegmentsToGlobal(targetSegments);
  };

  const handleCustomOperation = async () => {
    // 验证权重值
    for (const [classificationId, weight] of Object.entries(customWeights)) {
      if (!TemplateSegmentWeightHelper.validateWeight(weight)) {
        throw new Error(`分类 ${classificationId} 的权重值必须在 0-100 之间`);
      }
    }

    // 批量应用自定义权重
    await Promise.all(
      targetSegments.map(({ templateId, trackSegmentId }) =>
        TemplateSegmentWeightService.setSegmentWeights(templateId, trackSegmentId, customWeights)
      )
    );
  };

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

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto">
      <div className="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onClick={onClose}></div>

        <div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
          <div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            {/* 标题 */}
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-medium text-gray-900">
                批量权重配置
              </h3>
              <button
                onClick={onClose}
                className="text-gray-400 hover:text-gray-600"
              >
                <XMarkIcon className="w-6 h-6" />
              </button>
            </div>

            {/* 目标片段信息 */}
            <div className="mb-6">
              <h4 className="text-sm font-medium text-gray-700 mb-2">
                目标片段 ({targetSegments.length} 个)
              </h4>
              <div className="max-h-24 overflow-y-auto bg-gray-50 border border-gray-200 rounded-md p-2">
                {targetSegments.map((segment, index) => (
                  <div key={index} className="text-xs text-gray-600 py-1">
                    {segment.segmentName}
                  </div>
                ))}
              </div>
            </div>

            {/* 操作选择 */}
            <div className="mb-6">
              <h4 className="text-sm font-medium text-gray-700 mb-3">选择操作</h4>
              <div className="space-y-3">
                {/* 复制权重配置 */}
                <label className="flex items-start space-x-3 cursor-pointer">
                  <input
                    type="radio"
                    name="operation"
                    value="copy"
                    checked={operation === 'copy'}
                    onChange={(e) => setOperation(e.target.value as BatchOperation)}
                    className="mt-1"
                  />
                  <div className="flex-1">
                    <div className="flex items-center space-x-2">
                      <DocumentDuplicateIcon className="w-4 h-4 text-blue-500" />
                      <span className="text-sm font-medium text-gray-900">复制权重配置</span>
                    </div>
                    <p className="text-xs text-gray-500 mt-1">
                      从指定的源片段复制权重配置到目标片段
                    </p>
                    
                    {operation === 'copy' && (
                      <div className="mt-3 space-y-2">
                        <input
                          type="text"
                          placeholder="源模板ID"
                          value={sourceTemplateId}
                          onChange={(e) => setSourceTemplateId(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-blue-500"
                        />
                        <input
                          type="text"
                          placeholder="源片段ID"
                          value={sourceTrackSegmentId}
                          onChange={(e) => setSourceTrackSegmentId(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-blue-500"
                        />
                      </div>
                    )}
                  </div>
                </label>

                {/* 重置为全局权重 */}
                <label className="flex items-start space-x-3 cursor-pointer">
                  <input
                    type="radio"
                    name="operation"
                    value="reset"
                    checked={operation === 'reset'}
                    onChange={(e) => setOperation(e.target.value as BatchOperation)}
                    className="mt-1"
                  />
                  <div className="flex-1">
                    <div className="flex items-center space-x-2">
                      <ArrowPathIcon className="w-4 h-4 text-orange-500" />
                      <span className="text-sm font-medium text-gray-900">重置为全局权重</span>
                    </div>
                    <p className="text-xs text-gray-500 mt-1">
                      清除自定义权重配置，恢复使用全局默认权重
                    </p>
                  </div>
                </label>

                {/* 自定义权重配置 */}
                <label className="flex items-start space-x-3 cursor-pointer">
                  <input
                    type="radio"
                    name="operation"
                    value="custom"
                    checked={operation === 'custom'}
                    onChange={(e) => setOperation(e.target.value as BatchOperation)}
                    className="mt-1"
                  />
                  <div className="flex-1">
                    <div className="flex items-center space-x-2">
                      <CheckIcon className="w-4 h-4 text-green-500" />
                      <span className="text-sm font-medium text-gray-900">自定义权重配置</span>
                    </div>
                    <p className="text-xs text-gray-500 mt-1">
                      为所有目标片段设置统一的自定义权重配置
                    </p>
                    
                    {operation === 'custom' && (
                      <div className="mt-3 space-y-2 max-h-48 overflow-y-auto border border-gray-200 rounded-md p-3 bg-gray-50">
                        {aiClassifications.map((classification) => {
                          const weight = customWeights[classification.id] || 0;
                          
                          return (
                            <div key={classification.id} className="flex items-center space-x-2">
                              <span className="text-xs text-gray-700 flex-1 truncate">
                                {classification.name}
                              </span>
                              <input
                                type="range"
                                min="0"
                                max="100"
                                value={weight}
                                onChange={(e) => handleWeightChange(classification.id, parseInt(e.target.value))}
                                className="flex-1 h-1 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-12 px-1 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-blue-500"
                              />
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </label>
              </div>
            </div>

            {/* 错误和成功消息 */}
            {error && (
              <div className="mb-4 flex items-center space-x-2 text-sm text-red-700 bg-red-100 border border-red-200 p-3 rounded-md">
                <ExclamationTriangleIcon className="w-4 h-4 flex-shrink-0" />
                <span>{error}</span>
              </div>
            )}

            {success && (
              <div className="mb-4 flex items-center space-x-2 text-sm text-green-700 bg-green-100 border border-green-200 p-3 rounded-md">
                <CheckIcon className="w-4 h-4 flex-shrink-0" />
                <span>{success}</span>
              </div>
            )}
          </div>

          {/* 操作按钮 */}
          <div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
            <button
              onClick={handleExecute}
              disabled={loading}
              className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {loading ? '处理中...' : '执行操作'}
            </button>
            <button
              onClick={onClose}
              disabled={loading}
              className="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
            >
              取消
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
