import { buildAppUrl } from '../../shared/urls'
import { navigate } from '../router'
import { apps, isNarrow } from '../state'
import {
  EmptyState,
  Tile,
  TileGrid,
  TileIcon,
  TileName,
  TileStatus,
} from '../styles'

export function Urls({ render }: { render: () => void }) {
  const nonTools = apps.filter(a => !a.tool)

  if (nonTools.length === 0) {
    return <EmptyState>No apps installed</EmptyState>
  }

  return (
    <TileGrid narrow={isNarrow || undefined}>
      {nonTools.map(app => {
        const url = app.tunnelUrl || buildAppUrl(app.name, location.origin)
        const running = app.state === 'running'
        const appPage = `/app/${app.name}`

        const openAppPage = (e: MouseEvent) => {
          e.preventDefault()
          e.stopPropagation()
          navigate(appPage)
        }

        return (
          <Tile
            key={app.name}
            href={running ? url : appPage}
            target={running ? '_blank' : undefined}
            narrow={isNarrow || undefined}
          >
            <TileStatus state={app.state} onClick={openAppPage} />
            <TileIcon>{app.icon}</TileIcon>
            <TileName>{app.name}</TileName>
          </Tile>
        )
      })}
    </TileGrid>
  )
}
