import type { CSSProperties } from 'hono/jsx'
import {
  apps,
  selectedApp,
  setSidebarSection,
  sidebarSection,
} from '../state'
import {
  AppItem,
  AppList,
  SectionSwitcher,
  SectionTab,
  StatusDot,
} from '../styles'

interface AppSelectorProps {
  render: () => void
  onSelect?: () => void
  collapsed?: boolean
  large?: boolean
  switcherStyle?: CSSProperties
  listStyle?: CSSProperties
}

export function AppSelector({ render, onSelect, collapsed, large, switcherStyle, listStyle }: AppSelectorProps) {
  const switchSection = (section: 'apps' | 'tools') => {
    setSidebarSection(section)
    render()
  }

  const regularApps = apps.filter(app => !app.tool)
  const toolApps = apps.filter(app => app.tool)
  const activeApps = sidebarSection === 'apps' ? regularApps : toolApps

  return (
    <>
      {!collapsed && toolApps.length > 0 && (
        <SectionSwitcher style={switcherStyle}>
          <SectionTab active={sidebarSection === 'apps' ? true : undefined} large={large || undefined} onClick={() => switchSection('apps')}>
            Apps
          </SectionTab>
          <SectionTab active={sidebarSection === 'tools' ? true : undefined} large={large || undefined} onClick={() => switchSection('tools')}>
            Tools
          </SectionTab>
        </SectionSwitcher>
      )}
      <AppList style={listStyle}>
        {collapsed && (
          <AppItem
            href="/"
            selected={!selectedApp ? true : undefined}
            style={{ justifyContent: 'center', padding: '10px 12px' }}
            title="Toes"
          >
            <span style={{ fontSize: 18 }}>🐾</span>
          </AppItem>
        )}
        {activeApps.map(app => (
          <AppItem
            key={app.name}
            href={`/app/${app.name}`}
            onClick={onSelect}
            large={large || undefined}
            selected={app.name === selectedApp ? true : undefined}
            style={collapsed ? { justifyContent: 'center', padding: '10px 12px' } : undefined}
            title={collapsed ? app.name : undefined}
          >
            {collapsed ? (
              <span style={{ fontSize: 18 }}>{app.icon}</span>
            ) : (
              <>
                <span style={{ fontSize: large ? 20 : 14 }}>{app.icon}</span>
                {app.name}
                <StatusDot state={app.state} data-app={app.name} data-state={app.state} style={{ marginLeft: 'auto' }} />
              </>
            )}
          </AppItem>
        ))}
      </AppList>
    </>
  )
}
