import { useEffect } from 'hono/jsx'
import { navigate } from '../router'
import { dashboardTab, isNarrow, setMobileSidebar } from '../state'
import {
  HamburgerButton,
  HamburgerLine,
  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 = () => {
    navigate('/settings')
  }

  const switchTab = (tab: typeof dashboardTab) => {
    navigate(tab === 'urls' ? '/' : `/${tab}`)
    if (tab === 'logs') scrollLogsToBottom()
  }

  return (
    <DashboardContainer narrow={narrow} relative>
      <SettingsGear
        onClick={openSettings}
        title="Settings"
        style={{ position: 'absolute', top: 16, right: 16 }}
      >
        ⚙️
      </SettingsGear>
      {isNarrow && (
        <HamburgerButton
          onClick={() => { setMobileSidebar(true); render() }}
          title="Show apps"
          style={{ position: 'absolute', top: 16, left: 16 }}
        >
          <HamburgerLine />
          <HamburgerLine />
          <HamburgerLine />
        </HamburgerButton>
      )}
      <DashboardHeader>
        <DashboardTitle narrow={narrow}>
          🐾 Toes
        </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>
  )
}
