import { useEffect } from 'hono/jsx'
import { openAppSelectorModal } from '../modals'
import { apps, isNarrow, setCurrentView, setSelectedApp } from '../state'
import {
  AppSelectorChevron,
  DashboardContainer,
  DashboardHeader,
  DashboardTitle,
  SettingsGear,
  StatusDot,
  StatusDotLink,
  StatusDotsRow,
} from '../styles'
import { update } from '../update'
import { UnifiedLogs, initUnifiedLogs } from './UnifiedLogs'
import { Vitals, initVitals } from './Vitals'

let activeTooltip: string | null = null

export function DashboardLanding({ render }: { render: () => void }) {
  useEffect(() => {
    initUnifiedLogs()
    initVitals()
  }, [])

  const narrow = isNarrow || undefined

  const openSettings = () => {
    setSelectedApp(null)
    setCurrentView('settings')
    render()
  }

  return (
    <DashboardContainer narrow={narrow} relative>
      <SettingsGear
        onClick={openSettings}
        title="Settings"
        style={{ position: 'absolute', top: 16, right: 16 }}
      >
        ⚙️
      </SettingsGear>
      <DashboardHeader>
        <DashboardTitle narrow={narrow}>
          🐾 Toes
          {isNarrow && (
            <AppSelectorChevron onClick={() => openAppSelectorModal(render)}>
              ▼
            </AppSelectorChevron>
          )}
        </DashboardTitle>
      </DashboardHeader>

      <StatusDotsRow>
        {[...apps.filter(a => !a.tool), ...apps.filter(a => a.tool)].map(app => (
          <StatusDotLink
            key={app.name}
            data-tooltip={app.name}
            tooltipVisible={activeTooltip === app.name || undefined}
            onClick={(e: Event) => {
              e.preventDefault()
              if (isNarrow && activeTooltip !== app.name) {
                activeTooltip = app.name
                render()
                return
              }
              activeTooltip = null
              setSelectedApp(app.name)
              update()
            }}
          >
            <StatusDot state={app.state} data-app={app.name} />
          </StatusDotLink>
        ))}
      </StatusDotsRow>

      <Vitals />

      <UnifiedLogs />
    </DashboardContainer>
  )
}
