"use client";

import { useState } from 'react';
import { motion } from 'framer-motion';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import type { DragEndEvent } from '@dnd-kit/core';
import { ScriptMetaInfo } from '../script-overview/script-meta-info';
import { SceneFilmstrip } from '../script-overview/scene-filmstrip';
import { StoryboardCardList } from '../storyboard/storyboard-card-list';
import { Scene } from '../pages/script-overview';

// 分镜场景数据结构
export interface StoryboardScene {
  id: string;
  name: string;
  description: string;
  shot: string;
  frame: string;
  atmosphere: string;
  imageUrl: string;
}

// 剧本元信息数据结构
export interface ScriptMeta {
  title: string;
  type: string;
  genre: string;
  tags: string[];
  duration: string;
  uploadTime: string;
}

export default function StoryboardView() {
  // 示例数据
  const [scriptMeta] = useState<ScriptMeta>({
    title: "Lost Stars",
    type: "Short Drama",
    genre: "Sci-Fi/Mystery",
    tags: ["Space", "Psychology", "Future"],
    duration: "20-25 minutes",
    uploadTime: "2024-03-20"
  });

  const [scenes, setScenes] = useState<StoryboardScene[]>([
    {
      id: "scene-1",
      name: "Opening Shot",
      description: "Establishing shot of the space station",
      shot: "Wide angle, slow pan from right to left",
      frame: "Space station silhouetted against Earth",
      atmosphere: "Mysterious, serene, with soft starlight",
      imageUrl: "https://smart-video-ai.oss-cn-beijing.aliyuncs.com/frames/d877fa43-4856-4acb-9a3b-627c28275343/frame_000007.jpg/1750507514_tmphfb431oc_000007.jpg",
    },
    {
      id: "scene-2",
      name: "Control Room",
      description: "Interior of the main control center",
      shot: "Medium close-up, steady cam",
      frame: "Monitors displaying unusual signal patterns",
      atmosphere: "Tense, with blinking lights and shadows",
      imageUrl: "https://smart-video-ai.oss-cn-beijing.aliyuncs.com/frames/d877fa43-4856-4acb-9a3b-627c28275343/frame_000007.jpg/1750507514_tmphfb431oc_000007.jpg",
    },
    {
      id: "scene-3",
      name: "Control Room",
      description: "Interior of the main control center",
      shot: "Medium close-up, steady cam",
      frame: "Monitors displaying unusual signal patterns",
      atmosphere: "Tense, with blinking lights and shadows",
      imageUrl: "https://smart-video-ai.oss-cn-beijing.aliyuncs.com/frames/d877fa43-4856-4acb-9a3b-627c28275343/frame_000007.jpg/1750507514_tmphfb431oc_000007.jpg",
    },
    {
      id: "scene-4",
      name: "Control Room",
      description: "Interior of the main control center",
      shot: "Medium close-up, steady cam",
      frame: "Monitors displaying unusual signal patterns",
      atmosphere: "Tense, with blinking lights and shadows",
      imageUrl: "https://smart-video-ai.oss-cn-beijing.aliyuncs.com/frames/d877fa43-4856-4acb-9a3b-627c28275343/frame_000007.jpg/1750507514_tmphfb431oc_000007.jpg",
    },
    {
      id: "scene-5",
      name: "Control Room",
      description: "Interior of the main control center",
      shot: "Medium close-up, steady cam",
      frame: "Monitors displaying unusual signal patterns",
      atmosphere: "Tense, with blinking lights and shadows",
      imageUrl: "https://smart-video-ai.oss-cn-beijing.aliyuncs.com/frames/d877fa43-4856-4acb-9a3b-627c28275343/frame_000007.jpg/1750507514_tmphfb431oc_000007.jpg",
    },
    {
      id: "scene-6",
      name: "Control Room",
      description: "Interior of the main control center",
      shot: "Medium close-up, steady cam",
      frame: "Monitors displaying unusual signal patterns",
      atmosphere: "Tense, with blinking lights and shadows",
      imageUrl: "https://smart-video-ai.oss-cn-beijing.aliyuncs.com/frames/d877fa43-4856-4acb-9a3b-627c28275343/frame_000007.jpg/1750507514_tmphfb431oc_000007.jpg",
    },
    {
      id: "scene-7",
      name: "Control Room",
      description: "Interior of the main control center",
      shot: "Medium close-up, steady cam",
      frame: "Monitors displaying unusual signal patterns",
      atmosphere: "Tense, with blinking lights and shadows",
      imageUrl: "https://smart-video-ai.oss-cn-beijing.aliyuncs.com/frames/d877fa43-4856-4acb-9a3b-627c28275343/frame_000007.jpg/1750507514_tmphfb431oc_000007.jpg",
    },
    {
      id: "scene-8",
      name: "Control Room",
      description: "Interior of the main control center",
      shot: "Medium close-up, steady cam",
      frame: "Monitors displaying unusual signal patterns",
      atmosphere: "Tense, with blinking lights and shadows",
      imageUrl: "https://smart-video-ai.oss-cn-beijing.aliyuncs.com/frames/d877fa43-4856-4acb-9a3b-627c28275343/frame_000007.jpg/1750507514_tmphfb431oc_000007.jpg",
    },
    {
      id: "scene-9",
      name: "Control Room",
      description: "Interior of the main control center",
      shot: "Medium close-up, steady cam",
      frame: "Monitors displaying unusual signal patterns",
      atmosphere: "Tense, with blinking lights and shadows",
      imageUrl: "https://smart-video-ai.oss-cn-beijing.aliyuncs.com/frames/d877fa43-4856-4acb-9a3b-627c28275343/frame_000007.jpg/1750507514_tmphfb431oc_000007.jpg",
    },
    {
      id: "scene-10",
      name: "Control Room",
      description: "Interior of the main control center",
      shot: "Medium close-up, steady cam",
      frame: "Monitors displaying unusual signal patterns",
      atmosphere: "Tense, with blinking lights and shadows",
      imageUrl: "https://smart-video-ai.oss-cn-beijing.aliyuncs.com/frames/d877fa43-4856-4acb-9a3b-627c28275343/frame_000007.jpg/1750507514_tmphfb431oc_000007.jpg",
    },
    {
      id: "scene-11",
      name: "Control Room",
      description: "Interior of the main control center",
      shot: "Medium close-up, steady cam",
      frame: "Monitors displaying unusual signal patterns",
      atmosphere: "Tense, with blinking lights and shadows",
      imageUrl: "https://smart-video-ai.oss-cn-beijing.aliyuncs.com/frames/d877fa43-4856-4acb-9a3b-627c28275343/frame_000007.jpg/1750507514_tmphfb431oc_000007.jpg",
    }
  ]);

  const [selectedSceneId, setSelectedSceneId] = useState<string>();

  // 处理场景拖拽排序
  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;

    if (active.id === over?.id) {
      return;
    }

    const oldIndex = scenes.findIndex(scene => scene.id === active.id);
    const newIndex = scenes.findIndex(scene => scene.id === over?.id);

    if (oldIndex === -1 || newIndex === -1) {
      return;
    }

    setScenes(arrayMove(scenes, oldIndex, newIndex));
  };

  // 处理场景更新
  const handleSceneUpdate = (sceneId: string, updates: Partial<StoryboardScene>) => {
    setScenes(scenes.map(scene => 
      scene.id === sceneId ? { ...scene, ...updates } : scene
    ));
  };

  // 处理场景删除
  const handleSceneDelete = (sceneId: string) => {
    setScenes(scenes.filter(scene => scene.id !== sceneId));
    if (selectedSceneId === sceneId) {
      setSelectedSceneId(undefined);
    }
  };

  // 处理场景复制
  const handleSceneDuplicate = (sceneId: string) => {
    const sceneToDuplicate = scenes.find(scene => scene.id === sceneId);
    if (!sceneToDuplicate) return;

    const newScene = {
      ...sceneToDuplicate,
      id: `scene-${Date.now()}`,
      name: `${sceneToDuplicate.name} (Copy)`
    };

    setScenes([...scenes, newScene]);
  };

  // 将 StoryboardScene 转换为 Scene 类型
  const adaptScenesForFilmstrip = (storyboardScenes: StoryboardScene[]): Scene[] => {
    return storyboardScenes.map(scene => ({
      id: scene.id,
      name: scene.name,
      description: scene.description,
      imageUrl: scene.imageUrl,
      plot: scene.shot,           // 使用 shot 作为 plot
      dialogue: scene.frame,      // 使用 frame 作为 dialogue
      narration: scene.atmosphere // 使用 atmosphere 作为 narration
    }));
  };

  return (
    <div className="h-full bg-[#0C0E11] text-white">
      <div className="h-full flex">
        {/* Left: Script Meta Info */}
        <div className="flex-shrink-0 h-full">
          <ScriptMetaInfo meta={scriptMeta} />
        </div>

        {/* Right: Scene Content */}
        <div className="flex-grow min-w-0 h-full overflow-hidden flex flex-col">
          {/* Scene Card List */}
          <div className="flex-grow overflow-y-auto">
            <DndContext
              sensors={useSensors(
                useSensor(PointerSensor),
                useSensor(KeyboardSensor, {
                  coordinateGetter: sortableKeyboardCoordinates,
                })
              )}
              collisionDetection={closestCenter}
              onDragEnd={handleDragEnd}
            >
              <SortableContext
                items={scenes.map(scene => scene.id)}
                strategy={verticalListSortingStrategy}
              >
                <StoryboardCardList
                  scenes={scenes}
                  selectedSceneId={selectedSceneId}
                  onSceneUpdate={handleSceneUpdate}
                  onSceneDelete={handleSceneDelete}
                  onSceneDuplicate={handleSceneDuplicate}
                />
              </SortableContext>
            </DndContext>
          </div>

          {/* Filmstrip Preview */}
          <div className="flex-shrink-0 py-6 px-8">
            <SceneFilmstrip 
              scenes={adaptScenesForFilmstrip(scenes)}
              selectedSceneId={selectedSceneId}
              onSceneSelect={(sceneId: string) => {
                setSelectedSceneId(sceneId);
              }}
            />
          </div>
        </div>
      </div>
    </div>
  );
} 