import { useEffect } from 'hono/jsx'
import { openAppSelectorModal } from '../modals'
import { dashboardTab, isNarrow, setCurrentView, setDashboardTab, setSelectedApp } from '../state'
import {
  AppSelectorChevron,
  DashboardContainer,
  DashboardHeader,
  DashboardTitle,
  SettingsGear,
  Tab,
  TabBar,
  TabContent,
} from '../styles'
import { UnifiedLogs, initUnifiedLogs, scrollLogsToBottom } from './UnifiedLogs'
import { Urls } from './Urls'
import { Vitals, initVitals } from './Vitals'

export function DashboardLanding({ render }: { render: () => void }) {
  useEffect(() => {
    initUnifiedLogs()
    initVitals()
    if (dashboardTab === 'logs') scrollLogsToBottom()
  }, [])

  const narrow = isNarrow || undefined

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

  const switchTab = (tab: typeof dashboardTab) => {
    setDashboardTab(tab)
    render()
    if (tab === 'logs') scrollLogsToBottom()
  }

  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>

      <TabBar centered>
        <Tab active={dashboardTab === 'urls' || undefined} onClick={() => switchTab('urls')}>URLs</Tab>
        <Tab active={dashboardTab === 'logs' || undefined} onClick={() => switchTab('logs')}>Logs</Tab>
        <Tab active={dashboardTab === 'metrics' || undefined} onClick={() => switchTab('metrics')}>Metrics</Tab>
      </TabBar>

      <TabContent active={dashboardTab === 'urls' || undefined}>
        <Urls render={render} />
      </TabContent>

      <TabContent active={dashboardTab === 'logs' || undefined}>
        <UnifiedLogs />
      </TabContent>

      <TabContent active={dashboardTab === 'metrics' || undefined}>
        <Vitals />
      </TabContent>
    </DashboardContainer>
  )
}
