"use client"

import { Suspense, useState, useEffect } from "react"
import { DndContext, type DragEndEvent, DragOverlay, type DragStartEvent } from "@dnd-kit/core"
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Trash2, Palette, PenTool, Eye, EyeOff, SquarePen } from "lucide-react"

import WireframeCanvas from "@/components/wireframe-canvas"
import PromptSidePanel from "@/components/prompt-side-panel"
import { Canvas } from "@/components/canvas"
import { ComponentPalette } from "@/components/component-palette"
import { PropertiesPanel } from "@/components/properties-panel"
import { useEditorStore } from "@/lib/store"
import { useWireframeIntegration } from "@/lib/wireframe-integration"

interface DualCanvasEditorProps {
  className?: string
  onWireframeGenerated?: (data: any) => void
  onGenerationStart?: () => void
  selectedDevice?: 'desktop' | 'tablet' | 'mobile'
  onDeviceChange?: (device: 'desktop' | 'tablet' | 'mobile') => void
  initialPrompt?: string
}

export function DualCanvasEditor({ 
  className,
  onWireframeGenerated,
  onGenerationStart,
  selectedDevice = 'desktop',
  onDeviceChange,
  initialPrompt
}: DualCanvasEditorProps) {
  const [activeId, setActiveId] = useState<string | null>(null)
  const [canvasMode, setCanvasMode] = useState<'wireframe' | 'components'>('wireframe')
  const { 
    selectedComponent, 
    addComponent, 
    clearAll, 
    components, 
    showWireframes, 
    setShowWireframes,
    wireframeRenderMode,
    setWireframeRenderMode
  } = useEditorStore()

  // Initialize wireframe integration
  useWireframeIntegration()

  // Auto-show wireframes when components are added
  useEffect(() => {
    if (components.length > 0 && components.some(comp => comp.type.startsWith('wireframe-'))) {
      setShowWireframes(true)
    }
  }, [components, setShowWireframes])

  const handleDeviceChange = (device: 'desktop' | 'tablet' | 'mobile') => {
    if (onDeviceChange) {
      onDeviceChange(device)
    }
  }

  const handleDragStart = (event: DragStartEvent) => {
    setActiveId(event.active.id as string)
  }

  const handleDragEnd = (event: DragEndEvent) => {
    setActiveId(null)

    if (event.over?.id === "canvas" && event.active) {
      const componentType = event.active.id as string

      // Get the drop position relative to the canvas
      const canvasRect = event.over.rect
      const dragRect = event.active.rect.current.translated

      if (dragRect && canvasRect) {
        const newComponent = {
          id: `${componentType}-${Date.now()}`,
          type: componentType,
          props: getDefaultProps(componentType),
          position: {
            x: Math.max(0, dragRect.left - canvasRect.left),
            y: Math.max(0, dragRect.top - canvasRect.top),
          },
        }

        addComponent(newComponent)
      }
    }
  }

  const getDefaultProps = (componentType: string): Record<string, any> => {
    const defaults: Record<string, any> = {
      button: { children: "Button", variant: "default" },
      input: { placeholder: "Enter text..." },
      textarea: { placeholder: "Enter text..." },
      card: { title: "Card Title", description: "Card description" },
      checkbox: { label: "Checkbox", checked: false },
      switch: { label: "Switch", checked: false },
      select: { placeholder: "Select option...", options: ["Option 1", "Option 2"] },
      radiogroup: { options: ["Option 1", "Option 2"], value: "Option 1" },
      progress: { value: 50, max: 100 },
      avatar: { fallback: "AB" },
      table: {
        headers: ["Name", "Email", "Role"],
        rows: [
          ["John Doe", "john@example.com", "Admin"],
          ["Jane Smith", "jane@example.com", "User"],
          ["kenil", "kenil@example.com", "User"],
          ["kavya", "kavya@example.com", "User"],
          ["raj", "raj@example.com", "User"]
        ],
      },
      tabs: {
        tabs: [
          { label: "Tab 1", content: "Content 1" },
          { label: "Tab 2", content: "Content 2" },
        ],
      },
      datepicker: { placeholder: "Pick a date", selectedDate: null },
      dialog: { title: "Dialog Title", description: "Dialog description" },
    }

    return defaults[componentType] || {}
  }

  return (
    <div className={`h-full w-full bg-background text-foreground ${className || ''}`}>
      <header className="border-b border-border">
        <div className="mx-auto max-w-6xl px-4 py-3">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-pretty text-lg font-semibold tracking-tight">Dual Canvas Editor</h1>
              <p className="text-sm text-muted-foreground">
                Switch between AI wireframe generation and drag-and-drop component editor.
              </p>
            </div>
            <div className="flex items-center gap-2">
              <Tabs value={canvasMode} onValueChange={(value) => setCanvasMode(value as 'wireframe' | 'components')}>
                <TabsList>
                  <TabsTrigger value="wireframe" className="flex items-center gap-2">
                    <PenTool className="h-4 w-4" />
                    AI Wireframe
                  </TabsTrigger>
                  <TabsTrigger value="components" className="flex items-center gap-2">
                    <Palette className="h-4 w-4" />
                    Components
                  </TabsTrigger>
                </TabsList>
              </Tabs>
              {canvasMode === 'components' && (
                <>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      // Switch to wireframe mode to generate wireframe
                      setCanvasMode('wireframe')
                      // Trigger wireframe generation after a short delay
                      setTimeout(() => {
                        window.dispatchEvent(new CustomEvent("tldraw:generate", { 
                          detail: { 
                            prompt: "Dashboard with header, left sidebar, 3 stats cards, a line chart and a data table, plus footer.",
                            device: selectedDevice 
                          } 
                        }))
                        // Switch back to components mode after generation
                        setTimeout(() => setCanvasMode('components'), 2000)
                      }, 100)
                    }}
                    className="flex items-center gap-2"
                  >
                    <PenTool className="h-4 w-4" />
                    Generate Wireframe
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setShowWireframes(!showWireframes)}
                    className="flex items-center gap-2"
                  >
                    {showWireframes ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                    {showWireframes ? 'Hide Wireframes' : 'Show Wireframes'}
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={clearAll}
                    disabled={components.length === 0}
                    className="flex items-center gap-2"
                  >
                    <Trash2 className="h-4 w-4" />
                    Clear All
                  </Button>
                </>
              )}
            </div>
          </div>
        </div>
      </header>
      
      <div className="h-[calc(100%-80px)] w-full">
        {canvasMode === 'wireframe' ? (
          <div className="h-full w-full flex">
            <div className="flex-1 min-w-0">
              <Suspense fallback={<div className="p-4">Loading canvas…</div>}>
                <WireframeCanvas 
                  className="h-full w-full" 
                  selectedDevice={selectedDevice}
                  onWireframeGenerated={onWireframeGenerated}
                  onGenerationStart={onGenerationStart}
                />
              </Suspense>
            </div>
            <PromptSidePanel 
              className="shrink-0" 
              selectedDevice={selectedDevice}
              onDeviceChange={handleDeviceChange}
              initialPrompt={initialPrompt}
            />
          </div>
        ) : (
          <DndContext onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
            <ResizablePanelGroup direction="horizontal" className="h-full">
              {/* Component Palette Sidebar */}
              <ResizablePanel defaultSize={20} minSize={15} maxSize={30}>
                <div className="h-full bg-sidebar border-r border-sidebar-border">
                  <ComponentPalette />
                </div>
              </ResizablePanel>

              <ResizableHandle className="w-1 bg-border hover:bg-accent transition-colors" />

              {/* Canvas Area */}
              <ResizablePanel defaultSize={selectedComponent ? 60 : 80} minSize={40}>
                <div className="h-full bg-background">
                  <Canvas />
                </div>
              </ResizablePanel>

              {/* Properties Panel - Only show when component is selected */}
              {selectedComponent && (
                <>
                  <ResizableHandle className="w-1 bg-border hover:bg-accent transition-colors" />
                  <ResizablePanel defaultSize={20} minSize={15} maxSize={35}>
                    <div className="h-full bg-sidebar border-l border-sidebar-border">
                      <PropertiesPanel />
                    </div>
                  </ResizablePanel>
                </>
              )}
            </ResizablePanelGroup>

            {/* Drag Overlay */}
            <DragOverlay>
              {activeId ? (
                <div className="drag-overlay p-2 bg-card border border-border rounded-md shadow-lg">{activeId}</div>
              ) : null}
            </DragOverlay>
          </DndContext>
        )}
      </div>
    </div>
  )
}
