import React, { useState } from 'react';
import { RefreshCw, X, Zap, AlertCircle } from 'lucide-react';
import { SegmentWithDetails } from '../types/materialSegmentView';

interface MaterialSegmentReclassifyDialogProps {
  segments: SegmentWithDetails[];
  isOpen: boolean;
  onClose: () => void;
  onConfirm: (options: ReclassifyOptions) => void;
  isLoading?: boolean;
}

interface ReclassifyOptions {
  overwriteExisting: boolean;
  useLatestModel: boolean;
  priority: 'low' | 'normal' | 'high';
}

/**
 * MaterialSegment重新分类对话框组件
 * 遵循 Tauri 开发规范的组件设计模式
 */
export const MaterialSegmentReclassifyDialog: React.FC<MaterialSegmentReclassifyDialogProps> = ({
  segments,
  isOpen,
  onClose,
  onConfirm,
  isLoading = false,
}) => {
  const [options, setOptions] = useState<ReclassifyOptions>({
    overwriteExisting: true,
    useLatestModel: true,
    priority: 'normal',
  });

  if (!isOpen) return null;

  const isBatch = segments.length > 1;
  const classifiedSegments = segments.filter(s => s.classification);
  const unclassifiedSegments = segments.filter(s => !s.classification);

  // 格式化时长
  const formatDuration = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    const secs = Math.round(seconds % 60);
    return `${minutes}:${secs.toString().padStart(2, '0')}`;
  };

  // 计算总时长
  const totalDuration = segments.reduce((sum, segment) => sum + segment.segment.duration, 0);

  const handleConfirm = () => {
    onConfirm(options);
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-lg w-full max-h-[90vh] overflow-hidden">
        {/* 对话框头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
              <RefreshCw className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-900">
                {isBatch ? '批量重新分类' : '重新分类'}
              </h3>
              <p className="text-sm text-gray-600">
                {isBatch ? `重新分类 ${segments.length} 个片段` : '重新分类该片段'}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            disabled={isLoading}
            className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 对话框内容 */}
        <div className="p-6 overflow-y-auto max-h-[calc(90vh-200px)]">
          {/* 片段概览 */}
          <div className="mb-6">
            <h4 className="text-sm font-medium text-gray-900 mb-3">片段概览</h4>
            <div className="bg-gray-50 rounded-lg p-4">
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div className="flex items-center justify-between">
                  <span className="text-gray-600">总片段数</span>
                  <span className="font-medium text-gray-900">{segments.length}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-gray-600">总时长</span>
                  <span className="font-medium text-gray-900">{formatDuration(totalDuration)}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-gray-600">已分类</span>
                  <span className="font-medium text-green-600">{classifiedSegments.length}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-gray-600">未分类</span>
                  <span className="font-medium text-orange-600">{unclassifiedSegments.length}</span>
                </div>
              </div>
            </div>
          </div>

          {/* 分类选项 */}
          <div className="space-y-6">
            <div>
              <h4 className="text-sm font-medium text-gray-900 mb-3">分类选项</h4>
              
              {/* 覆盖现有分类 */}
              <div className="space-y-4">
                <div className="flex items-start space-x-3">
                  <input
                    type="checkbox"
                    id="overwriteExisting"
                    checked={options.overwriteExisting}
                    onChange={(e) => setOptions(prev => ({ ...prev, overwriteExisting: e.target.checked }))}
                    className="mt-1 w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                  />
                  <div className="flex-1">
                    <label htmlFor="overwriteExisting" className="text-sm font-medium text-gray-900 cursor-pointer">
                      覆盖现有分类结果
                    </label>
                    <p className="text-xs text-gray-600 mt-1">
                      如果片段已有分类结果，是否重新分类并覆盖原结果
                    </p>
                  </div>
                </div>

                {/* 使用最新模型 */}
                <div className="flex items-start space-x-3">
                  <input
                    type="checkbox"
                    id="useLatestModel"
                    checked={options.useLatestModel}
                    onChange={(e) => setOptions(prev => ({ ...prev, useLatestModel: e.target.checked }))}
                    className="mt-1 w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                  />
                  <div className="flex-1">
                    <label htmlFor="useLatestModel" className="text-sm font-medium text-gray-900 cursor-pointer">
                      使用最新AI模型
                    </label>
                    <p className="text-xs text-gray-600 mt-1">
                      使用最新版本的AI分类模型进行分类，可能获得更准确的结果
                    </p>
                  </div>
                </div>
              </div>
            </div>

            {/* 优先级设置 */}
            <div>
              <h4 className="text-sm font-medium text-gray-900 mb-3">处理优先级</h4>
              <div className="space-y-2">
                {[
                  { value: 'low', label: '低优先级', desc: '在后台慢速处理，不影响其他任务' },
                  { value: 'normal', label: '普通优先级', desc: '正常速度处理，推荐选择' },
                  { value: 'high', label: '高优先级', desc: '优先处理，可能影响其他任务性能' },
                ].map((priority) => (
                  <div key={priority.value} className="flex items-start space-x-3">
                    <input
                      type="radio"
                      id={`priority-${priority.value}`}
                      name="priority"
                      value={priority.value}
                      checked={options.priority === priority.value}
                      onChange={(e) => setOptions(prev => ({ ...prev, priority: e.target.value as any }))}
                      className="mt-1 w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500"
                    />
                    <div className="flex-1">
                      <label htmlFor={`priority-${priority.value}`} className="text-sm font-medium text-gray-900 cursor-pointer">
                        {priority.label}
                      </label>
                      <p className="text-xs text-gray-600 mt-1">{priority.desc}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* 警告信息 */}
          {classifiedSegments.length > 0 && options.overwriteExisting && (
            <div className="mt-6 bg-yellow-50 border border-yellow-200 rounded-lg p-3">
              <div className="flex items-start">
                <AlertCircle className="w-4 h-4 text-yellow-600 mt-0.5 mr-2 flex-shrink-0" />
                <div className="text-sm text-yellow-800">
                  <p className="font-medium mb-1">注意：</p>
                  <p>
                    有 {classifiedSegments.length} 个片段已有分类结果，重新分类将覆盖现有结果。
                    如果您只想分类未分类的片段，请取消勾选"覆盖现有分类结果"。
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* 预估时间 */}
          <div className="mt-6 bg-blue-50 border border-blue-200 rounded-lg p-3">
            <div className="flex items-start">
              <Zap className="w-4 h-4 text-blue-600 mt-0.5 mr-2 flex-shrink-0" />
              <div className="text-sm text-blue-800">
                <p className="font-medium mb-1">预估处理时间：</p>
                <p>
                  根据片段数量和优先级，预计需要 {Math.ceil(segments.length * 0.5)} - {Math.ceil(segments.length * 2)} 分钟完成分类。
                  您可以在AI分析日志中查看处理进度。
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* 对话框底部 */}
        <div className="flex items-center justify-end space-x-3 p-6 border-t border-gray-200 bg-gray-50">
          <button
            onClick={onClose}
            disabled={isLoading}
            className="px-4 py-2 text-gray-600 hover:text-gray-800 transition-colors disabled:opacity-50"
          >
            取消
          </button>
          <button
            onClick={handleConfirm}
            disabled={isLoading}
            className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isLoading ? (
              <>
                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2" />
                处理中...
              </>
            ) : (
              <>
                <RefreshCw className="w-4 h-4 mr-2" />
                开始重新分类
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
};
