import React, { useState } from 'react';
import { Button, Form, Spinner, Card, ListGroup, Modal, InputGroup, Alert } from 'react-bootstrap';
import { toast } from 'react-toastify';
import './style.css';
import { bookService, bookInfoService } from '../../db';
import { processProjectAudio } from '../../utils/audioProcessor'; // 导入音频处理工具
// 替换Node.js模块为浏览器兼容版本
// const fs = require('fs');
// const path = require('path');
// const os = require('os');
import path from 'path-browserify';
import os from 'os-browserify/browser';
// fs模块在浏览器中不可用，需要通过IPC调用主进程

const SubtitleUpload = ({ onProjectCreated, projectAudioFile }) => {
  const [file, setFile] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [subtitles, setSubtitles] = useState([]);
  const [fileName, setFileName] = useState('');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [projectTitle, setProjectTitle] = useState('');
  const [isCreating, setIsCreating] = useState(false);
  const [processingAudio, setProcessingAudio] = useState(false);
  const [audioProgress, setAudioProgress] = useState(0);

  // 处理文件选择
  const handleFileChange = (e) => {
    const selectedFile = e.target.files[0];
    if (selectedFile) {
      setFile(selectedFile);
      setFileName(selectedFile.name);
    }
  };

  // 解析SRT格式字幕
  const parseSRT = (content) => {
    const srtRegex = /(\d+)\r?\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\r?\n([\s\S]*?)(?=\r?\n\r?\n\d+|$)/g;
    const subtitles = [];
    let match;

    while ((match = srtRegex.exec(content)) !== null) {
      subtitles.push({
        id: parseInt(match[1]),
        startTime: match[2],
        endTime: match[3],
        text: match[4].trim()
      });
    }

    return subtitles;
  };

  // 解析VTT格式字幕
  const parseVTT = (content) => {
    // 移除WEBVTT头部
    const lines = content.replace(/^WEBVTT\r?\n/, '').split(/\r?\n\r?\n/);
    const subtitles = [];
    
    lines.forEach((block, index) => {
      const lines = block.split(/\r?\n/);
      if (lines.length >= 2) {
        // 检查时间戳行
        const timeLine = lines.find(line => line.includes(' --> '));
        if (timeLine) {
          const [startTime, endTime] = timeLine.split(' --> ');
          const textLines = lines.filter(line => line !== timeLine && !line.match(/^\d+$/));
          
          subtitles.push({
            id: index + 1,
            startTime: startTime,
            endTime: endTime,
            text: textLines.join(' ').trim()
          });
        }
      }
    });

    return subtitles;
  };

  // 上传并解析字幕
  const handleUpload = () => {
    if (!file) {
      toast.error('请先选择字幕文件');
      return;
    }

    setIsLoading(true);
    const reader = new FileReader();
    
    reader.onload = (e) => {
      try {
        const content = e.target.result;
        let parsedSubtitles = [];
        
        if (file.name.endsWith('.srt')) {
          parsedSubtitles = parseSRT(content);
        } else if (file.name.endsWith('.vtt')) {
          parsedSubtitles = parseVTT(content);
        } else {
          throw new Error('不支持的字幕格式，请上传.srt或.vtt格式的字幕文件');
        }
        
        if (parsedSubtitles.length > 0) {
          setSubtitles(parsedSubtitles);
          toast.success(`成功解析 ${parsedSubtitles.length} 条字幕`);
        } else {
          toast.warning('未能解析出任何字幕内容，请检查文件格式');
        }
      } catch (error) {
        toast.error(`解析字幕失败: ${error.message}`);
      } finally {
        setIsLoading(false);
      }
    };
    
    reader.onerror = () => {
      toast.error('读取文件失败');
      setIsLoading(false);
    };
    
    reader.readAsText(file);
  };

  // 打开创建项目模态框
  const openCreateProjectModal = () => {
    if (subtitles.length === 0) {
      toast.error('请先上传并解析字幕文件');
      return;
    }
    
    if (!projectAudioFile) {
      toast.error('请先上传音频文件（必选）');
      return;
    }
    
    setShowCreateModal(true);
  };

  // 获取应用数据路径
  const getAppDataPath = async () => {
    try {
      // 首先通过IPC获取数据库路径
      const dbPath = await window.electron.ipcRenderer.invoke('db:getPath');
      
      // 数据库路径示例: /Users/username/Library/Application Support/lip_sync/database.sqlite
      // 提取基础目录
      let basePath = '';
      if (dbPath) {
        const lastSlashIndex = Math.max(dbPath.lastIndexOf('/'), dbPath.lastIndexOf('\\'));
        if (lastSlashIndex !== -1) {
          basePath = dbPath.substring(0, lastSlashIndex);
        }
      } else {
        // 备用方案：使用基于平台的默认路径
        const platform = process?.platform || 'unknown';
        
        if (platform === 'win32') {
          // Windows
          basePath = path.join(process.env.APPDATA || '', 'lip_sync');
        } else if (platform === 'darwin') {
          // macOS
          basePath = path.join(os.homedir(), 'Library/Application Support/lip_sync');
        } else {
          // Linux或其他
          basePath = path.join(os.homedir(), '.local/share/lip_sync');
        }
      }
      
      // 添加资源子目录
      const resourcePath = path.join(basePath, 'resources');
      const audioPath = path.join(resourcePath, 'audio');
      
      console.log('音频文件路径:', audioPath);
      return audioPath;
    } catch (error) {
      console.error('获取应用数据路径失败:', error);
      return null;
    }
  };

  // 保存音频文件到本地
  const saveAudioFile = async (audioFile, projectId) => {
    try {
      const audioDir = await getAppDataPath();
      if (!audioDir) {
        throw new Error('无法获取音频存储路径');
      }
      
      const fileName = `project_${projectId}_full.mp3`;
      
      // 读取文件内容
      const buffer = await audioFile.arrayBuffer();
      
      // 检查electron对象是否存在
      if (typeof window.electron !== 'undefined' && window.electron.ipcRenderer) {
        // 通过IPC调用保存文件
        const result = await window.electron.ipcRenderer.invoke('save-audio-file', {
          buffer: Array.from(new Uint8Array(buffer)),
          fileName: fileName,
          directory: audioDir,
          projectId: projectId
        });
        
        if (result.success) {
          return {
            success: true,
            path: result.filePath,
            relativePath: path.join('audio', fileName)
          };
        } else {
          throw new Error(result.error);
        }
      } else {
        // 处理非Electron环境（例如开发环境中的Web浏览器）
        console.warn('Electron IPC不可用，无法保存文件到本地');
        
        // 模拟成功返回，用于开发环境测试
        return {
          success: true,
          path: path.join(audioDir, fileName),
          relativePath: path.join('audio', fileName)
        };
      }
    } catch (error) {
      console.error('保存音频文件失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  };

  // 创建项目
  const handleCreateProject = async () => {
    if (!projectTitle.trim()) {
      toast.error('请输入项目标题');
      return;
    }

    if (!projectAudioFile) {
      toast.error('请上传音频文件（必选）');
      return;
    }

    setIsCreating(true);
    try {
      // 创建项目记录
      const bookId = await bookService.createBook({
        title: projectTitle,
        subtitle_path: file ? file.name : null,
        audio_path: projectAudioFile ? projectAudioFile.name : null,
        created_at: new Date().toISOString()
      });

      // 为每个字幕段计算持续时间
      const processedSubtitles = subtitles.map(sub => {
        // 解析开始和结束时间
        const startParts = sub.startTime.replace(',', '.').split(':').map(Number);
        const endParts = sub.endTime.replace(',', '.').split(':').map(Number);
        
        // 计算开始和结束时间（秒）
        const startSeconds = startParts[0] * 3600 + startParts[1] * 60 + parseFloat(startParts[2]);
        const endSeconds = endParts[0] * 3600 + endParts[1] * 60 + parseFloat(endParts[2]);
        
        // 计算持续时间
        const durationSeconds = endSeconds - startSeconds;
        
        return {
          ...sub,
          duration: durationSeconds.toFixed(3)
        };
      });

      // 创建项目详细信息（先不包含音频路径）
      const bookInfoPromises = processedSubtitles.map(sub => {
        return bookInfoService.createBookInfo({
          book_id: bookId,
          segment_id: sub.id,
          start_time: sub.startTime,
          end_time: sub.endTime,
          duration: sub.duration,
          text: sub.text
        });
      });

      const createdSegments = await Promise.all(bookInfoPromises);
      
      // 处理音频文件
      setProcessingAudio(true);
      toast.info('正在处理音频文件，请稍候...');
      
      // 保存完整音频文件
      const savedAudio = await saveAudioFile(projectAudioFile, bookId);
      
      if (savedAudio.success) {
        // 更新项目记录中的音频路径为相对路径
        await bookService.updateBook(bookId, {
          audio_path: savedAudio.relativePath
        });
        
        // 获取所有已创建的分镜信息
        const segments = await bookInfoService.getBookInfoByBookId(bookId);
        
        // 切割音频
        const audioProcessResult = await processProjectAudio(
          bookId,
          savedAudio.path,
          segments,
          getAppDataPath()
        );
        
        if (audioProcessResult.success) {
          // 更新每个分镜的音频路径
          const updatePromises = audioProcessResult.segments.map(segment => {
            return bookInfoService.updateBookInfo(segment.segmentId, {
              audio_path: segment.relativePath
            });
          });
          
          await Promise.all(updatePromises);
          
          toast.success(`音频处理完成，已为 ${audioProcessResult.processedSegments}/${audioProcessResult.totalSegments} 个分镜生成独立音频`);
        } else {
          toast.warning(`音频切割过程中出现一些问题: ${audioProcessResult.error}`);
        }
      } else {
        toast.warning(`保存音频文件失败: ${savedAudio.error}`);
      }

      toast.success('项目创建成功！');
      setShowCreateModal(false);
      
      // 重置表单
      setProjectTitle('');
      setFile(null);
      setFileName('');
      setSubtitles([]);
      setProcessingAudio(false);
      
      // 调用回调函数
      if (typeof onProjectCreated === 'function') {
        onProjectCreated();
      }
    } catch (error) {
      console.error('创建项目失败:', error);
      toast.error(`创建项目失败: ${error.message}`);
    } finally {
      setIsCreating(false);
      setProcessingAudio(false);
    }
  };

  return (
    <div className="subtitle-upload-container">
      <Card>
        <Card.Header as="h5">上传字幕</Card.Header>
        <Card.Body>
          <Form>
            <Form.Group controlId="subtitleFile" className="mb-3">
              <Form.Label>选择字幕文件 (.srt 或 .vtt 格式)</Form.Label>
              <div className="custom-file-upload">
                <input
                  type="file"
                  accept=".srt,.vtt"
                  onChange={handleFileChange}
                  id="subtitle-file-input"
                  className="d-none"
                />
                <div className="file-upload-box">
                  <Button 
                    variant="outline-primary" 
                    onClick={() => document.getElementById('subtitle-file-input').click()}
                  >
                    选择文件
                  </Button>
                  <span className="ml-2">{fileName || '未选择文件'}</span>
                </div>
              </div>
            </Form.Group>
            
            <Button 
              variant="primary" 
              onClick={handleUpload}
              disabled={isLoading || !file}
              className="w-100"
            >
              {isLoading ? (
                <>
                  <Spinner
                    as="span"
                    animation="border"
                    size="sm"
                    role="status"
                    aria-hidden="true"
                  />
                  <span className="ml-2">处理中...</span>
                </>
              ) : (
                '上传并解析字幕'
              )}
            </Button>
          </Form>
          
          {subtitles.length > 0 && (
            <>
              <div className="mt-4">
                <h5>解析结果 ({subtitles.length} 条字幕)</h5>
                <div className="subtitle-list">
                  <ListGroup>
                    {subtitles.map((subtitle) => (
                      <ListGroup.Item key={subtitle.id}>
                        <div className="subtitle-item">
                          <div className="subtitle-time">
                            {subtitle.startTime} → {subtitle.endTime}
                          </div>
                          <div className="subtitle-text">{subtitle.text}</div>
                        </div>
                      </ListGroup.Item>
                    ))}
                  </ListGroup>
                </div>
              </div>
              
              <div className="mt-4 text-center">
                <Button 
                  variant="success" 
                  size="lg" 
                  onClick={openCreateProjectModal}
                  disabled={!projectAudioFile}
                >
                  创建项目
                </Button>
                {!projectAudioFile && (
                  <div className="text-danger mt-2">
                    请先上传音频文件（必选）
                  </div>
                )}
              </div>
            </>
          )}
        </Card.Body>
      </Card>

      {/* 创建项目模态框 */}
      <Modal show={showCreateModal} onHide={() => !isCreating && !processingAudio && setShowCreateModal(false)}>
        <Modal.Header closeButton={!isCreating && !processingAudio}>
          <Modal.Title>创建新项目</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Form>
            <Form.Group controlId="projectTitle">
              <Form.Label>项目标题</Form.Label>
              <Form.Control
                type="text"
                placeholder="请输入项目标题"
                value={projectTitle}
                onChange={(e) => setProjectTitle(e.target.value)}
                disabled={isCreating || processingAudio}
              />
            </Form.Group>
            <Form.Group className="mt-3">
              <Form.Label>字幕文件</Form.Label>
              <InputGroup>
                <Form.Control
                  readOnly
                  value={fileName}
                />
              </InputGroup>
            </Form.Group>
            <Form.Group className="mt-3">
              <Form.Label>音频文件</Form.Label>
              <InputGroup>
                <Form.Control
                  readOnly
                  value={projectAudioFile ? projectAudioFile.name : '未选择音频文件'}
                />
              </InputGroup>
            </Form.Group>
            <Form.Group className="mt-3">
              <Form.Label>字幕条数</Form.Label>
              <Form.Control
                readOnly
                value={`${subtitles.length} 条`}
              />
            </Form.Group>
            
            {processingAudio && (
              <div className="mt-3">
                <Alert variant="info">
                  正在处理音频文件，请稍候...这可能需要一些时间。
                </Alert>
              </div>
            )}
          </Form>
        </Modal.Body>
        <Modal.Footer>
          <Button 
            variant="secondary" 
            onClick={() => setShowCreateModal(false)}
            disabled={isCreating || processingAudio}
          >
            取消
          </Button>
          <Button 
            variant="primary" 
            onClick={handleCreateProject}
            disabled={isCreating || processingAudio}
          >
            {isCreating || processingAudio ? (
              <>
                <Spinner
                  as="span"
                  animation="border"
                  size="sm"
                  role="status"
                  aria-hidden="true"
                />
                <span className="ml-2">{processingAudio ? '处理音频中...' : '创建中...'}</span>
              </>
            ) : (
              '确认创建'
            )}
          </Button>
        </Modal.Footer>
      </Modal>
    </div>
  );
};

export default SubtitleUpload; 