"use client"
import React, { useRef, useEffect } from "react";
import "./style/work-flow.css";
import { Skeleton } from "@/components/ui/skeleton";
import { AISuggestionBar } from "@/components/ai-suggestion-bar";
import { EditModal } from "@/components/ui/edit-modal";
import { TaskInfo } from "./work-flow/task-info";
import { MediaViewer } from "./work-flow/media-viewer";
import { ThumbnailGrid } from "./work-flow/thumbnail-grid";
import { useWorkflowData } from "./work-flow/use-workflow-data";
import { usePlaybackControls } from "./work-flow/use-playback-controls";

export default function WorkFlow() {
  const containerRef = useRef<HTMLDivElement>(null);
  const [isEditModalOpen, setIsEditModalOpen] = React.useState(false);
  const [activeEditTab, setActiveEditTab] = React.useState('1');

  // 使用自定义 hooks 管理状态
  const {
    taskObject,
    taskSketch,
    taskVideos,
    sketchCount,
    isLoading,
    currentStep,
    currentSketchIndex,
    isGeneratingSketch,
    isGeneratingVideo,
    currentLoadingText,
    setCurrentSketchIndex,
  } = useWorkflowData();

  const {
    isPlaying,
    isVideoPlaying,
    showControls,
    setShowControls,
    togglePlay,
    toggleVideoPlay,
    playTimerRef,
  } = usePlaybackControls(taskSketch, taskVideos, currentStep);

  // 处理自动播放的分镜切换逻辑
  useEffect(() => {
    if (isPlaying && taskSketch.length > 0 && playTimerRef.current) {
      const interval = setInterval(() => {
        setCurrentSketchIndex((prev: number) => (prev + 1) % taskSketch.length);
      }, 2000);
      
      return () => clearInterval(interval);
    }
  }, [isPlaying, taskSketch.length, setCurrentSketchIndex]);

  // 模拟 AI 建议
  const mockSuggestions = [
    "优化场景转场效果",
    "调整画面构图",
    "改进角色动作设计",
    "增加环境氛围",
    "调整镜头语言"
  ];

  const handleEditModalOpen = (tab: string) => {
    setActiveEditTab(tab);
    setIsEditModalOpen(true);
  };

  const handleSuggestionClick = (suggestion: string) => {
    console.log('Selected suggestion:', suggestion);
  };

  const handleSubmit = (text: string) => {
    console.log('Submitted text:', text);
  };

  return (
    <div className="w-full h-full overflow-hidden">
      <div className="flex h-full flex-col p-6 justify-center items-center pt-0">
        <div className="container-H2sRZG">
          <div className="splashContainer-otuV_A">
            <div className="content-vPGYx8">
              <div className="info-UUGkPJ">
                <TaskInfo
                  isLoading={isLoading}
                  taskObject={taskObject}
                  currentLoadingText={currentLoadingText}
                />
              </div>
            </div>
            <div className="media-Ocdu1O">
              <div 
                className="videoContainer-qteKNi" 
                style={currentStep !== '6' ? { flex: 3 } : {}} 
                ref={containerRef}
              >
                {isLoading ? (
                  <Skeleton className="w-full aspect-video rounded-lg" />
                ) : (
                  <div className="heroVideo-FIzuK1" style={{ aspectRatio: "16 / 9" }}>
                    <MediaViewer
                      currentStep={currentStep}
                      currentSketchIndex={currentSketchIndex}
                      taskSketch={taskSketch}
                      taskVideos={taskVideos}
                      isVideoPlaying={isVideoPlaying}
                      isPlaying={isPlaying}
                      showControls={showControls}
                      onControlsChange={setShowControls}
                      onEditModalOpen={handleEditModalOpen}
                      onToggleVideoPlay={toggleVideoPlay}
                      onTogglePlay={togglePlay}
                    />
                  </div>
                )}
              </div>
              <div className="imageGrid-ymZV9z hidden-scrollbar">
                <ThumbnailGrid
                  isLoading={isLoading}
                  currentStep={currentStep}
                  currentSketchIndex={currentSketchIndex}
                  taskSketch={taskSketch}
                  taskVideos={taskVideos}
                  isGeneratingSketch={isGeneratingSketch}
                  sketchCount={sketchCount}
                  onSketchSelect={setCurrentSketchIndex}
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* AI 建议栏 */}
      <AISuggestionBar
        suggestions={mockSuggestions}
        onSuggestionClick={handleSuggestionClick}
        onSubmit={handleSubmit}
        placeholder="请输入你的想法，或点击预设词条获取 AI 建议..."
      />

      <EditModal
        isOpen={isEditModalOpen}
        activeEditTab={activeEditTab}
        onClose={() => setIsEditModalOpen(false)}
        taskStatus={taskObject?.taskStatus || '1'}
        taskSketch={taskSketch}
        sketchVideo={taskVideos}
        currentSketchIndex={currentSketchIndex}
        onSketchSelect={setCurrentSketchIndex}
      />
    </div>
  )
}