import { useEffect } from 'react';
import ScriptCreation from './ScriptCreation';
import VoiceSynthesis from './VoiceSynthesis';
import VideoGeneration from '../VideoGeneration';
import SubtitleBurning from './SubtitleBurning';
import CoverDesign from './CoverDesign';
import VideoCompose from './VideoCompose';

import { useProjectStore, createNewProject, saveMetaToLocalFile } from '../../store';
import { toast } from '../../store/uiStore';
import { localProjectApi, getCurrentProjectId, type ProjectMeta } from '../../api/modules/localStorage';
import './VideoCreation.css';

const steps = [
  { id: 1, label: '脚本生成' },
  { id: 2, label: '配音合成' },
  { id: 3, label: '视频生成' },
  { id: 4, label: '字幕烧录' },
  { id: 5, label: '封面设计' },
  { id: 6, label: '压制成片' },
];

/**
 * 视频创作流程容器
 *
 * 流程：
 * - 6 步流程：脚本生成 -> 配音合成 -> 视频生成 -> 字幕烧录 -> 封面设计 -> 压制成片
 * - 使用全局 projectStore 状态管理
 */
function VideoCreationContent() {
  // 从全局状态读取当前步骤，新建项目时会自动重置为 1
  const currentStep = useProjectStore(state => state.currentStep);
  const setCurrentStep = useProjectStore(state => state.setCurrentStep);

  // 直接订阅 segments，避免 project getter 无法追踪的问题
  const segments = useProjectStore(state => state.segments);
  const isLoading = useProjectStore(state => state._isLoading);
  const composedVideoPath = useProjectStore(state => state.composedVideoPath);
  const dubbingAudioUrl = useProjectStore(state => state.dubbingAudioUrl);
  const burnedVideoPath = useProjectStore(state => state.burnedVideoPath);
  const coverPath = useProjectStore(state => state.coverPath);
  const finalVideoPath = useProjectStore(state => state.finalVideoPath);
  const stepDirtyFlags = useProjectStore(state => state.stepDirtyFlags);

  // 页面刷新后从 meta.json 恢复项目状态（projectStore persist 不保存业务数据）
  useEffect(() => {
    async function loadMeta() {
      const pid = getCurrentProjectId();
      if (!pid) {return;}
      try {
        const meta = await localProjectApi.loadMeta(pid);
        if (meta) {
          const updates: Record<string, unknown> = {};
          // 系统字段
          if (meta.title !== undefined) {updates.title = meta.title;}

          // Step 1 参数
          if (meta.topic !== undefined) {updates.topic = meta.topic;}
          if (meta.categoryCode !== undefined) {updates.categoryCode = meta.categoryCode;}

          // Step 2 配音合成
          if (meta.selectedVoiceId !== undefined) {updates.selectedVoiceId = meta.selectedVoiceId;}
          if (meta.dubbingAudioUrl !== undefined) {updates.dubbingAudioUrl = meta.dubbingAudioUrl;}
          if (meta.dubbingAudioPath !== undefined) {updates.dubbingAudioPath = meta.dubbingAudioPath;}
          if (meta.dubbingAudioDuration !== undefined) {updates.dubbingAudioDuration = meta.dubbingAudioDuration;}
          if (meta.voiceSpeed !== undefined) {updates.voiceSpeed = meta.voiceSpeed;}
          if (meta.voiceVolume !== undefined) {updates.voiceVolume = meta.voiceVolume;}
          if (meta.voicePitch !== undefined) {updates.voicePitch = meta.voicePitch;}
          if (meta.subtitleAlignment !== undefined) {updates.subtitleAlignment = meta.subtitleAlignment;}

          // Step 3 视频生成
          if (meta.avatarMaterialPath !== undefined) {updates.avatarMaterialPath = meta.avatarMaterialPath;}
          if (meta.avatarMaterialName !== undefined) {updates.avatarMaterialName = meta.avatarMaterialName;}
          if (meta.avatarMaterialDuration !== undefined) {updates.avatarMaterialDuration = meta.avatarMaterialDuration;}
          if (meta.composedVideoUrl !== undefined) {updates.composedVideoUrl = meta.composedVideoUrl;}
          if (meta.composedVideoPath !== undefined) {updates.composedVideoPath = meta.composedVideoPath;}
          if (meta.lipSyncTaskId !== undefined) {updates.lipSyncTaskId = meta.lipSyncTaskId;}
          if (meta.lipSyncState !== undefined) {updates.lipSyncState = meta.lipSyncState;}
          if (meta.lipSyncedVideoUrl !== undefined) {updates.lipSyncedVideoUrl = meta.lipSyncedVideoUrl;}
          if (meta.lipSyncedVideoPath !== undefined) {updates.lipSyncedVideoPath = meta.lipSyncedVideoPath;}
          if (meta.userUploadedMaterials !== undefined) {updates.userUploadedMaterials = meta.userUploadedMaterials;}

          // Step 4 字幕
          if (meta.burnedVideoPath !== undefined) {updates.burnedVideoPath = meta.burnedVideoPath;}
          if (meta.mainTitle !== undefined) {updates.mainTitle = meta.mainTitle;}
          if (meta.subTitle !== undefined) {updates.subTitle = meta.subTitle;}
          if (meta.mainTitlePreset !== undefined) {updates.mainTitlePreset = meta.mainTitlePreset;}
          if (meta.subTitlePreset !== undefined) {updates.subTitlePreset = meta.subTitlePreset;}
          if (meta.captionPreset !== undefined) {updates.captionPreset = meta.captionPreset;}

          // Step 5 封面
          if (meta.coverPath !== undefined) {updates.coverPath = meta.coverPath;}
          if (meta.coverConfig !== undefined) {updates.coverConfig = meta.coverConfig;}

          // Step 6 合成
          if (meta.finalVideoPath !== undefined) {updates.finalVideoPath = meta.finalVideoPath;}
          if (meta.exportedAt !== undefined) {updates.exportedAt = meta.exportedAt;}

          // 步骤脏标记
          if (meta.stepDirtyFlags !== undefined) {updates.stepDirtyFlags = meta.stepDirtyFlags;}

          useProjectStore.setState(updates);
        }
      } catch (e) {
        console.error('[VideoCreation] 加载 meta.json 失败:', e);
      }
    }
    loadMeta();
  }, []);

  // 等待项目数据加载
  if (isLoading) {
    return (
      <div className="video-creation loading">
        <div className="loading-spinner">加载项目中...</div>
      </div>
    );
  }

  // 步骤完成检查
  const isStep1Complete = segments.length > 0;
  // Step 2 配音合成：必须有配音音频
  const isStep2Complete = isStep1Complete && !!dubbingAudioUrl;
  // Step 3 视频生成：拼接视频已生成
  const isStep3Complete = isStep2Complete && !!composedVideoPath;
  // Step 4 字幕烧录：必须有烧录后的视频
  const isStep4Complete = isStep3Complete && !!burnedVideoPath;
  // Step 5 封面设计：必须有封面图
  const isStep5Complete = isStep4Complete && !!coverPath;
  // Step 6 压制成片：必须有成品视频
  const isStep6Complete = isStep5Complete && !!finalVideoPath;

  // 判断用户能否进入某步骤
  const canAccessStep = (stepId: number) => {
    if (stepId === 1) {return true;}
    if (stepId === 2) {return isStep1Complete;}
    if (stepId === 3) {return isStep2Complete;}
    if (stepId === 4) {return isStep3Complete;}
    if (stepId === 5) {return isStep4Complete;}
    if (stepId === 6) {return isStep5Complete;}
    return isStep6Complete;
  };

  const canGoNext = () => {
    if (currentStep === 1) {return isStep1Complete;}
    if (currentStep === 2) {return isStep2Complete;}
    if (currentStep === 3) {return isStep3Complete;}
    if (currentStep === 4) {return isStep4Complete;}
    if (currentStep === 5) {return isStep5Complete;}
    if (currentStep === 6) {return isStep6Complete;}
    return false;
  };

  // 保存当前步骤数据（目前只有 Step 1 需要在切换前落盘）
  // 返回 true 表示已经保存过 meta.json，调用方无需再重复保存 currentStep
  const saveCurrentStepData = async (now: number): Promise<boolean> => {
    if (currentStep !== 1) {
      return false;
    }

    const state = useProjectStore.getState();
    let projectId = getCurrentProjectId();
    const topic = state.topic || '';
    const categoryCode = state.categoryCode;

    if (!projectId) {
      projectId = await createNewProject(topic, state.segments);

      await localProjectApi.saveSegments(projectId, state.segments);

      const meta: ProjectMeta = {
        id: projectId,
        title: topic || '未命名项目',
        topic,
        categoryCode,
        status: 'draft',
        currentStep: 2,
        createdAt: now,
        updatedAt: now,
      };
      await localProjectApi.saveMeta(projectId, meta);
      return true;
    } else {
      const existingMeta = await localProjectApi.loadMeta(projectId);
      const meta: ProjectMeta = {
        ...(existingMeta || { id: projectId, title: topic || '未命名项目', status: 'draft', currentStep: 2, createdAt: now, updatedAt: now }),
        topic,
        categoryCode,
        currentStep: 2,
        updatedAt: now,
      };
      await localProjectApi.saveProject(projectId, meta, state.segments);
      return true;
    }
  };

  const goNext = async () => {
    if (!canGoNext()) {
      return;
    }

    try {
      const saved = await saveCurrentStepData(Date.now());
      const nextStep = Math.min(currentStep + 1, steps.length);

      // 更新全局状态中的当前步骤
      setCurrentStep(nextStep);

      // 如果 saveCurrentStepData 没有保存 meta，再单独更新 currentStep
      const projectId = getCurrentProjectId();
      if (projectId && !saved) {
        await saveMetaToLocalFile({ currentStep: nextStep });
      }
    } catch (err) {
      console.error('[VideoCreation] goNext save failed:', err);
      toast.error('保存失败，请重试');
    }
  };

  const goPrev = async () => {
    try {
      const saved = await saveCurrentStepData(Date.now());
      const prevStep = Math.max(currentStep - 1, 1);
      setCurrentStep(prevStep);
      // 如果 saveCurrentStepData 没有保存 meta，再单独更新 currentStep
      const projectId = getCurrentProjectId();
      if (projectId && !saved) {
        await saveMetaToLocalFile({ currentStep: prevStep });
      }
    } catch (err) {
      console.error('[VideoCreation] goPrev save failed:', err);
      toast.error('保存失败，请重试');
    }
  };

  const renderStep = () => {
    switch (currentStep) {
      case 1:
        return <ScriptCreation />;
      case 2:
        return <VoiceSynthesis />;
      case 3:
        return <VideoGeneration />;
      case 4:
        return <SubtitleBurning />;
      case 5:
        return <CoverDesign />;
      case 6:
        return <VideoCompose />;
      default:
        return <ScriptCreation />;
    }
  };

  return (
    <div className="video-creation">
      {/* 步骤指示器 */}
      <div className="step-indicator">
        <div className="step-progress-track">
          <div
            className="step-progress-fill"
            style={{ width: `${((currentStep - 1) / (steps.length - 1)) * 100}%` }}
          />
        </div>
        <div className="step-dots">
          {steps.map(step => {
            const accessible = canAccessStep(step.id);
            const stepCompleteMap: Record<number, boolean> = {
              1: isStep1Complete,
              2: isStep2Complete,
              3: isStep3Complete,
              4: isStep4Complete,
              5: isStep5Complete,
              6: isStep6Complete,
            };
            const hasData = stepCompleteMap[step.id];
            const isDirty = (stepDirtyFlags?.[step.id] ?? false) && hasData;
            return (
              <button
                key={step.id}
                className={`step-dot ${step.id === currentStep ? 'active' : ''} ${step.id < currentStep ? 'completed' : ''} ${!accessible ? 'disabled' : ''} ${isDirty ? 'dirty' : ''}`}
                // 步骤条仅作进度展示，禁止直接点击跳转
                // 用户通过「上一步 / 下一步」按钮顺序导航，避免跨步骤回退导致数据不一致
                title={!accessible ? '请先完成前置步骤' : isDirty ? '上游已更新，需重新生成' : step.id === currentStep ? '当前步骤' : '通过下方按钮切换步骤'}
              >
                <span className="step-number">
                  {step.id < currentStep && accessible ? (
                    <svg
                      width="14"
                      height="14"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2.5"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <polyline points="20 6 9 17 4 12" />
                    </svg>
                  ) : (
                    step.id
                  )}
                </span>
                <span className="step-label">{step.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* 步骤内容 */}
      <div className="step-content animate-fadeIn" key={currentStep}>
        {renderStep()}
      </div>

      {/* 导航 */}
      <div className="step-navigation">
        <button
          className="btn btn-secondary nav-btn-prev"
          onClick={goPrev}
          disabled={currentStep === 1}
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <polyline points="15 18 9 12 15 6" />
          </svg>
          上一步
        </button>
        <div className="step-counter-center">
          <span className="step-counter">
            {currentStep} / {steps.length}
          </span>
        </div>
        {currentStep < steps.length && (
          <button
            className={`btn btn-primary nav-btn-next ${!canGoNext() ? 'btn-disabled' : ''}`}
            onClick={goNext}
          >
            下一步
            <svg
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <polyline points="9 18 15 12 9 6" />
            </svg>
          </button>
        )}
        {currentStep >= steps.length && <div />}
      </div>
    </div>
  );
}

/**
 * 视频创作页面（带项目状态管理）
 */
export default function VideoCreation() {
  return <VideoCreationContent />;
}
