'use client'

import { useState } from 'react'
import { TopBar } from './workspace/top-bar'
import { LeftPanel } from './workspace/left-panel'
import { EditorPane } from './workspace/editor-pane'
import { RightPanel } from './workspace/right-panel'
import { StatusBar } from './workspace/status-bar'
import { usePanelStore } from '@/lib/stores/panel-store'
import type { StoryMaster, SceneInstance, Character, ScenesCatalog, Scene, Seat, User } from '@prisma/client'

type StoryWithRelations = StoryMaster & {
  sceneInstances: (SceneInstance & {
    catalog: ScenesCatalog
    scene: Pick<Scene, 'id' | 'wordCount' | 'status'> | null
  })[]
  characters: Character[]
  seats: (Seat & { user: Pick<User, 'id' | 'displayName' | 'avatar'> })[]
  creator: Pick<User, 'id' | 'displayName' | 'avatar'>
}

interface StoryWorkspaceProps {
  story: StoryWithRelations
  userRole: string
  userId: string
}

export function StoryWorkspace({ story, userRole, userId }: StoryWorkspaceProps) {
  const [currentSceneIndex, setCurrentSceneIndex] = useState(0)
  const { leftPanelOpen, rightPanelOpen, rightPanelTab } = usePanelStore()

  const currentScene = story.sceneInstances[currentSceneIndex] ?? null
  const totalWordCount = story.sceneInstances.reduce(
    (sum, si) => sum + (si.scene?.wordCount ?? 0),
    0
  )

  return (
    <div className="flex flex-col h-screen overflow-hidden">
      {/* Top Bar */}
      <TopBar
        story={story}
        collaborators={story.seats.map((s) => s.user)}
      />

      {/* Main three-column layout */}
      <div className="flex flex-1 overflow-hidden">
        {/* Left Panel — Scene Navigation */}
        {leftPanelOpen && (
          <LeftPanel
            scenes={story.sceneInstances}
            currentSceneIndex={currentSceneIndex}
            onSelectScene={setCurrentSceneIndex}
            format={story.format}
          />
        )}

        {/* Center — Screenplay Editor (always visible) */}
        <EditorPane
          scene={currentScene}
          storyId={story.id}
          readOnly={userRole === 'viewer'}
        />

        {/* Right Panel — Contextual */}
        {rightPanelOpen && (
          <RightPanel
            activeTab={rightPanelTab}
            storyId={story.id}
            scene={currentScene}
            characters={story.characters}
            format={story.format}
          />
        )}
      </div>

      {/* Status Bar */}
      <StatusBar
        currentScene={currentScene}
        currentSceneIndex={currentSceneIndex}
        totalScenes={story.sceneInstances.length}
        totalWordCount={totalWordCount}
      />
    </div>
  )
}
