"use client"

import { useDroppable } from "@dnd-kit/core"
import { useEffect, useRef, useState } from "react"
import { useEditorStore } from "@/lib/store"
import { ComponentRenderer } from "@/components/component-renderer"
import { MousePointer } from "lucide-react"

export function Canvas() {
  const { components, selectComponent, moveComponent } = useEditorStore()
  const containerRef = useRef<HTMLDivElement | null>(null)
  const [dragState, setDragState] = useState<{
    id: string
    offsetX: number
    offsetY: number
  } | null>(null)

  const { setNodeRef, isOver } = useDroppable({
    id: "canvas",
  })

  return (
    <div className="h-full flex flex-col">
      {/* Canvas Header */}
      <div className="p-4 border-b border-border bg-card">
        <h2 className="text-lg font-semibold text-card-foreground">Canvas</h2>
        <p className="text-sm text-muted-foreground">Drag components here to build your interface</p>
      </div>

      {/* Canvas Area */}
      <div
        ref={(node) => {
          setNodeRef(node)
          containerRef.current = node
        }}
        className={`flex-1 relative canvas-grid overflow-auto ${isOver ? "drop-zone-active" : ""}`}
        onClick={() => selectComponent(null)}
        onMouseMove={(e) => {
          if (!dragState || !containerRef.current) return
          const rect = containerRef.current.getBoundingClientRect()
          const x = e.clientX - rect.left - dragState.offsetX + containerRef.current.scrollLeft
          const y = e.clientY - rect.top - dragState.offsetY + containerRef.current.scrollTop
          moveComponent(dragState.id, { x: Math.max(0, x), y: Math.max(0, y) })
        }}
        onMouseUp={() => setDragState(null)}
        onMouseLeave={() => setDragState(null)}
      >
        {components.length === 0 ? (
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="text-center">
              <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-muted flex items-center justify-center">
                <MousePointer className="w-8 h-8 text-muted-foreground" />
              </div>
              <h3 className="text-lg font-medium text-foreground mb-2">Start Building</h3>
              <p className="text-muted-foreground max-w-sm">
                Drag components from the sidebar to start building your interface
              </p>
            </div>
          </div>
        ) : (
          components.map((component) => (
            <ComponentRenderer
              key={component.id}
              component={component}
              onClick={(e) => {
                e.stopPropagation()
                selectComponent(component)
              }}
              onMouseDown={(e) => {
                const target = e.currentTarget as HTMLDivElement
                const rect = target.getBoundingClientRect()
                const offsetX = e.clientX - rect.left
                const offsetY = e.clientY - rect.top
                setDragState({ id: component.id, offsetX, offsetY })
              }}
            />
          ))
        )}
      </div>
    </div>
  )
}
