import { ScoreCard, SectionCard, StaleBadge } from '@overdeck/deck-ui'
import { adapterIdForPanel } from '../../lib/collector-client'
import { scoreCardPropsFor } from '../../lib/overview-mappers'
import type { GolivePanelData } from '../../lib/panel-data'
import { useCollectorState } from '../../lib/collector-queries'
import { CollectorQueryBoundary } from '../shared/CollectorQueryBoundary'

export function ProjectsContent() {
  const stateQuery = useCollectorState()
  return (
    <CollectorQueryBoundary query={stateQuery}>
      {(state) => {
        const scoreboardPanel = state.panels.find((panel) => panel.id === 'scoreboard')
        const scoreboardData = scoreboardPanel?.data as GolivePanelData | undefined
        const status = state.adapters.find((adapter) => adapter.id === adapterIdForPanel('scoreboard'))

        if (!scoreboardData || scoreboardData.repos.length === 0) {
          return <div className="text-fg-muted">No projects data in collector state.</div>
        }

        return (
          <div className="flex flex-col gap-3.5">
            {scoreboardData.repos.some((repo) => repo.churn) ? (
              <SectionCard title="Churn callouts">
                {scoreboardData.repos
                  .filter((repo) => repo.churn)
                  .map((repo) => (
                    <p key={repo.repo} className="text-[12px] text-danger">
                      {repo.repo} is flat for 9d while receiving {repo.commitsSinceLastWorksDelta} commits — churn
                    </p>
                  ))}
              </SectionCard>
            ) : null}
            <div className="grid grid-cols-3 gap-3">
              {scoreboardData.repos.map((repo, index) => (
                <SectionCard
                  key={repo.repo}
                  title={repo.repo}
                  titleBadge={index === 0 && status ? <StaleBadge status={status} /> : undefined}
                  action={{ label: 'open →', href: `/projects/${repo.repo}` }}
                >
                  <ScoreCard {...scoreCardPropsFor(repo)} barColorClassName={index === 2 ? 'bg-teal' : undefined} />
                </SectionCard>
              ))}
            </div>
          </div>
        )
      }}
    </CollectorQueryBoundary>
  )
}
