import React, { useState, useEffect } from 'react'
import { Minimize2, Maximize2, Square, X } from 'lucide-react'
import { getCurrentWindow } from '@tauri-apps/api/window'

const TitleBar: React.FC = () => {
  const [isMaximized, setIsMaximized] = useState(false)

  useEffect(() => {
    let isActive = true

    const checkMaximized = async () => {
      if (!isActive) return

      try {
        const window = getCurrentWindow()
        const maximized = await window.isMaximized()
        if (isActive) {
          setIsMaximized(maximized)
        }
      } catch (error) {
        console.error('Failed to check window state:', error)
      }
    }

    // Throttled check function
    let checkTimeout: number | null = null
    const throttledCheck = () => {
      if (checkTimeout) clearTimeout(checkTimeout)
      checkTimeout = setTimeout(checkMaximized, 100)
    }

    checkMaximized()

    // Listen for window resize events with throttling
    const setupListener = async () => {
      try {
        const unlisten = await getCurrentWindow().listen('tauri://resize', throttledCheck)
        return unlisten
      } catch (error) {
        console.error('Failed to setup window listener:', error)
        return () => {}
      }
    }

    let unlistenFn: (() => void) | null = null
    setupListener().then(fn => {
      unlistenFn = fn
    })

    return () => {
      isActive = false
      if (checkTimeout) clearTimeout(checkTimeout)
      if (unlistenFn) {
        unlistenFn()
      }
    }
  }, [])

  const handleMinimize = async () => {
    try {
      const window = getCurrentWindow()
      await window.minimize()
    } catch (error) {
      console.error('Failed to minimize window:', error)
    }
  }

  const handleMaximize = async () => {
    try {
      const window = getCurrentWindow()
      await window.toggleMaximize()
      // Update state after toggle
      const maximized = await window.isMaximized()
      setIsMaximized(maximized)
    } catch (error) {
      console.error('Failed to toggle maximize window:', error)
    }
  }

  const handleClose = async () => {
    try {
      const window = getCurrentWindow()
      await window.close()
    } catch (error) {
      console.error('Failed to close window:', error)
    }
  }

  // Handle titlebar drag and double-click
  const handleTitlebarMouseDown = async (e: React.MouseEvent) => {
    // Prevent event bubbling
    e.preventDefault()
    e.stopPropagation()

    if (e.buttons === 1) { // Primary (left) button
      try {
        const window = getCurrentWindow()
        if (e.detail === 2) {
          // Double click - toggle maximize
          await window.toggleMaximize()
          const maximized = await window.isMaximized()
          setIsMaximized(maximized)
        } else {
          // Single click - start dragging with throttling
          setTimeout(async () => {
            try {
              await window.startDragging()
            } catch (error) {
              console.error('Failed to start dragging:', error)
            }
          }, 10)
        }
      } catch (error) {
        console.error('Failed to handle titlebar interaction:', error)
      }
    }
  }

  return (
    <div className="h-8 bg-secondary-800 text-white flex items-center justify-between px-4 select-none">
      <div
        className="flex items-center space-x-2 flex-1"
        onMouseDown={handleTitlebarMouseDown}
      >
        <div className="w-4 h-4 bg-primary-500 rounded-full flex items-center justify-center">
          <span className="text-xs font-bold">M</span>
        </div>
        <span className="text-sm font-medium">MixVideo V2</span>
      </div>

      <div className="flex items-center space-x-1">
        <button
          onClick={(e) => {
            e.stopPropagation()
            handleMinimize()
          }}
          className="w-6 h-6 flex items-center justify-center hover:bg-secondary-700 rounded transition-colors"
        >
          <Minimize2 size={12} />
        </button>
        <button
          onClick={(e) => {
            e.stopPropagation()
            handleMaximize()
          }}
          className="w-6 h-6 flex items-center justify-center hover:bg-secondary-700 rounded transition-colors"
        >
          {isMaximized ? <Square size={12} /> : <Maximize2 size={12} />}
        </button>
        <button
          onClick={(e) => {
            e.stopPropagation()
            handleClose()
          }}
          className="w-6 h-6 flex items-center justify-center hover:bg-red-600 rounded transition-colors"
        >
          <X size={12} />
        </button>
      </div>
    </div>
  )
}

export default TitleBar
