---
import { Code } from 'astro-expressive-code/components';
import fs from 'fs';

import VerticalSideBarLayout from '@layouts/VerticalSideBarLayout.astro';
import Footer from '@layouts/Footer.astro';
import { Page } from './_[filename].data';
import { getAbsoluteFilePathForAstroFile } from '@utils/files';
import { buildUrl, buildEditUrlForResource } from '@utils/url-builder';
import Admonition from '@components/MDX/Admonition';

import { ServerIcon } from '@heroicons/react/24/outline';

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

// Get data
const { collection, data, filePath, filename, path: relativeSpecPath } = await Page.getData(Astro);

const fileName = filename || 'schema.graphql';
const pathToSpec = getAbsoluteFilePathForAstroFile(filePath, fileName);
const fileExists = fs.existsSync(pathToSpec);
const isRemote = relativeSpecPath.includes('https://');
let content = '';

if (fileExists && !isRemote) {
  content = fs.readFileSync(pathToSpec, 'utf8');
}

if (isRemote) {
  // Fetch the content from the remote path
  content = await fetch(relativeSpecPath).then((res) => res.text());
}

// Create comprehensive page title
const pageTitle = `${collection} | ${data.name} | GraphQL Schema`.replace(/^\w/, (c) => c.toUpperCase());

const getServiceBadge = () => {
  return [{ backgroundColor: 'pink', textColor: 'pink', content: 'Service', icon: ServerIcon }];
};

const getGraphQLBadge = () => {
  return [
    {
      backgroundColor: 'purple',
      textColor: 'purple',
      content: 'GraphQL Schema',
      iconURL: buildUrl('/icons/graphql.svg', true),
      id: 'graphql-schema-badge',
    },
  ];
};

const badges = [...getServiceBadge(), ...getGraphQLBadge()];

// Index only the latest version
const pagefindAttributes =
  data.version === data.latestVersion
    ? {
        'data-pagefind-body': '',
        'data-pagefind-meta': `title:${pageTitle}`,
      }
    : {};
---

<VerticalSideBarLayout title={pageTitle} description={`GraphQL schema for ${data.name}`}>
  <main class="flex sm:px-8 docs-layout h-full" {...pagefindAttributes}>
    <div class="flex docs-layout w-full">
      <div class="w-full lg:mr-2 pr-8 overflow-y-auto py-8">
        <div class="border-b border-[rgb(var(--ec-page-border))] md:pb-4">
          <div>
            <div class="flex justify-between items-start">
              <div class="flex-1">
                <h1 class="text-2xl md:text-4xl font-bold text-[rgb(var(--ec-page-text))] mb-2">
                  {data.name}
                  <span class="text-[rgb(var(--ec-page-text-muted))]">(v{data.version})</span>
                </h1>
                <h2 class="text-lg text-[rgb(var(--ec-page-text-muted))] font-medium mb-1">GraphQL Schema</h2>
              </div>
            </div>

            {
              badges && (
                <div class="flex flex-wrap gap-3 py-4">
                  {badges.map((badge: any) => (
                    <span
                      id={badge.id || ''}
                      class={`
                        inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium
                        bg-${badge.backgroundColor || 'gray'}-500/10 border border-${badge.backgroundColor || 'gray'}-500/20
                        text-${badge.textColor || 'gray'}-500
                        shadow-xs transition-all duration-200 ease-out
                      `}
                    >
                      {badge.icon && <badge.icon className={`w-4 h-4 flex-shrink-0`} />}
                      {badge.iconURL && <img src={badge.iconURL} class="w-4 h-4 flex-shrink-0 opacity-80" alt="" />}
                      <span>{badge.content}</span>
                    </span>
                  ))}
                </div>
              )
            }
          </div>
        </div>

        <div data-pagefind-ignore>
          {
            data.version !== data.latestVersion && (
              <div class="rounded-md bg-[rgb(var(--ec-accent-subtle))] p-4 not-prose my-4">
                <div class="flex">
                  <div class="flex-shrink-0">
                    <svg class="h-5 w-5 text-[rgb(var(--ec-accent))]" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                      <path
                        fill-rule="evenodd"
                        d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 5a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 5zm0 9a1 1 0 100-2 1 1 0 000 2z"
                        clip-rule="evenodd"
                      />
                    </svg>
                  </div>
                  <div class="ml-3">
                    <h3 class="text-sm font-medium text-[rgb(var(--ec-accent-text))]">New version found</h3>
                    <div class="mt-2 text-sm text-[rgb(var(--ec-accent-text))]">
                      <p>
                        You are looking at a previous version of the service <strong>{data.name}</strong>.{' '}
                        <a
                          class="underline hover:text-primary block pt-2"
                          href={buildUrl(`/docs/${collection}/${data.id}/${data.latestVersion}/graphql/${filename}`)}
                        >
                          The latest version of this GraphQL schema is
                          <span>v{data.latestVersion}</span> &rarr;
                        </a>
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            )
          }
        </div>

        {
          !fileExists && (
            <Admonition type="warning" title="Schema not found">
              <p>The GraphQL schema file could not be found at the expected location.</p>
            </Admonition>
          )
        }

        {
          fileExists && content && (
            <div class="mt-6">
              <div class="bg-[rgb(var(--ec-card-bg))] rounded-lg p-4 mb-4 border border-[rgb(var(--ec-page-border))]">
                <div class="flex items-center gap-2 mb-2">
                  <img src={buildUrl('/icons/graphql.svg', true)} class="w-5 h-5" alt="GraphQL" />
                  <h3 class="text-lg font-semibold text-[rgb(var(--ec-page-text))]">GraphQL Schema</h3>
                </div>
                <p class="text-sm text-[rgb(var(--ec-page-text-muted))]">
                  This schema defines the GraphQL API structure including types, queries, mutations, and subscriptions for{' '}
                  {data.name}.
                </p>
              </div>

              <div class="not-prose overflow-x-auto">
                <Code code={content} title={`${data.name} v${data.version} - Schema`} lang="graphql" />
              </div>
            </div>
          )
        }

        <Footer />
      </div>
    </div>
  </main>

  <style is:global>
    .docs-layout .prose {
      max-width: none;
      overflow: auto;
    }
  </style>
</VerticalSideBarLayout>
