"use client"

import { useEffect, useMemo, useRef, useState } from "react"
import {
  ReactFlow,
  ReactFlowProvider,
  Background,
  useReactFlow,
  useNodesState,
  useEdgesState,
} from "@xyflow/react"
import "@xyflow/react/dist/style.css"
import { workflowNodeTypes } from "@/components/gmail/settings/automation/workflow-nodes"
import {
  workflowEdgesToFlow,
  workflowNodesToFlow,
} from "@/lib/mail-automation/workflow-flow"
import { createUltimailProductDemoRuleState } from "@/components/landing/product/product-demos/ultimail-demo-workflow"

function WorkflowFlowPreviewCanvas() {
  const { fitView } = useReactFlow()
  const demoState = useMemo(() => createUltimailProductDemoRuleState(), [])
  const initialNodes = useMemo(
    () => workflowNodesToFlow(demoState.workflow.nodes),
    [demoState]
  )
  const initialEdges = useMemo(
    () => workflowEdgesToFlow(demoState.workflow.edges),
    [demoState]
  )
  const [nodes] = useNodesState(initialNodes)
  const [edges] = useEdgesState(initialEdges)

  useEffect(() => {
    fitView({ padding: 0.18, duration: 0 })
  }, [fitView])

  return (
    <ReactFlow
      nodes={nodes}
      edges={edges}
      nodeTypes={workflowNodeTypes}
      fitView
      nodesDraggable={false}
      nodesConnectable={false}
      elementsSelectable={false}
      panOnDrag={false}
      zoomOnScroll={false}
      preventScrolling={false}
      proOptions={{ hideAttribution: true }}
    >
      <Background gap={16} />
    </ReactFlow>
  )
}

/** Canvas ReactFlow seul — aperçu no-code sans panneaux latéraux. */
export function WorkflowFlowPreview() {
  return (
    <ReactFlowProvider>
      <div className="h-full w-full">
        <WorkflowFlowPreviewCanvas />
      </div>
    </ReactFlowProvider>
  )
}
