import m from 'mithril'
import render from 'mithril-node-render'
import {NavHelper} from './helpers/nav.ts'

export default async (
  eleventyConfig: any,
  data: any,
  nav: ReturnType<typeof NavHelper>
) => {
  const slugify = eleventyConfig.getFilter("slugify")

  const branchesWithWorkInProgress = data.branches.filter(branch => branch.ahead > 0)
  const branchesFullyMerged = data.branches.filter(branch => branch.ahead === 0)

  const branchCards = (branches) => {
    return m('div', {class: "d-flex flex-wrap"}, branches.map((branch) => {
      return branch.repoName === data.branchInfo.repoName
        ? m('div', {class: "card bezel-gray m-2 flex-grow-1", style: "flex-basis: 20rem; max-width: 20rem;"}, [
            m('div', {class: "card-header"}, [
              m('a', {
                class: "card-title",
                href: `${data.reposPath}/${slugify(branch.repoName)}/branches/${slugify(branch.branchName)}/branches`
              }, branch.branchName),
              branch.branchName === data.branchInfo.branchName
                ? m('div', {class: "badge rounded-pill bg-secondary mx-1"}, 'current') : null,
              branch.branchName === data.reposConfig.repos[branch.repoName].defaultBranch
                ? m('div', {class: "badge rounded-pill bg-info text-dark mx-1"}, 'default') : null,
            ]),
            m('div', {class: "card-body"}, [
              m('p', branch.description || ''),
              m('p', [
                `${branch.ahead} commits ahead, ${branch.behind} commits behind `,
                m('span', {class: "font-monospace"}, branch.compareTo)
              ])
            ]),
            m('div', {class: "card-footer"},
              m('a', {
                class: "m-1 btn btn-outline-primary shadow-none",
                href: `${data.reposPath}/${slugify(branch.repoName)}/branches/${slugify(branch.branchName)}/branches`
              }, 'Switch to branch')
            )
          ])
        : null
      })
    )
  }

  return render([
    m('h1', {class: 'fs-2'}, 'Branches with unmerged commits'),
    branchCards(branchesWithWorkInProgress),
    m('h1', {class: 'fs-2'}, 'Branches that are fully merged'),
    branchCards(branchesFullyMerged),
  ])
}
