import { buildAppUrl } from '../../shared/urls'
import { navigate } from '../router'
import { apps } from '../state'
import {
  EmptyState,
  Tile,
  TileGrid,
  TileIcon,
  TileName,
  TilePort,
  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>
      {nonTools.map(app => {
        const url = 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}
          >
            <TileStatus state={app.state} onClick={openAppPage} />
            <TileIcon>{app.icon}</TileIcon>
            <TileName>{app.name}</TileName>
            <TilePort>{app.port ? `:${app.port}` : '\u2014'}</TilePort>
          </Tile>
        )
      })}
    </TileGrid>
  )
}
