import { Styles } from '@because/forge'
import { openNewAppModal } from '../modals'
import { apps, currentView, isNarrow, mobileSidebar, selectedApp, setMobileSidebar } from '../state'
import {
  HamburgerButton,
  HamburgerLine,
  Layout,
  Main,
  MainContent as MainContentContainer,
  MainHeader,
  MainTitle,
  NewAppButton,
} from '../styles'
import { AppDetail } from './AppDetail'
import { AppSelector } from './AppSelector'
import { DashboardLanding } from './DashboardLanding'
import { Modal } from './modal'
import { SettingsPage } from './SettingsPage'
import { Sidebar } from './Sidebar'

function MobileSidebar({ render }: { render: () => void }) {
  return (
    <Main>
      <MainHeader>
        <MainTitle>
          <HamburgerButton onClick={() => { setMobileSidebar(false); render() }} title="Hide apps">
            <HamburgerLine />
            <HamburgerLine />
            <HamburgerLine />
          </HamburgerButton>
          <a href="/" style={{ textDecoration: 'none', color: 'inherit' }}>🐾 Toes</a>
        </MainTitle>
      </MainHeader>
      <MainContentContainer>
        <AppSelector render={render} large />
        <div style={{ padding: '12px 16px' }}>
          <NewAppButton onClick={openNewAppModal}>+ New App</NewAppButton>
        </div>
      </MainContentContainer>
    </Main>
  )
}

function MainContent({ render }: { render: () => void }) {
  if (isNarrow && mobileSidebar) return <MobileSidebar render={render} />
  const selected = apps.find(a => a.name === selectedApp)
  if (selected) return <AppDetail app={selected} render={render} />
  if (currentView === 'settings') return <SettingsPage render={render} />
  return <DashboardLanding render={render} />
}

export function Dashboard({ render }: { render: () => void }) {
  return (
    <Layout>
      <Styles />
      {!isNarrow && <Sidebar render={render} />}
      <MainContent render={render} />
      <Modal />
    </Layout>
  )
}
