'use client'

import { useCallback } from 'react'
import ReactFlow, {
  Background,
  BackgroundVariant,
  Controls,
  useNodesState,
  useEdgesState,
  addEdge,
  Connection,
  Node,
  Edge,
} from 'reactflow'
import 'reactflow/dist/style.css'
import Toolbar from '@/components/editor/Toolbar'
import type { FlowchartData, FlowchartNode, FlowchartEdge } from '@/types/flowchart'

type FlowchartEditorProps = {
  projectId: string
  initialData: FlowchartData
}

// Convert our FlowchartNode type to React Flow Node type
function toReactFlowNodes(nodes: FlowchartNode[]): Node[] {
  return nodes.map((node) => ({
    id: node.id,
    type: node.type,
    position: node.position,
    data: node.data,
  }))
}

// Convert our FlowchartEdge type to React Flow Edge type
function toReactFlowEdges(edges: FlowchartEdge[]): Edge[] {
  return edges.map((edge) => ({
    id: edge.id,
    source: edge.source,
    sourceHandle: edge.sourceHandle,
    target: edge.target,
    targetHandle: edge.targetHandle,
    data: edge.data,
  }))
}

export default function FlowchartEditor({
  initialData,
}: FlowchartEditorProps) {
  const [nodes, setNodes, onNodesChange] = useNodesState(
    toReactFlowNodes(initialData.nodes)
  )
  const [edges, setEdges, onEdgesChange] = useEdgesState(
    toReactFlowEdges(initialData.edges)
  )

  const onConnect = useCallback(
    (params: Connection) => setEdges((eds) => addEdge(params, eds)),
    [setEdges]
  )

  // Placeholder handlers - functionality will be added in future stories
  const handleAddDialogue = useCallback(() => {
    // TODO: Implement in US-021
  }, [])

  const handleAddChoice = useCallback(() => {
    // TODO: Implement in US-023
  }, [])

  const handleAddVariable = useCallback(() => {
    // TODO: Implement in US-026
  }, [])

  const handleSave = useCallback(() => {
    // TODO: Implement in US-034
  }, [])

  const handleExport = useCallback(() => {
    // TODO: Implement in US-035
  }, [])

  const handleImport = useCallback(() => {
    // TODO: Implement in US-036
  }, [])

  return (
    <div className="flex h-full w-full flex-col">
      <Toolbar
        onAddDialogue={handleAddDialogue}
        onAddChoice={handleAddChoice}
        onAddVariable={handleAddVariable}
        onSave={handleSave}
        onExport={handleExport}
        onImport={handleImport}
      />
      <div className="flex-1">
        <ReactFlow
          nodes={nodes}
          edges={edges}
          onNodesChange={onNodesChange}
          onEdgesChange={onEdgesChange}
          onConnect={onConnect}
          fitView
        >
          <Background variant={BackgroundVariant.Dots} gap={16} size={1} />
          <Controls position="bottom-right" />
        </ReactFlow>
      </div>
    </div>
  )
}
