---
import Footer from '@layouts/Footer.astro';
import { getChangeLogs } from '@utils/collections/changelogs';
import {
  RectangleGroupIcon,
  ServerIcon,
  BoltIcon,
  ChatBubbleLeftIcon,
  MagnifyingGlassIcon,
  QueueListIcon,
} from '@heroicons/react/24/outline';
import { DatabaseIcon } from 'lucide-react';
import { render, getEntry } from 'astro:content';
import mdxComponents from '@components/MDX/components';
import 'diff2html/bundles/css/diff2html.min.css';

import { buildUrl } from '@utils/url-builder';
import { getPreviousVersion } from '@utils/collections/util';
import { getDiffsForCurrentAndPreviousVersion } from '@utils/file-diffs';
import VerticalSideBarLayout from '@layouts/VerticalSideBarLayout.astro';
import { ClientRouter } from 'astro:transitions';
import { isChangelogEnabled } from '@utils/feature';

import { Page } from './_index.data';

export const prerender = Page.prerender;
export const getStaticPaths = Page.getStaticPaths;

// Get data
const props = await Page.getData(Astro);

let collectionItem = props;
const logs = await getChangeLogs(props);

const { data } = props;
const latestVersion = data.latestVersion;

const renderedLogs = logs.map(async (log) => {
  const logEntry = await getEntry('changelogs', log.id);
  const { Content } = await render(logEntry as any);
  return {
    Content,
    ...log,
  };
});

const logsToRender = await Promise.all(renderedLogs);

const logListPromise = logsToRender.map(async (log, index) => {
  const currentLogVersion = log.data.version;
  const previousLogVersion = log.data.version ? getPreviousVersion(log.data.version, data.versions || []) : '';
  return {
    id: log.id,
    url: buildUrl(`/docs/${props.collection}/${props.data.id}`),
    isLatest: log.data.version === latestVersion,
    version: log.data.version,
    createdAt: log.data.createdAt,
    badges: log.data.badges || [],
    Content: log.Content,
    diffs:
      currentLogVersion && previousLogVersion
        ? await getDiffsForCurrentAndPreviousVersion(
            currentLogVersion,
            previousLogVersion,
            collectionItem.data.id,
            props.allCollectionItems
          )
        : [],
  };
});

const logList = await Promise.all(logListPromise);

const getBadge = () => {
  if (props.collection === 'services') {
    return { badgeType: 'service', content: 'Service', icon: ServerIcon };
  }
  if (props.collection === 'events') {
    return { badgeType: 'event', content: 'Event', icon: BoltIcon };
  }
  if (props.collection === 'commands') {
    return { badgeType: 'command', content: 'Command', icon: ChatBubbleLeftIcon };
  }
  if (props.collection === 'queries') {
    return { badgeType: 'query', content: 'Query', icon: MagnifyingGlassIcon };
  }
  if (props.collection === 'domains') {
    return { badgeType: 'domain', content: 'Domain', icon: RectangleGroupIcon };
  }
  if (props.collection === 'containers') {
    return { badgeType: 'default', content: 'Container', icon: DatabaseIcon };
  }
  if (props.collection === 'flows') {
    return { badgeType: 'design', content: 'Flow', icon: QueueListIcon };
  }
};

const badges = [getBadge()];
---

<VerticalSideBarLayout title="ChangeLog">
  <main class="w-full md:pt-4 px-8 overflow-y-auto h-full max-w-[95%]">
    <nav aria-label="Breadcrumb" class="flex">
      <ol role="list" class="flex items-center space-x-2">
        <li>
          <div>
            <a
              href={buildUrl(`/docs/${props.collection}/${props.data.id}/${props.data.version}`)}
              class="text-sm font-medium text-[rgb(var(--ec-page-text-muted))] hover:text-[rgb(var(--ec-page-text))]"
            >
              {props.data.name}
            </a>
          </div>
        </li>
        <li>
          <div class="flex items-center">
            <svg
              fill="currentColor"
              viewBox="0 0 20 20"
              aria-hidden="true"
              class="h-5 w-5 flex-shrink-0 text-[rgb(var(--ec-page-border))]"
            >
              <path d="M5.555 17.776l8-16 .894.448-8 16-.894-.448z"></path>
            </svg>
            <a
              href={buildUrl(`/docs/${props.collection}/${props.data.id}/${props.data.version}`)}
              class="text-sm font-medium text-[rgb(var(--ec-page-text-muted))] hover:text-[rgb(var(--ec-page-text))]"
            >
              Changelog
            </a>
          </div>
        </li>
      </ol>
    </nav>
    <div class="border-b border-[rgb(var(--ec-page-border))] flex justify-between items-start py-4 w-full">
      <div>
        <h2 class="text-2xl md:text-4xl font-bold text-[rgb(var(--ec-page-text))]">{props.data.name} (Changelog)</h2>
        <h2 class="text-lg pt-2 text-[rgb(var(--ec-page-text-muted))] font-light">{props.data.summary}</h2>
        {
          badges && (
            <div class="flex flex-wrap py-2 pt-4">
              {badges.map((badge: any) => (
                <span
                  class="text-sm font-medium px-2 py-1 rounded-md mr-2 space-x-1 flex items-center"
                  style={`background-color: rgb(var(--ec-badge-${badge.badgeType}-bg)); color: rgb(var(--ec-badge-${badge.badgeType}-text));`}
                >
                  {badge.icon && <badge.icon className="w-4 h-4 inline-block mr-1" />}
                  <span>{badge.content}</span>
                </span>
              ))}
            </div>
          )
        }
      </div>
    </div>
    {
      logList.length === 0 && (
        <div class="py-4 text-[rgb(var(--ec-page-text-muted))] prose prose-md">
          <p>No changelogs found.</p>
        </div>
      )
    }
    <div class="flow-root py-8 w-full">
      <ul role="list" class="-mb-8">
        {
          logList.map((log, index) => (
            <li>
              <div class="relative pb-8">
                {index !== logList.length - 1 ? (
                  <span aria-hidden="true" class="absolute left-6 top-4 -ml-px h-full w-0.5 bg-[rgb(var(--ec-page-border))]" />
                ) : null}
                <div class="relative flex space-x-3">
                  <div>
                    <a
                      href={buildUrl(`${log.url}/${log.version}`)}
                      class="bg-primary hover:bg-primary/80 text-white flex h-8 w-14 items-center justify-center rounded-full ring-8 ring-[rgb(var(--ec-page-bg))]"
                    >
                      {log.version}
                    </a>
                  </div>
                </div>
                <div class="pl-[70px] py-2 -mt-10">
                  {log.createdAt && (
                    <div class="pb-2">
                      <h3 class="text-2xl text-[rgb(var(--ec-page-text))] font-bold">
                        <span>
                          {log.createdAt.toISOString().split('T')[0]} {`${log.isLatest ? '(latest)' : ''}`}
                        </span>
                      </h3>
                    </div>
                  )}
                  {log.badges && (
                    <div class="flex flex-wrap">
                      {log.badges.map((badge: any) => (
                        <span class="text-sm font-medium px-2 py-1 rounded-md mr-2 space-x-1 flex items-center bg-[rgb(var(--ec-badge-default-bg))] text-[rgb(var(--ec-badge-default-text))]">
                          {badge.icon && <badge.icon className="w-4 h-4 inline-block mr-1" />}
                          <span>{badge.content}</span>
                        </span>
                      ))}
                    </div>
                  )}
                  <div class="prose prose-md max-w-none! py-2">
                    <log.Content components={mdxComponents(props)} />
                  </div>
                  {log.diffs && log.diffs.map((diff) => <div class="bg-white rounded-lg p-2 my-2" set:html={diff} />)}
                </div>
              </div>
            </li>
          ))
        }
      </ul>
    </div>
    <Footer />
  </main>
  <ClientRouter />
</VerticalSideBarLayout>
