"use client"

import { useEffect } from 'react'
import { useEditorStore } from './store'
import { wireframeConverter, ParsedWireframe } from './wireframe-converter'

/**
 * Hook to integrate wireframe data from the backend with the component canvas
 */
export function useWireframeIntegration() {
  const { 
    addWireframe, 
    setCurrentWireframe, 
    addComponent, 
    currentWireframe,
    showWireframes,
    clearWireframeComponents,
    wireframeRenderMode
  } = useEditorStore()

  // Listen for wireframe generation events from the TLDraw canvas
  useEffect(() => {
    const handleWireframeGenerated = (event: CustomEvent<{
      svgData: string
      deviceType: 'desktop' | 'tablet' | 'mobile'
      prompt: string
    }>) => {
      try {
        const { svgData, deviceType, prompt } = event.detail
        
        // Parse the SVG wireframe
        const parsedWireframe = wireframeConverter.parseSVGToWireframe(svgData, deviceType)
        
        // Create wireframe data
        const wireframeData = {
          id: `wireframe-${Date.now()}`,
          name: `Wireframe - ${prompt.substring(0, 50)}...`,
          deviceType,
          data: parsedWireframe,
          createdAt: new Date(),
          updatedAt: new Date()
        }

        // Add to store
        addWireframe(wireframeData)
        setCurrentWireframe(wireframeData)

        // Clear old wireframe components before adding new ones
        clearWireframeComponents()
        
        // Convert to a single exact-SVG component if showing wireframes in SVG mode
        if (showWireframes && wireframeRenderMode === 'svg') {
          const component = wireframeConverter.convertToSVGComponent(parsedWireframe)
          addComponent(component)
        }

        console.log('Wireframe integrated:', wireframeData)
      } catch (error) {
        console.error('Error integrating wireframe:', error)
      }
    }

    // Listen for wireframe generation events
    window.addEventListener('wireframe:generated', handleWireframeGenerated as EventListener)

    return () => {
      window.removeEventListener('wireframe:generated', handleWireframeGenerated as EventListener)
    }
  }, [addWireframe, setCurrentWireframe, addComponent, showWireframes, clearWireframeComponents])

  // Handle wireframe display toggle
  useEffect(() => {
    if (showWireframes && currentWireframe) {
      // Clear old wireframe components first
      clearWireframeComponents()
      
      // Convert current wireframe to a single SVG component for display
      const component = wireframeConverter.convertToSVGComponent(currentWireframe.data)
      addComponent(component)
    } else if (!showWireframes) {
      // Clear wireframe components when hiding wireframes
      clearWireframeComponents()
    }
  }, [showWireframes, currentWireframe, addComponent, clearWireframeComponents])

  return {
    currentWireframe,
    showWireframes
  }
}

/**
 * Service to handle wireframe data conversion and management
 */
export class WireframeIntegrationService {
  private static instance: WireframeIntegrationService

  static getInstance(): WireframeIntegrationService {
    if (!WireframeIntegrationService.instance) {
      WireframeIntegrationService.instance = new WireframeIntegrationService()
    }
    return WireframeIntegrationService.instance
  }

  /**
   * Convert SVG wireframe to components and add to canvas
   */
  convertAndAddWireframe(
    svgData: string, 
    deviceType: 'desktop' | 'tablet' | 'mobile',
    prompt: string
  ) {
    try {
      // Parse the SVG wireframe
      const parsedWireframe = wireframeConverter.parseSVGToWireframe(svgData, deviceType)
      
      // Create wireframe data
      const wireframeData = {
        id: `wireframe-${Date.now()}`,
        name: `Wireframe - ${prompt.substring(0, 50)}...`,
        deviceType,
        data: parsedWireframe,
        createdAt: new Date(),
        updatedAt: new Date()
      }

      // Dispatch event to update store
      window.dispatchEvent(new CustomEvent('wireframe:generated', {
        detail: { svgData, deviceType, prompt }
      }))

      return wireframeData
    } catch (error) {
      console.error('Error converting wireframe:', error)
      throw error
    }
  }

  /**
   * Convert wireframe to individual components
   */
  convertToComponents(wireframe: ParsedWireframe) {
    return wireframeConverter.convertToComponents(wireframe)
  }

  /**
   * Convert wireframe to single SVG component
   */
  convertToSVGComponent(wireframe: ParsedWireframe) {
    return wireframeConverter.convertToSVGComponent(wireframe)
  }
}

export const wireframeIntegrationService = WireframeIntegrationService.getInstance()
