"use client";

import { useEffect, useMemo } from "react";
import { useRouter } from "next/navigation";
import { RefreshCw } from "lucide-react";
import VideoPreviewModal from "@/components/VideoPreviewModal";
import ScriptExtractionModal from "./ScriptExtractionModal";
import RewriteModal from "./RewriteModal";
import { useHomeController } from "@/features/home/model/useHomeController";
import { resolveMediaUrl } from "@/shared/lib/media";
import { BgmPanel } from "@/features/home/ui/BgmPanel";
import { GenerateActionBar } from "@/features/home/ui/GenerateActionBar";
import { HistoryList } from "@/features/home/ui/HistoryList";
import { HomeHeader } from "@/features/home/ui/HomeHeader";
import { MaterialSelector } from "@/features/home/ui/MaterialSelector";
import { TimelineEditor } from "@/features/home/ui/TimelineEditor";
import { ClipTrimmer } from "@/features/home/ui/ClipTrimmer";
import { PreviewPanel } from "@/features/home/ui/PreviewPanel";
import { RefAudioPanel } from "@/features/home/ui/RefAudioPanel";
import { ScriptEditor } from "@/features/home/ui/ScriptEditor";
import { TitleSubtitlePanel } from "@/features/home/ui/TitleSubtitlePanel";
import { VoiceSelector } from "@/features/home/ui/VoiceSelector";
import { GeneratedAudiosPanel } from "@/features/home/ui/GeneratedAudiosPanel";

export function HomePage() {
  const router = useRouter();
  const {
    apiBase,
    registerMaterialRef,
    previewMaterial,
    setPreviewMaterial,
    materials,
    fetchError,
    isFetching,
    lastMaterialCount,
    isUploading,
    uploadProgress,
    uploadError,
    setUploadError,
    fetchMaterials,
    deleteMaterial,
    handleUpload,
    selectedMaterials,
    toggleMaterial,
    handlePreviewMaterial,
    editingMaterialId,
    editMaterialName,
    setEditMaterialName,
    startMaterialEditing,
    saveMaterialEditing,
    cancelMaterialEditing,
    text,
    setText,
    extractModalOpen,
    setExtractModalOpen,
    rewriteModalOpen,
    setRewriteModalOpen,
    handleGenerateMeta,
    isGeneratingMeta,
    handleTranslate,
    isTranslating,
    originalText,
    handleRestoreOriginal,
    savedScripts,
    handleSaveScript,
    deleteSavedScript,
    showStylePreview,
    setShowStylePreview,
    videoTitle,
    titleInput,
    titleStyles,
    selectedTitleStyleId,
    setSelectedTitleStyleId,
    titleFontSize,
    setTitleFontSize,
    setTitleSizeLocked,
    videoSecondaryTitle,
    secondaryTitleInput,
    selectedSecondaryTitleStyleId,
    setSelectedSecondaryTitleStyleId,
    secondaryTitleFontSize,
    setSecondaryTitleFontSize,
    setSecondaryTitleSizeLocked,
    secondaryTitleTopMargin,
    setSecondaryTitleTopMargin,
    subtitleStyles,
    selectedSubtitleStyleId,
    setSelectedSubtitleStyleId,
    subtitleFontSize,
    setSubtitleFontSize,
    setSubtitleSizeLocked,
    titleTopMargin,
    setTitleTopMargin,
    subtitleBottomMargin,
    setSubtitleBottomMargin,
    titleDisplayMode,
    setTitleDisplayMode,
    outputAspectRatio,
    setOutputAspectRatio,
    lipsyncModelMode,
    setLipsyncModelMode,
    resolveAssetUrl,
    getFontFormat,
    buildTextShadow,
    ttsMode,
    setTtsMode,
    voices,
    voice,
    setVoice,
    refAudios,
    selectedRefAudio,
    handleSelectRefAudio,
    isUploadingRef,
    uploadRefError,
    setUploadRefError,
    uploadRefAudio,
    fetchRefAudios,
    playingAudioId,
    togglePlayPreview,
    editingAudioId,
    editName,
    setEditName,
    startEditing,
    saveEditing,
    cancelEditing,
    deleteRefAudio,
    retranscribeRefAudio,
    retranscribingId,
    recordedBlob,
    isRecording,
    recordingTime,
    startRecording,
    stopRecording,
    useRecording,
    discardRecording,
    formatRecordingTime,
    bgmList,
    bgmLoading,
    bgmError,
    enableBgm,
    setEnableBgm,
    fetchBgmList,
    selectedBgmId,
    setSelectedBgmId,
    playingBgmId,
    toggleBgmPreview,
    bgmListContainerRef,
    registerBgmItemRef,
    currentTask,
    isGenerating,
    handleGenerate,
    generatedVideo,
    generatedVideos,
    selectedVideoId,
    handleSelectVideo,
    deleteVideo,
    fetchGeneratedVideos,
    registerVideoRef,
    formatDate,
    generatedAudios,
    selectedAudio,
    selectedAudioId,
    isGeneratingAudio,
    audioTask,
    fetchGeneratedAudios,
    handleGenerateAudio,
    deleteAudio,
    renameAudio,
    selectAudio,
    speed,
    setSpeed,
    emotion,
    setEmotion,
    timelineSegments,
    reorderSegments,
    setSourceRange,
    clipTrimmerOpen,
    setClipTrimmerOpen,
    clipTrimmerSegmentId,
    setClipTrimmerSegmentId,
    materialPosterUrl,
  } = useHomeController();

  useEffect(() => {
    router.prefetch("/publish");
  }, [router]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    if ("scrollRestoration" in history) {
      history.scrollRestoration = "manual";
    }
    window.scrollTo({ top: 0, left: 0, behavior: "auto" });
    // 兜底：等所有恢复 effect + 异步数据加载 settle 后再次强制回顶部
    const timer = setTimeout(() => {
      window.scrollTo({ top: 0, left: 0, behavior: "auto" });
    }, 200);
    return () => clearTimeout(timer);
  }, []);

  const clipTrimmerSegment = useMemo(
    () => timelineSegments.find((s) => s.id === clipTrimmerSegmentId) ?? null,
    [timelineSegments, clipTrimmerSegmentId]
  );

  const clipTrimmerMaterialUrl = useMemo(() => {
    if (!clipTrimmerSegment) return null;
    const mat = materials.find((m) => m.id === clipTrimmerSegment.materialId);
    return mat?.path ? resolveMediaUrl(mat.path) : null;
  }, [clipTrimmerSegment, materials]);

  return (
    <div className="min-h-dvh">
      <HomeHeader />

      <main className="max-w-6xl mx-auto px-6 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* 左侧: 输入区域 */}
          <div className="space-y-6">
            {/* 一、文案提取与编辑 */}
            <ScriptEditor
              text={text}
              onChangeText={setText}
              onOpenExtractModal={() => setExtractModalOpen(true)}
              onOpenRewriteModal={() => setRewriteModalOpen(true)}
              onGenerateMeta={handleGenerateMeta}
              isGeneratingMeta={isGeneratingMeta}
              onTranslate={handleTranslate}
              isTranslating={isTranslating}
              hasOriginalText={originalText !== null}
              onRestoreOriginal={handleRestoreOriginal}
              savedScripts={savedScripts}
              onSaveScript={handleSaveScript}
              onLoadScript={setText}
              onDeleteScript={deleteSavedScript}
            />

            {/* 二、配音 */}
            <div className="relative z-20 bg-white/5 rounded-2xl p-4 sm:p-6 border border-white/10 backdrop-blur-sm">
              <h2 className="text-base sm:text-lg font-semibold text-white mb-4">
                二、配音
              </h2>
              <h3 className="text-sm font-medium text-gray-400 mb-3">配音方式</h3>
              <VoiceSelector
                embedded
                ttsMode={ttsMode}
                onSelectTtsMode={setTtsMode}
                voices={voices}
                voice={voice}
                onSelectVoice={setVoice}
                voiceCloneSlot={(
                  <RefAudioPanel
                    refAudios={refAudios}
                    selectedRefAudio={selectedRefAudio}
                    onSelectRefAudio={handleSelectRefAudio}
                    isUploadingRef={isUploadingRef}
                    uploadRefError={uploadRefError}
                    onClearUploadRefError={() => setUploadRefError(null)}
                    onUploadRefAudio={uploadRefAudio}
                    onFetchRefAudios={fetchRefAudios}
                    playingAudioId={playingAudioId}
                    onTogglePlayPreview={togglePlayPreview}
                    editingAudioId={editingAudioId}
                    editName={editName}
                    onEditNameChange={setEditName}
                    onStartEditing={startEditing}
                    onSaveEditing={saveEditing}
                    onCancelEditing={cancelEditing}
                    onDeleteRefAudio={deleteRefAudio}
                    onRetranscribe={retranscribeRefAudio}
                    retranscribingId={retranscribingId}
                    recordedBlob={recordedBlob}
                    isRecording={isRecording}
                    recordingTime={recordingTime}
                    onStartRecording={startRecording}
                    onStopRecording={stopRecording}
                    onUseRecording={useRecording}
                    onDiscardRecording={discardRecording}
                    formatRecordingTime={formatRecordingTime}
                  />
                )}
              />
              <div className="border-t border-white/10 my-4" />
              <GeneratedAudiosPanel
                embedded
                generatedAudios={generatedAudios}
                selectedAudioId={selectedAudioId}
                isGeneratingAudio={isGeneratingAudio}
                audioTask={audioTask}
                onGenerateAudio={handleGenerateAudio}
                onRefresh={() => fetchGeneratedAudios()}
                onSelectAudio={selectAudio}
                onDeleteAudio={deleteAudio}
                onRenameAudio={renameAudio}
                hasText={!!text.trim()}
                missingRefAudio={ttsMode === "voiceclone" && !selectedRefAudio}
                speed={speed}
                onSpeedChange={setSpeed}
                ttsMode={ttsMode}
                emotion={emotion}
                onEmotionChange={setEmotion}
              />
            </div>

            {/* 三、素材编辑 */}
            <div className="bg-white/5 rounded-2xl p-4 sm:p-6 border border-white/10 backdrop-blur-sm">
              <h2 className="text-base sm:text-lg font-semibold text-white mb-4">
                三、素材编辑
              </h2>
              <MaterialSelector
                embedded
                materials={materials}
                selectedMaterials={selectedMaterials}
                isFetching={isFetching}
                lastMaterialCount={lastMaterialCount}
                editingMaterialId={editingMaterialId}
                editMaterialName={editMaterialName}
                isUploading={isUploading}
                uploadProgress={uploadProgress}
                uploadError={uploadError}
                fetchError={fetchError}
                apiBase={apiBase}
                onUploadChange={handleUpload}
                onRefresh={fetchMaterials}
                onToggleMaterial={toggleMaterial}
                onPreviewMaterial={handlePreviewMaterial}
                onStartEditing={startMaterialEditing}
                onEditNameChange={setEditMaterialName}
                onSaveEditing={saveMaterialEditing}
                onCancelEditing={cancelMaterialEditing}
                onDeleteMaterial={deleteMaterial}
                onClearUploadError={() => setUploadError(null)}
                registerMaterialRef={registerMaterialRef}
              />
              <div className="border-t border-white/10 my-4" />
              <div className="relative">
                {(!selectedAudio || selectedMaterials.length === 0) && (
                  <div className="absolute inset-0 bg-black/50 backdrop-blur-sm rounded-xl flex items-center justify-center z-10">
                    <p className="text-gray-400">
                      {!selectedAudio ? "请先生成并选中配音" : "请先选择素材"}
                    </p>
                  </div>
                )}
                <TimelineEditor
                  embedded
                  audioDuration={selectedAudio?.duration_sec ?? 0}
                  audioUrl={selectedAudio ? (resolveMediaUrl(selectedAudio.path) || "") : ""}
                  segments={timelineSegments}
                  materials={materials}
                  outputAspectRatio={outputAspectRatio}
                  onOutputAspectRatioChange={setOutputAspectRatio}
                  onReorderSegment={reorderSegments}
                  onClickSegment={(seg) => {
                    setClipTrimmerSegmentId(seg.id);
                    setClipTrimmerOpen(true);
                  }}
                />
              </div>
            </div>

            {/* 四、标题与字幕 */}
            <TitleSubtitlePanel
              showStylePreview={showStylePreview}
              onTogglePreview={() => setShowStylePreview((prev) => !prev)}
              videoTitle={videoTitle}
              onTitleChange={titleInput.handleChange}
              onTitleCompositionStart={titleInput.handleCompositionStart}
              onTitleCompositionEnd={titleInput.handleCompositionEnd}
              videoSecondaryTitle={videoSecondaryTitle}
              onSecondaryTitleChange={secondaryTitleInput.handleChange}
              onSecondaryTitleCompositionStart={secondaryTitleInput.handleCompositionStart}
              onSecondaryTitleCompositionEnd={secondaryTitleInput.handleCompositionEnd}
              titleStyles={titleStyles}
              selectedTitleStyleId={selectedTitleStyleId}
              onSelectTitleStyle={setSelectedTitleStyleId}
              titleFontSize={titleFontSize}
              onTitleFontSizeChange={(value) => {
                setTitleFontSize(value);
                setTitleSizeLocked(true);
              }}
              selectedSecondaryTitleStyleId={selectedSecondaryTitleStyleId}
              onSelectSecondaryTitleStyle={setSelectedSecondaryTitleStyleId}
              secondaryTitleFontSize={secondaryTitleFontSize}
              onSecondaryTitleFontSizeChange={(value) => {
                setSecondaryTitleFontSize(value);
                setSecondaryTitleSizeLocked(true);
              }}
              secondaryTitleTopMargin={secondaryTitleTopMargin}
              onSecondaryTitleTopMarginChange={setSecondaryTitleTopMargin}
              subtitleStyles={subtitleStyles}
              selectedSubtitleStyleId={selectedSubtitleStyleId}
              onSelectSubtitleStyle={setSelectedSubtitleStyleId}
              subtitleFontSize={subtitleFontSize}
              onSubtitleFontSizeChange={(value) => {
                setSubtitleFontSize(value);
                setSubtitleSizeLocked(true);
              }}
              titleTopMargin={titleTopMargin}
              onTitleTopMarginChange={setTitleTopMargin}
              subtitleBottomMargin={subtitleBottomMargin}
              onSubtitleBottomMarginChange={setSubtitleBottomMargin}
              titleDisplayMode={titleDisplayMode}
              onTitleDisplayModeChange={setTitleDisplayMode}
              resolveAssetUrl={resolveAssetUrl}
              getFontFormat={getFontFormat}
              buildTextShadow={buildTextShadow}
              previewBaseWidth={outputAspectRatio === "16:9" ? 1920 : 1080}
              previewBaseHeight={outputAspectRatio === "16:9" ? 1080 : 1920}
              previewBackgroundUrl={materialPosterUrl}
            />

            {/* 背景音乐 (不编号) */}
            <BgmPanel
              bgmList={bgmList}
              bgmLoading={bgmLoading}
              bgmError={bgmError}
              enableBgm={enableBgm}
              onToggleEnable={setEnableBgm}
              onRefresh={fetchBgmList}
              selectedBgmId={selectedBgmId}
              onSelectBgm={setSelectedBgmId}
              playingBgmId={playingBgmId}
              onTogglePreview={toggleBgmPreview}
              bgmListContainerRef={bgmListContainerRef}
              registerBgmItemRef={registerBgmItemRef}
            />

            {/* 生成按钮 (不编号) */}
            <GenerateActionBar
              isGenerating={isGenerating}
              progress={currentTask?.progress || 0}
              materialCount={selectedMaterials.length}
              disabled={isGenerating || selectedMaterials.length === 0 || !selectedAudio}
              modelMode={lipsyncModelMode}
              onModelModeChange={setLipsyncModelMode}
              onGenerate={handleGenerate}
            />
          </div>

          {/* 右侧: 作品区域 */}
          <div className="space-y-6">
            {/* 生成进度（在作品卡片上方） */}
            {currentTask && isGenerating && (
              <div className="bg-white/5 rounded-2xl p-4 sm:p-6 border border-purple-500/30 backdrop-blur-sm">
                <div className="space-y-3">
                  <div className="flex justify-between text-sm text-purple-300 mb-1">
                    <span>正在AI生成中...</span>
                    <span>{currentTask.progress || 0}%</span>
                  </div>
                  <div className="h-3 bg-black/30 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-gradient-to-r from-purple-500 to-pink-500 transition-all duration-300"
                      style={{ width: `${currentTask.progress || 0}%` }}
                    />
                  </div>
                </div>
              </div>
            )}
            {/* 六、作品 */}
            <div className="bg-white/5 rounded-2xl p-4 sm:p-6 border border-white/10 backdrop-blur-sm">
              <h2 className="text-base sm:text-lg font-semibold text-white mb-4">
                六、作品
              </h2>
              <div className="flex justify-between items-center mb-3">
                <h3 className="text-sm font-medium text-gray-400">作品列表</h3>
                <button
                  onClick={() => fetchGeneratedVideos()}
                  className="px-2 py-1 text-xs bg-white/10 hover:bg-white/20 rounded text-gray-300 flex items-center gap-1"
                >
                  <RefreshCw className="h-3.5 w-3.5" />
                  刷新
                </button>
              </div>
              <HistoryList
                embedded
                generatedVideos={generatedVideos}
                selectedVideoId={selectedVideoId}
                onSelectVideo={handleSelectVideo}
                onDeleteVideo={deleteVideo}
                onRefresh={() => fetchGeneratedVideos()}
                registerVideoRef={registerVideoRef}
                formatDate={formatDate}
              />
              <div className="border-t border-white/10 my-4" />
              <h3 className="text-sm font-medium text-gray-400 mb-3">作品预览</h3>
              <PreviewPanel
                embedded
                currentTask={null}
                isGenerating={false}
                generatedVideo={generatedVideo}
              />
            </div>
          </div>
        </div>
      </main>
      <VideoPreviewModal
        onClose={() => setPreviewMaterial(null)}
        videoUrl={previewMaterial}
        title="素材预览"
      />

      <ScriptExtractionModal
        isOpen={extractModalOpen}
        onClose={() => setExtractModalOpen(false)}
        onApply={(nextText) => setText(nextText)}
      />

      <RewriteModal
        isOpen={rewriteModalOpen}
        onClose={() => setRewriteModalOpen(false)}
        originalText={text}
        onApply={(newText) => setText(newText)}
      />

      <ClipTrimmer
        isOpen={clipTrimmerOpen}
        segment={clipTrimmerSegment}
        materialUrl={clipTrimmerMaterialUrl}
        onConfirm={(sourceStart, sourceEnd) => {
          if (clipTrimmerSegmentId) {
            setSourceRange(clipTrimmerSegmentId, sourceStart, sourceEnd);
          }
          setClipTrimmerOpen(false);
        }}
        onClose={() => setClipTrimmerOpen(false)}
      />
    </div>
  );
}
