import React, { useState } from 'react';
import { X, Calendar, Clock, Monitor, Layers, FileText, Image, Video, Music, Type, Sparkles, CheckCircle, XCircle, AlertCircle, Upload, Cloud, ChevronDown, ChevronRight, Info } from 'lucide-react';
import { Template, TemplateMaterial, TemplateMaterialType, TrackType } from '../../types/template';
import { SegmentMatchingRuleEditor } from './SegmentMatchingRuleEditor';
import { useTemplateStore } from '../../stores/templateStore';

interface TemplateDetailModalProps {
  template: Template;
  onClose: () => void;
  onTemplateUpdated?: () => void;
}

export const TemplateDetailModal: React.FC<TemplateDetailModalProps> = ({
  template,
  onClose,
  onTemplateUpdated,
}) => {
  const [activeTab, setActiveTab] = useState<'overview' | 'materials' | 'tracks'>('overview');
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({});
  const [expandedMaterials, setExpandedMaterials] = useState<Record<string, boolean>>({});
  const [expandedSegments, setExpandedSegments] = useState<Record<string, boolean>>({});
  const [currentTemplate, setCurrentTemplate] = useState<Template>(template);

  const { getTemplateById } = useTemplateStore();

  // 刷新模板数据
  const refreshTemplateData = async () => {
    try {
      const updatedTemplate = await getTemplateById(template.id);
      if (updatedTemplate) {
        setCurrentTemplate(updatedTemplate);
        onTemplateUpdated?.();
      }
    } catch (error) {
      console.error('刷新模板数据失败:', error);
    }
  };

  // 处理匹配规则更新
  const handleRuleUpdated = async (segmentId: string, newRule: any) => {
    console.log('片段匹配规则已更新:', segmentId, newRule);
    // 刷新模板数据以获取最新的轨道片段信息
    await refreshTemplateData();
  };

  // 切换展开状态
  const toggleSection = (sectionId: string) => {
    setExpandedSections(prev => ({
      ...prev,
      [sectionId]: !prev[sectionId]
    }));
  };

  const toggleMaterial = (materialId: string) => {
    setExpandedMaterials(prev => ({
      ...prev,
      [materialId]: !prev[materialId]
    }));
  };

  const toggleSegment = (segmentId: string) => {
    setExpandedSegments(prev => ({
      ...prev,
      [segmentId]: !prev[segmentId]
    }));
  };

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

  // 格式化时长（精确到毫秒）
  const formatDurationWithMs = (microseconds: number) => {
    const totalMs = Math.floor(microseconds / 1000);
    const seconds = Math.floor(totalMs / 1000);
    const ms = totalMs % 1000;
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}`;
  };

  // 格式化文件大小
  const formatFileSize = (bytes?: number) => {
    if (!bytes) return '未知';
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${sizes[i]}`;
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN');
  };

  // 获取素材类型图标
  const getMaterialIcon = (type: TemplateMaterialType) => {
    switch (type) {
      case TemplateMaterialType.Video:
        return <Video className="w-4 h-4 text-blue-600" />;
      case TemplateMaterialType.Audio:
        return <Music className="w-4 h-4 text-green-600" />;
      case TemplateMaterialType.Image:
        return <Image className="w-4 h-4 text-purple-600" />;
      case TemplateMaterialType.Text:
        return <Type className="w-4 h-4 text-orange-600" />;
      case TemplateMaterialType.Effect:
        return <Sparkles className="w-4 h-4 text-pink-600" />;
      default:
        return <FileText className="w-4 h-4 text-gray-600" />;
    }
  };

  // 获取轨道类型图标
  const getTrackIcon = (type: TrackType) => {
    switch (type) {
      case TrackType.Video:
        return <Video className="w-4 h-4 text-blue-600" />;
      case TrackType.Audio:
        return <Music className="w-4 h-4 text-green-600" />;
      case TrackType.Text:
        return <Type className="w-4 h-4 text-orange-600" />;
      default:
        return <Layers className="w-4 h-4 text-gray-600" />;
    }
  };



  // 检查文件是否存在（基于数据库字段和路径）
  const getFileExistenceInfo = (material: any) => {
    const hasRemoteFile = material.remote_url && material.remote_url.trim() !== '';

    if (hasRemoteFile) {
      return {
        icon: <Cloud className="w-4 h-4 text-blue-600" />,
        text: '云端文件',
        color: 'text-blue-600'
      };
    } else if (material.file_exists) {
      return {
        icon: <CheckCircle className="w-4 h-4 text-green-600" />,
        text: '本地文件存在',
        color: 'text-green-600'
      };
    } else {
      return {
        icon: <XCircle className="w-4 h-4 text-red-600" />,
        text: '文件不存在',
        color: 'text-red-600'
      };
    }
  };

  // 获取上传状态（基于数据库字段）
  const getUploadStatusInfo = (material: any) => {
    if (material.upload_success) {
      return {
        icon: <CheckCircle className="w-4 h-4 text-green-600" />,
        text: '上传成功',
        color: 'text-green-600'
      };
    } else {
      // 根据 upload_status 显示具体状态
      switch (material.upload_status) {
        case 'Uploading':
          return {
            icon: <Upload className="w-4 h-4 text-blue-600" />,
            text: '上传中',
            color: 'text-blue-600'
          };
        case 'Failed':

        case 'Pending':
          return {
            icon: <AlertCircle className="w-4 h-4 text-yellow-600" />,
            text: '待上传',
            color: 'text-yellow-600'
          };
        case 'Skipped':
          return {
            icon: <AlertCircle className="w-4 h-4 text-gray-600" />,
            text: '已跳过',
            color: 'text-gray-600'
          };
        default:
          return {
            icon: <AlertCircle className="w-4 h-4 text-gray-600" />,
            text: '未上传',
            color: 'text-gray-600'
          };
      }
    }
  };

  // 解析文字素材的文本内容和样式
  const parseTextContent = (metadata: string | null) => {
    if (!metadata) return null;
    try {
      const parsed = JSON.parse(metadata);
      const obj = {
        content: tryParse(parsed.content || null),
        font_family: parsed.font_family || null,
        font_size: parsed.font_size || null,
        color: parsed.color || null
      };
      console.log({ obj })
      return obj;
    } catch (e) {
      return null;
    }
  };

  const tryParse = (str: any) => {
    try {
      if (typeof str === 'string') {
        return JSON.parse(str)
      }
      return str;
    } catch (e) {
      return str;
    }
  }

  // 解析片段属性信息
  const parseSegmentProperties = (properties: string | null) => {
    if (!properties) return null;

    try {
      const parsed = JSON.parse(properties);
      return {
        speed: parsed.speed || 1.0,
        source_timerange: parsed.source_timerange || null,
        target_timerange: parsed.target_timerange || null,
        speed_info: parsed.speed_info || null,
        visible: parsed.visible,
        volume: parsed.volume
      };
    } catch (e) {
      return null;
    }
  };

  const tabs = [
    { id: 'overview', label: '概览', icon: Monitor },
    { id: 'materials', label: '素材', icon: FileText },
    { id: 'tracks', label: '轨道', icon: Layers },
  ];

  const getMaterialName = (material: TemplateMaterial) => {
    if (material.material_type === TemplateMaterialType.Text) {
      return parseTextContent(material.metadata!)?.content?.text
    }
    return material.name
  }

  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-xl shadow-2xl w-full max-w-5xl max-h-[95vh] overflow-hidden">
        {/* 模态框头部 */}
        <div className="flex items-center justify-between p-4 sm:p-6 border-b border-gray-200 bg-gradient-to-r from-gray-50 to-white">
          <div className="flex-1 min-w-0">
            <h2 className="text-lg sm:text-xl font-semibold text-gray-900 truncate">{currentTemplate.name}</h2>
            {currentTemplate.description && (
              <p className="text-sm text-gray-600 mt-1 line-clamp-2">{currentTemplate.description}</p>
            )}
          </div>
          <button
            onClick={onClose}
            className="ml-4 p-2 rounded-full hover:bg-gray-100 transition-colors flex-shrink-0"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* 标签页导航 */}
        <div className="border-b border-gray-200 bg-white">
          <nav className="flex space-x-4 sm:space-x-8 px-4 sm:px-6 overflow-x-auto">
            {tabs.map((tab) => {
              const Icon = tab.icon;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id as any)}
                  className={`flex items-center py-3 sm:py-4 px-2 sm:px-1 border-b-2 font-medium text-sm transition-colors whitespace-nowrap ${activeTab === tab.id
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                    }`}
                >
                  <Icon className="w-4 h-4 mr-2 flex-shrink-0" />
                  <span className="hidden sm:inline">{tab.label}</span>
                  <span className="sm:hidden">{tab.label.charAt(0)}</span>
                </button>
              );
            })}
          </nav>
        </div>

        {/* 标签页内容 */}
        <div className="p-4 sm:p-6 overflow-y-auto max-h-[60vh] sm:max-h-[65vh]">
          {activeTab === 'overview' && (
            <div className="space-y-8">
              {/* 核心信息卡片 */}
              <div className="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-100 rounded-xl p-4 sm:p-6">
                <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
                  <div className="text-center">
                    <div className="inline-flex items-center justify-center w-12 h-12 bg-blue-100 rounded-lg mb-3">
                      <Monitor className="w-6 h-6 text-blue-600" />
                    </div>
                    <div className="text-2xl font-bold text-gray-900">
                      {currentTemplate.canvas_config.width}×{currentTemplate.canvas_config.height}
                    </div>
                    <div className="text-sm text-gray-600 mt-1">分辨率</div>
                    <div className="text-xs text-gray-500">{currentTemplate.canvas_config.ratio}</div>
                  </div>

                  <div className="text-center">
                    <div className="inline-flex items-center justify-center w-12 h-12 bg-green-100 rounded-lg mb-3">
                      <Clock className="w-6 h-6 text-green-600" />
                    </div>
                    <div className="text-2xl font-bold text-gray-900">
                      {formatDuration(currentTemplate.duration)}
                    </div>
                    <div className="text-sm text-gray-600 mt-1">时长</div>
                    <div className="text-xs text-gray-500">{currentTemplate.fps} FPS</div>
                  </div>

                  <div className="text-center">
                    <div className="inline-flex items-center justify-center w-12 h-12 bg-purple-100 rounded-lg mb-3">
                      <FileText className="w-6 h-6 text-purple-600" />
                    </div>
                    <div className="text-2xl font-bold text-gray-900">
                      {currentTemplate.materials.length}
                    </div>
                    <div className="text-sm text-gray-600 mt-1">素材</div>
                  </div>

                  <div className="text-center">
                    <div className="inline-flex items-center justify-center w-12 h-12 bg-orange-100 rounded-lg mb-3">
                      <Layers className="w-6 h-6 text-orange-600" />
                    </div>
                    <div className="text-2xl font-bold text-gray-900">
                      {currentTemplate.tracks.length}
                    </div>
                    <div className="text-sm text-gray-600 mt-1">轨道</div>
                  </div>
                </div>
              </div>

              {/* 技术详情 - 可折叠 */}
              <div className="border border-gray-200 rounded-lg overflow-hidden">
                <button
                  onClick={() => toggleSection('technical')}
                  className="w-full px-6 py-4 bg-gray-50 hover:bg-gray-100 transition-colors flex items-center justify-between"
                >
                  <div className="flex items-center space-x-3">
                    <Info className="w-5 h-5 text-gray-600" />
                    <span className="font-medium text-gray-900">技术详情</span>
                  </div>
                  {expandedSections.technical ? (
                    <ChevronDown className="w-5 h-5 text-gray-600" />
                  ) : (
                    <ChevronRight className="w-5 h-5 text-gray-600" />
                  )}
                </button>

                {expandedSections.technical && (
                  <div className="px-6 py-4 bg-white border-t border-gray-200">
                    <div className="space-y-4">
                      <div className="flex items-center justify-between py-2">
                        <span className="text-sm text-gray-600">模板ID</span>
                        <code className="text-xs bg-gray-100 px-2 py-1 rounded font-mono text-blue-600">
                          {currentTemplate.id}
                        </code>
                      </div>
                      {currentTemplate.source_file_path && (
                        <div className="flex items-start justify-between py-2">
                          <span className="text-sm text-gray-600">源文件路径</span>
                          <span className="text-xs text-gray-900 text-right max-w-md break-all">
                            {currentTemplate.source_file_path}
                          </span>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>

              {/* 时间信息 - 可折叠 */}
              <div className="border border-gray-200 rounded-lg overflow-hidden">
                <button
                  onClick={() => toggleSection('timestamps')}
                  className="w-full px-6 py-4 bg-gray-50 hover:bg-gray-100 transition-colors flex items-center justify-between"
                >
                  <div className="flex items-center space-x-3">
                    <Calendar className="w-5 h-5 text-gray-600" />
                    <span className="font-medium text-gray-900">时间信息</span>
                  </div>
                  {expandedSections.timestamps ? (
                    <ChevronDown className="w-5 h-5 text-gray-600" />
                  ) : (
                    <ChevronRight className="w-5 h-5 text-gray-600" />
                  )}
                </button>

                {expandedSections.timestamps && (
                  <div className="px-6 py-4 bg-white border-t border-gray-200">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div className="flex items-center justify-between py-2">
                        <span className="text-sm text-gray-600">创建时间</span>
                        <span className="text-sm text-gray-900">{formatDate(currentTemplate.created_at)}</span>
                      </div>
                      <div className="flex items-center justify-between py-2">
                        <span className="text-sm text-gray-600">更新时间</span>
                        <span className="text-sm text-gray-900">{formatDate(currentTemplate.updated_at)}</span>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}

          {activeTab === 'materials' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <h3 className="text-xl font-semibold text-gray-900">
                  素材列表
                </h3>
                <span className="text-sm text-gray-500 bg-gray-100 px-3 py-1 rounded-full">
                  {currentTemplate.materials.length} 个素材
                </span>
              </div>

              <div className="grid gap-4">
                {currentTemplate.materials.map((material) => {
                  const uploadStatus = getUploadStatusInfo(material);
                  const fileExistence = getFileExistenceInfo(material);
                  const isExpanded = expandedMaterials[material.id];

                  return (
                    <div key={material.id} className="bg-white border border-gray-200 rounded-lg overflow-hidden hover:shadow-md transition-shadow">
                      {/* 主要信息 */}
                      <div className="p-4">
                        <div className="flex items-start justify-between">
                          <div className="flex items-start space-x-3 flex-1">
                            <div className="flex-shrink-0">
                              {getMaterialIcon(material.material_type)}
                            </div>
                            <div className="flex-1 min-w-0">
                              <div className="flex items-center space-x-2 mb-2">
                                <h4 className="text-base font-medium text-gray-900 truncate">
                                  {getMaterialName(material)}
                                </h4>
                                <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                  {material.material_type}
                                </span>
                              </div>

                              {/* 状态指示器 */}
                              <div className="flex items-center space-x-4">
                                <div className="flex items-center space-x-1">
                                  {fileExistence.icon}
                                  <span className={`text-xs font-medium ${fileExistence.color}`}>
                                    {fileExistence.text}
                                  </span>
                                </div>
                                <div className="flex items-center space-x-1">
                                  {uploadStatus.icon}
                                  <span className={`text-xs font-medium ${uploadStatus.color}`}>
                                    {uploadStatus.text}
                                  </span>
                                </div>
                              </div>
                            </div>
                          </div>

                          {/* 文件信息摘要 */}
                          <div className="flex-shrink-0 text-right text-xs text-gray-500 space-y-1">
                            {material.duration && (
                              <div className="font-medium">{formatDuration(material.duration)}</div>
                            )}
                            {material.file_size && (
                              <div>{formatFileSize(material.file_size)}</div>
                            )}
                            {material.width && material.height && (
                              <div>{material.width}×{material.height}</div>
                            )}
                          </div>

                          {/* 展开按钮 */}
                          <button
                            onClick={() => toggleMaterial(material.id)}
                            className="ml-4 p-1 rounded-full hover:bg-gray-100 transition-colors"
                          >
                            {isExpanded ? (
                              <ChevronDown className="w-4 h-4 text-gray-600" />
                            ) : (
                              <ChevronRight className="w-4 h-4 text-gray-600" />
                            )}
                          </button>
                        </div>

                        {/* 详细信息 - 可展开 */}
                        {isExpanded && (
                          <div className="mt-4 pt-4 border-t border-gray-100 space-y-4">
                            {/* 文字素材显示文本内容 */}
                            {material.material_type === 'Text' && material.metadata && (() => {
                              const textData = parseTextContent(material.metadata);
                              return textData ? (
                                <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                                  <div className="text-sm font-medium text-blue-900 mb-2">文本内容</div>
                                  <div className="text-sm text-blue-800 break-words mb-3">
                                    {textData.content?.text || '无文本内容'}
                                  </div>
                                  {(textData.font_family || textData.font_size || textData.color) && (
                                    <div className="text-xs text-blue-700 space-y-1">
                                      {textData.font_family && (
                                        <div>字体: {textData.font_family}</div>
                                      )}
                                      {textData.font_size && (
                                        <div>大小: {textData.font_size}px</div>
                                      )}
                                      {textData.color && (
                                        <div>颜色: {textData.color}</div>
                                      )}
                                    </div>
                                  )}
                                </div>
                              ) : (
                                <div className="text-xs text-gray-500 bg-gray-100 p-2 rounded">
                                  无法解析文本内容
                                </div>
                              );
                            })()}

                            {/* 技术详情 */}
                            <div className="bg-gray-50 rounded-lg p-3">
                              <div className="text-sm font-medium text-gray-900 mb-2">技术详情</div>
                              <div className="space-y-2 text-xs text-gray-600">
                                <div className="flex justify-between">
                                  <span>素材ID</span>
                                  <code className="bg-white px-2 py-1 rounded font-mono text-blue-600">
                                    {material.id}
                                  </code>
                                </div>
                                <div className="flex justify-between">
                                  <span>原始ID</span>
                                  <code className="bg-white px-2 py-1 rounded font-mono text-purple-600">
                                    {material.original_id}
                                  </code>
                                </div>
                                {material.original_path && material.material_type !== 'Text' && (
                                  <div className="flex justify-between items-start">
                                    <span>文件路径</span>
                                    <span className="text-right max-w-xs break-all">
                                      {material.original_path}
                                    </span>
                                  </div>
                                )}
                                {material.remote_url && (
                                  <div className="flex justify-between items-start">
                                    <span>云端URL</span>
                                    <span className="text-right max-w-xs break-all">
                                      {material.remote_url}
                                    </span>
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {activeTab === 'tracks' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <h3 className="text-xl font-semibold text-gray-900">
                  轨道列表
                </h3>
                <span className="text-sm text-gray-500 bg-gray-100 px-3 py-1 rounded-full">
                  {currentTemplate.tracks.length} 个轨道
                </span>
              </div>

              <div className="space-y-4">
                {currentTemplate.tracks.map((track) => (
                  <div key={track.id} className="bg-white border border-gray-200 rounded-lg overflow-hidden">
                    {/* 轨道头部 */}
                    <div className="bg-gray-50 px-6 py-4 border-b border-gray-200">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                          <div className="flex-shrink-0">
                            {getTrackIcon(track.track_type)}
                          </div>
                          <div>
                            <h4 className="text-base font-medium text-gray-900">
                              {track.name}
                            </h4>
                            <div className="flex items-center space-x-4 text-xs text-gray-500 mt-1">
                              <span className="inline-flex items-center px-2 py-1 rounded-full bg-gray-100 text-gray-800">
                                {track.track_type}
                              </span>
                              <span>轨道 {track.track_index}</span>
                            </div>
                          </div>
                        </div>
                        <div className="text-right">
                          <div className="text-sm font-medium text-gray-900">
                            {track.segments.length} 个片段
                          </div>
                          <button
                            onClick={() => toggleSection(`track-${track.id}`)}
                            className="text-xs text-blue-600 hover:text-blue-800 mt-1"
                          >
                            {expandedSections[`track-${track.id}`] ? '收起详情' : '查看详情'}
                          </button>
                        </div>
                      </div>
                    </div>

                    {/* 轨道技术详情 */}
                    {expandedSections[`track-${track.id}`] && (
                      <div className="px-6 py-4 bg-gray-50 border-b border-gray-200">
                        <div className="text-xs text-gray-600">
                          <span>轨道ID: </span>
                          <code className="bg-white px-2 py-1 rounded font-mono text-green-600">
                            {track.id}
                          </code>
                        </div>
                      </div>
                    )}

                    {/* 片段列表 */}
                    {track.segments.length > 0 && (
                      <div className="divide-y divide-gray-100">
                        {track.segments.map((segment) => {
                          const segmentProps = parseSegmentProperties(segment.properties || null);
                          const isSegmentExpanded = expandedSegments[segment.id];

                          return (
                            <div key={segment.id} className="p-4">
                              {/* 片段主要信息 */}
                              <div className="flex items-start justify-between mb-3">
                                <div className="flex-1">
                                  <div className="flex items-center space-x-3 mb-2">
                                    <h5 className="text-sm font-medium text-gray-900">
                                      {segment.name}
                                    </h5>
                                    <span className="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded">
                                      #{segment.segment_index}
                                    </span>
                                  </div>

                                  <div className="flex items-center space-x-4 text-xs text-gray-600">
                                    <span className="font-medium">
                                      {formatDurationWithMs(segment.start_time)} - {formatDurationWithMs(segment.end_time)}
                                    </span>
                                    <span>时长: {formatDurationWithMs(segment.duration)}</span>
                                    {segmentProps?.speed && segmentProps.speed !== 1.0 && (
                                      <span className={`px-2 py-1 rounded text-xs font-medium ${
                                        segmentProps.speed > 1.0
                                          ? 'bg-red-100 text-red-700'
                                          : 'bg-green-100 text-green-700'
                                      }`}>
                                        {segmentProps.speed.toFixed(2)}x
                                      </span>
                                    )}
                                  </div>
                                </div>

                                <button
                                  onClick={() => toggleSegment(segment.id)}
                                  className="ml-4 p-1 rounded-full hover:bg-gray-100 transition-colors"
                                >
                                  {isSegmentExpanded ? (
                                    <ChevronDown className="w-4 h-4 text-gray-600" />
                                  ) : (
                                    <ChevronRight className="w-4 h-4 text-gray-600" />
                                  )}
                                </button>
                              </div>

                              {/* 匹配规则 - 始终显示 */}
                              <div className="mb-3">
                                <SegmentMatchingRuleEditor
                                  segmentId={segment.id}
                                  currentRule={segment.matching_rule}
                                  onRuleUpdated={(newRule) => handleRuleUpdated(segment.id, newRule)}
                                />
                              </div>

                              {/* 关联素材信息 */}
                              {segment.template_material_id && (
                                <div className="text-xs text-gray-600 mb-3">
                                  <span>关联素材: </span>
                                  <code className="bg-blue-50 text-blue-700 px-2 py-1 rounded font-mono">
                                    {segment.template_material_id}
                                  </code>
                                </div>
                              )}
                              {/* 详细属性 - 可展开 */}
                              {isSegmentExpanded && (
                                <div className="mt-4 pt-4 border-t border-gray-100 space-y-4">
                                  {/* 技术详情 */}
                                  <div className="bg-gray-50 rounded-lg p-3">
                                    <div className="text-sm font-medium text-gray-900 mb-2">技术详情</div>
                                    <div className="text-xs text-gray-600">
                                      <span>片段ID: </span>
                                      <code className="bg-white px-2 py-1 rounded font-mono text-orange-600">
                                        {segment.id}
                                      </code>
                                    </div>
                                  </div>

                                  {/* 时间轴位置信息 */}
                                  {segmentProps?.target_timerange && (
                                    <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                                      <div className="text-sm font-medium text-blue-900 mb-2">时间轴位置</div>
                                      <div className="text-xs text-blue-700 space-y-1">
                                        <div>开始: {formatDurationWithMs(segmentProps.target_timerange.start)}</div>
                                        <div>时长: {formatDurationWithMs(segmentProps.target_timerange.duration)}</div>
                                        <div>结束: {formatDurationWithMs(segmentProps.target_timerange.start + segmentProps.target_timerange.duration)}</div>
                                      </div>
                                    </div>
                                  )}

                                  {/* 源素材时间范围 */}
                                  {segmentProps?.source_timerange && (
                                    <div className="bg-purple-50 border border-purple-200 rounded-lg p-3">
                                      <div className="text-sm font-medium text-purple-900 mb-2">源素材时间范围</div>
                                      <div className="text-xs text-purple-700 space-y-1">
                                        <div>开始位置: {formatDurationWithMs(segmentProps.source_timerange.start)}</div>
                                        <div>截取时长: {formatDurationWithMs(segmentProps.source_timerange.duration)}</div>
                                        <div>结束位置: {formatDurationWithMs(segmentProps.source_timerange.start + segmentProps.source_timerange.duration)}</div>
                                      </div>
                                    </div>
                                  )}

                                  {/* 播放属性 */}
                                  {(segmentProps?.visible !== undefined || segmentProps?.volume !== undefined) && (
                                    <div className="bg-green-50 border border-green-200 rounded-lg p-3">
                                      <div className="text-sm font-medium text-green-900 mb-2">播放属性</div>
                                      <div className="text-xs text-green-700 space-y-1">
                                        {segmentProps?.visible !== undefined && (
                                          <div>可见性: {segmentProps.visible ? '可见' : '隐藏'}</div>
                                        )}
                                        {segmentProps?.volume !== undefined && (
                                          <div>音量: {(segmentProps.volume * 100).toFixed(0)}%</div>
                                        )}
                                      </div>
                                    </div>
                                  )}
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* 模态框底部 */}
        <div className="flex items-center justify-end p-4 sm:p-6 border-t border-gray-200 bg-gray-50">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors shadow-sm"
          >
            关闭
          </button>
        </div>
      </div>
    </div>
  );
};
