'use client'

import { useState, useRef, useEffect, useLayoutEffect } from 'react'
import Editor from '@monaco-editor/react'
import { Play, Trash2, FolderOpen, Save, Undo2, Redo2, User, Wrench, Plus, X } from 'lucide-react'

export default function Executor() {
  const [settings, setSettings] = useState(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('settings')
      if (saved) {
        try {
          return JSON.parse(saved)
        } catch (e) {
          return null
        }
      }
    }
    return null
  })

  const [tabs, setTabs] = useState(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('code')
      if (saved) {
        try {
          return JSON.parse(saved)
        } catch (e) {
          return [{ id: '1', name: 'Script 1', code: '-- Welcome to Aetheris! моя мать шлюха' }]
        }
      }
    }
    return [{ id: '1', name: 'Script 1', code: '-- Welcome to Aetheris! моя мать шлюха' }]
  })
  
  const [active, setActive] = useState(() => {
    if (typeof window !== 'undefined') {
      const savedActive = localStorage.getItem('activeTab')
      const saved = localStorage.getItem('code')
      
      if (saved) {
        try {
          const parsed = JSON.parse(saved)
          if (savedActive && parsed.some(tab => tab.id === savedActive)) {
            return savedActive
          }
          return parsed[0]?.id || '1'
        } catch (e) {
          return '1'
        }
      }
    }
    return '1'
  })
  
  const [closing, setClosing] = useState(null)
  const [style, setStyle] = useState({})
  const [closedTabs, setClosedTabs] = useState([])
  const [contextMenu, setContextMenu] = useState(null)
  const [connected, setConnected] = useState(false)
  const refs = useRef({})
  const editor = useRef(null)
  const monaco = useRef(null)

  const updatePos = () => {
    const btn = refs.current[active]
    if (btn) {
      const { offsetLeft, offsetWidth } = btn
      setStyle({
        left: offsetLeft,
        width: offsetWidth,
      })
    }
  }

  useLayoutEffect(() => {
    updatePos()
  }, [active, tabs])

  useEffect(() => {
    window.addEventListener('resize', updatePos)
    return () => window.removeEventListener('resize', updatePos)
  }, [active])

  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('code', JSON.stringify(tabs))
    }
  }, [tabs])

  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('activeTab', active)
    }
  }, [active])

  useEffect(() => {
    const handleKey = (e) => {
      if (e.ctrlKey && e.key >= '1' && e.key <= '9') {
        e.preventDefault()
        const index = parseInt(e.key) - 1
        if (tabs[index]) {
          setActive(tabs[index].id)
        }
      }
    }

    const handleClick = () => {
      setContextMenu(null)
    }

    const handleSettingsChange = (e) => {
      setSettings(e.detail)
    }

    window.addEventListener('keydown', handleKey)
    window.addEventListener('click', handleClick)
    window.addEventListener('settingsChanged', handleSettingsChange)
    return () => {
      window.removeEventListener('keydown', handleKey)
      window.removeEventListener('click', handleClick)
      window.removeEventListener('settingsChanged', handleSettingsChange)
    }
  }, [tabs])

  const mount = (ed, mon) => {
    editor.current = ed
    monaco.current = mon
    
    mon.editor.defineTheme('aetheris-dark', {
      base: 'vs-dark',
      inherit: true,
      rules: [],
      colors: {
        'editor.background': '#0a0a0a',
        'editor.foreground': '#ffffff',
        'editor.lineHighlightBackground': '#121212',
        'editorLineNumber.foreground': '#565656',
        'editorLineNumber.activeForeground': '#a0a0a0',
        'editor.selectionBackground': '#264f78',
        'editor.inactiveSelectionBackground': '#1a1a1a',
        'editorCursor.foreground': '#ffffff',
        'editorWhitespace.foreground': '#313131',
      }
    })
    mon.editor.setTheme('aetheris-dark')
    
    ed.focus()
  }

  const update = (id, code) => {
    setTabs(tabs.map(tab => 
      tab.id === id ? { ...tab, code } : tab
    ))
  }

  // getNextScriptNumber
  const getNextScriptNumber = () => {
    const existingNumbers = tabs.map(tab => {
      const match = tab.name.match(/Script (\d+)/)
      return match ? parseInt(match[1]) : 0
    }).sort((a, b) => a - b)
    
    for (let i = 1; i <= existingNumbers.length + 1; i++) {
      if (!existingNumbers.includes(i)) {
        return i
      }
    }
    return 1
  }

  const add = () => {
    const id = String(Date.now())
    const tab = {
      id,
      name: `Script ${getNextScriptNumber()}`,
      code: ''
    }
    setTabs([...tabs, tab])
    setActive(id)
  }

  const close = (id, e) => {
    e.stopPropagation()
    
    setClosing(id)
    
    const tabToClose = tabs.find(tab => tab.id === id)
    if (tabToClose) {
      setClosedTabs([...closedTabs, { tab: tabToClose, timestamp: Date.now() }])
    }
    
    setTimeout(() => {
      const currentIndex = tabs.findIndex(tab => tab.id === id)
      const newTabs = tabs.filter(tab => tab.id !== id)
      setTabs(newTabs)
      
      if (active === id && newTabs.length > 0) {
        const nextIndex = currentIndex >= newTabs.length ? newTabs.length - 1 : currentIndex
        setActive(newTabs[nextIndex].id)
      } else if (newTabs.length === 0) {
        setActive(null)
      }
      
      setClosing(null)
    }, 200)
  }

  // undoClose
  const undoClose = () => {
    if (closedTabs.length > 0) {
      const lastClosed = closedTabs[closedTabs.length - 1]
      setTabs([...tabs, lastClosed.tab])
      setActive(lastClosed.tab.id)
      setClosedTabs(closedTabs.slice(0, -1))
    }
    setContextMenu(null)
  }

  const execute = () => {
    const current = tabs.find(tab => tab.id === active)
  }

  const clear = () => {
    if (editor.current) {
      editor.current.setValue('')
    }
    update(active, '')
  }

  const undo = () => {
    if (editor.current) {
      editor.current.trigger('keyboard', 'undo')
    }
  }

  const redo = () => {
    if (editor.current) {
      editor.current.trigger('keyboard', 'redo')
    }
  }

  // openFile
  const openFile = () => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.lua,.txt,.luau'
    input.onchange = (e) => {
      const file = e.target.files[0]
      if (file) {
        const reader = new FileReader()
        reader.onload = (event) => {
          const content = event.target.result
          update(active, content)
          if (editor.current) {
            editor.current.setValue(content)
          }
        }
        reader.readAsText(file)
      }
    }
    input.click()
  }

  // saveFile
  const saveFile = () => {
    const current = tabs.find(tab => tab.id === active)
    if (!current) return
    
    const blob = new Blob([current.code], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${current.name}.lua`
    a.click()
    URL.revokeObjectURL(url)
  }

  const tabsRef = useRef(tabs)
  
  useEffect(() => {
    tabsRef.current = tabs
  }, [tabs])

  useEffect(() => {
    if (editor.current) {
      const current = tabsRef.current.find(tab => tab.id === active)
      if (current && editor.current.getValue() !== current.code) {
        editor.current.setValue(current.code)
      }
      editor.current.focus()
    }
  }, [active])

  const current = tabs.find(tab => tab.id === active)

  const toolbarPosition = settings?.editor?.toolbarPosition || 'bottom'
  const fontSize = settings?.editor?.fontSize || 14
  const tabSize = settings?.editor?.tabSize || 2
  const wordWrap = settings?.editor?.wordWrap !== false
  const minimap = settings?.editor?.minimap || false
  const lineNumbers = settings?.editor?.lineNumbers !== false
  const compactSidebar = settings?.interface?.compactSidebar || false
  const sidebarWidth = compactSidebar ? 200 : 280
  const enableAnimations = settings?.interface?.enableAnimations !== false

  const ToolbarComponent = () => (
    <div 
      className={toolbarPosition === 'bottom' ? 'fixed bottom-3 right-3' : 'px-3 pb-0'} 
      style={{ 
        paddingTop: toolbarPosition === 'top' ? '12px' : undefined,
        left: toolbarPosition === 'bottom' ? `${sidebarWidth + 12}px` : undefined,
        transition: enableAnimations ? 'left 300ms ease-out' : 'none',
      }}
    >
      <div 
        className="flex items-center gap-3 p-4 rounded-xl border backdrop-blur-xl"
        style={{ 
          backgroundColor: 'rgba(10, 10, 10, 0.8)',
          borderColor: '#1a1a1a',
        }}
      >
        <button
          onClick={(e) => {
            execute()
            e.currentTarget.blur()
          }}
          className="btn-execute flex items-center gap-2 px-4 py-2 rounded-2xl font-medium"
          style={{ cursor: 'pointer' }}
        >
          <Play className="h-4 w-4" />
          Execute
        </button>

        <div 
          className="h-6 w-px"
          style={{ backgroundColor: '#1a1a1a' }}
        />

        <button
          onClick={(e) => {
            undo()
            e.currentTarget.blur()
          }}
          className="btn-toolbar flex items-center gap-2 px-3 py-2 rounded-2xl font-medium"
          style={{ cursor: 'pointer' }}
        >
          <Undo2 className="h-4 w-4" />
          Undo
        </button>

        <button
          onClick={(e) => {
            redo()
            e.currentTarget.blur()
          }}
          className="btn-toolbar flex items-center gap-2 px-3 py-2 rounded-2xl font-medium"
          style={{ cursor: 'pointer' }}
        >
          Redo
          <Redo2 className="h-4 w-4" />
        </button>

        <div 
          className="h-6 w-px"
          style={{ backgroundColor: '#1f0c0cff' }}
        />

        <button
          onClick={(e) => {
            openFile()
            e.currentTarget.blur()
          }}
          className="btn-toolbar flex items-center gap-2 px-3 py-2 rounded-2xl font-medium"
          style={{ cursor: 'pointer' }}
        >
          <FolderOpen className="h-4 w-4" />
          Open
        </button>

        <button
          onClick={(e) => {
            saveFile()
            e.currentTarget.blur()
          }}
          className="btn-toolbar flex items-center gap-2 px-3 py-2 rounded-2xl font-medium"
          style={{ cursor: 'pointer' }}
        >
          <Save className="h-4 w-4" />
          Save
        </button>

        <button
          onClick={(e) => {
            clear()
            e.currentTarget.blur()
          }}
          className="btn-toolbar flex items-center gap-2 px-3 py-2 rounded-2xl font-medium"
          style={{ cursor: 'pointer' }}
        >
          <Trash2 className="h-4 w-4" />
          Clear
        </button>

        <div 
          className="h-6 w-px"
          style={{ backgroundColor: '#1a1a1a' }}
        />

        <button
          onClick={(e) => {
            e.currentTarget.blur()
          }}
          className="btn-toolbar flex items-center gap-2 px-3 py-2 rounded-2xl font-medium"
          style={{ cursor: 'pointer' }}
        >
          <User className="h-4 w-4" />
          R6
        </button>

        <button
          onClick={(e) => {
            e.currentTarget.blur()
          }}
          className="btn-toolbar flex items-center gap-2 px-3 py-2 rounded-2xl font-medium"
          style={{ cursor: 'pointer' }}
        >
          <Wrench className="h-4 w-4" />
          Btools
        </button>

        <div className="flex-1" />

        <div 
          className="flex items-center gap-2 px-2 py-1 rounded-2xl"
          style={{
            backgroundColor: connected ? 'rgba(34, 197, 94, 0.1)' : 'rgba(239, 68, 68, 0.1)',
            border: connected ? '1px solid rgba(34, 197, 94, 0.3)' : '1px solid rgba(239, 68, 68, 0.3)',
            userSelect: 'none',
          }}
        >
          <div 
            className="w-1.5 h-1.5 rounded-full"
            style={{
              backgroundColor: connected ? '#22c55e' : '#ef4444',
              boxShadow: connected ? '0 0 6px rgba(34, 197, 94, 0.6)' : '0 0 6px rgba(239, 68, 68, 0.6)',
            }}
          />
          <span 
            className="text-xs font-medium"
            style={{ color: connected ? '#22c55e' : '#ef4444' }}
          >
            {connected ? 'Connected' : 'Not connected'}
          </span>
        </div>
      </div>
    </div>
  )

  return (
    <>
      {toolbarPosition === 'top' && <ToolbarComponent />}

      <div className="px-3 pt-3 pb-0">
        <div 
          className="rounded-xl border backdrop-blur-xl overflow-hidden"
          style={{ 
            backgroundColor: 'rgba(10, 10, 10, 0.8)',
            borderColor: '#1a1a1a',
          }}
        >
          <div className="flex items-center px-2 py-1" onContextMenu={(e) => {
            e.preventDefault()
            setContextMenu({ x: e.clientX, y: e.clientY })
          }}>
            <div 
              className="flex items-center gap-1 flex-1 relative overflow-visible py-1"
              onMouseDown={(e) => {
                if (e.button === 1 && e.target === e.currentTarget) {
                  e.preventDefault()
                  add()
                }
              }}
            >
              {tabs.length === 0 ? (
                <div 
                  className="px-3 py-1.5 text-sm" 
                  style={{ color: '#565656' }}
                  onMouseDown={(e) => {
                    if (e.button === 1) {
                      e.preventDefault()
                      add()
                    }
                  }}
                >
                  No active tabs. The void awaits... 
                </div>
              ) : (
                <>
                  {style.width !== undefined && (
                    <div
                      className="absolute rounded-xl transition-all duration-300 ease-out pointer-events-none"
                      style={{
                        left: style.left,
                        width: style.width,
                        height: '32px',
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        boxShadow: '0 0 20px rgba(255, 255, 255, 0.2), 0 0 10px rgba(255, 255, 255, 0.1)',
                        zIndex: 20,
                      }}
                    />
                  )}
                  
                  {tabs.map(tab => {
                    const isActive = active === tab.id
                    const isClosing = closing === tab.id
                    return (
                      <button
                        key={tab.id}
                        ref={(el) => {
                          refs.current[tab.id] = el
                          if (el && isActive) {
                            requestAnimationFrame(() => {
                              const { offsetLeft, offsetWidth } = el
                              setStyle({
                                left: offsetLeft,
                                width: offsetWidth,
                              })
                            })
                          }
                        }}
                        onClick={() => setActive(tab.id)}
                        onMouseDown={(e) => {
                          if (e.button === 1) {
                            e.preventDefault()
                            close(tab.id, e)
                          }
                        }}
                        className="group flex items-center gap-2 px-3 py-1.5 rounded-xl text-sm font-medium relative"
                        style={{
                          color: isActive ? '#000000' : '#a0a0a0',
                          backgroundColor: 'transparent',
                          border: isActive ? 'none' : '1px solid #2a2a2a',
                          transition: 'color 300ms ease-out, opacity 200ms ease-out, max-width 200ms ease-out, padding 200ms ease-out, margin 200ms ease-out, border-color 200ms ease-out, gap 200ms ease-out',
                          opacity: isClosing ? 0 : 1,
                          maxWidth: isClosing ? '0px' : '200px',
                          paddingLeft: isClosing ? '0px' : '12px',
                          paddingRight: isClosing ? '0px' : '12px',
                          marginLeft: isClosing ? '0px' : undefined,
                          marginRight: isClosing ? '0px' : undefined,
                          overflow: 'hidden',
                          whiteSpace: 'nowrap',
                          zIndex: isActive ? 30 : 10,
                          cursor: 'pointer',
                        }}
                        onMouseEnter={(e) => {
                          if (!isActive) {
                            e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.03)'
                            e.currentTarget.style.borderColor = '#3a3a3a'
                          }
                        }}
                        onMouseLeave={(e) => {
                          if (!isActive) {
                            e.currentTarget.style.backgroundColor = 'transparent'
                            e.currentTarget.style.borderColor = '#2a2a2a'
                          }
                        }}
                      >
                        <span>{tab.name}</span>
                        {isActive && (
                          <span
                            onClick={(e) => {
                              e.stopPropagation()
                              close(tab.id, e)
                            }}
                            className="transition-opacity cursor-pointer"
                            style={{ color: '#565656', opacity: 1 }}
                            onMouseEnter={(e) => {
                              e.currentTarget.style.color = '#000000'
                            }}
                            onMouseLeave={(e) => {
                              e.currentTarget.style.color = '#565656'
                            }}
                          >
                            <X className="h-3 w-3" />
                          </span>
                        )}
                      </button>
                    )
                  })}
                </>
              )}
            </div>
            
            <button
              onClick={add}
              className="flex items-center justify-center w-8 h-8 rounded-xl transition-all duration-200"
              style={{
                backgroundColor: 'transparent',
                color: '#a0a0a0',
                cursor: 'pointer',
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = '#1a1a1a'
                e.currentTarget.style.color = '#ffffff'
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = 'transparent'
                e.currentTarget.style.color = '#a0a0a0'
              }}
            >
              <Plus className="h-4 w-4" />
            </button>
          </div>
        </div>
      </div>

      <div className="px-3 pt-2 pb-3">
        <div 
          className="rounded-xl border backdrop-blur-xl overflow-hidden"
          style={{ 
            backgroundColor: 'rgba(10, 10, 10, 0.8)',
            borderColor: '#1a1a1a',
            height: toolbarPosition === 'top' ? 'calc(100vh - 160px)' : 'calc(100vh - 160px)',
          }}
        >
          {tabs.length === 0 ? (
            <div className="flex items-center justify-center h-full" style={{ color: '#565656', userSelect: 'none' }}>
              <div className="text-center">
                <img 
                  src="/kotostb.gif" 
                  alt="No scripts" 
                  className="w-24 h-24 mx-auto mb-4 opacity-30"
                  draggable="false"
                />
                <div className="text-lg">No scripts here...</div>
                <div className="text-sm mt-2">Click the + button to create one</div>
              </div>
            </div>
          ) : (
            <Editor
              height="100%"
              defaultLanguage="lua"
              value={current?.code || ''}
              onChange={(value) => update(active, value || '')}
              onMount={mount}
              options={{
                minimap: { enabled: minimap },
                fontSize: fontSize,
                fontFamily: 'Consolas, "Courier New", monospace',
                lineNumbers: lineNumbers ? 'on' : 'off',
                scrollBeyondLastLine: false,
                automaticLayout: true,
                tabSize: tabSize,
                wordWrap: wordWrap ? 'on' : 'off',
                padding: { top: 16, bottom: 16 },
                cursorSmoothCaretAnimation: 'on',
                smoothScrolling: true,
                cursorBlinking: 'smooth',
                placeholder: '-- Welcome to Aetheris! Start typing...',
              }}
            />
          )}
        </div>
      </div>

      {contextMenu && (
        <div
          className="fixed rounded-xl border backdrop-blur-xl shadow-lg"
          style={{
            left: contextMenu.x,
            top: contextMenu.y,
            backgroundColor: 'rgba(10, 10, 10, 0.95)',
            borderColor: '#1a1a1a',
            zIndex: 1000,
          }}
          onClick={(e) => e.stopPropagation()}
        >
          <button
            onClick={undoClose}
            disabled={closedTabs.length === 0}
            className="w-full flex items-center gap-2 px-4 py-2 text-sm transition-colors"
            style={{
              color: closedTabs.length === 0 ? '#565656' : '#ffffff',
              cursor: closedTabs.length === 0 ? 'not-allowed' : 'pointer',
            }}
            onMouseEnter={(e) => {
              if (closedTabs.length > 0) {
                e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.1)'
              }
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = 'transparent'
            }}
          >
            <Undo2 className="h-4 w-4" />
            Undo Close Tab
          </button>
        </div>
      )}

      {toolbarPosition === 'bottom' && <ToolbarComponent />}
    </>
  )
}
