import React from 'react';
import { GetServerSideProps } from 'next';
import Head from 'next/head';
import LayoutGuest from '../layouts/Guest';
import WebSiteHeader from '../components/WebPageComponents/Header';
import WebSiteFooter from '../components/WebPageComponents/Footer';
import { baseURLApi, appTitle } from '../config';

interface PageProps {
  pageData: { title: string; content: string } | null;
  siteConfig?: { contactemail: string; contactphone: string };
}

export default function Page({ pageData, siteConfig }: PageProps) {
  if (!pageData) {
    return <p className="p-8">Page not found</p>;
  }
  return (
    <div className="flex flex-col min-h-screen">
      <Head>
        <title>{`${pageData.title} — ${appTitle}`}</title>
        <meta name="description" content={pageData.content.substring(0, 160)} />
      </Head>
      <WebSiteHeader projectName={appTitle} />
      <main className="flex-grow container mx-auto py-8">
        <h1 className="text-4xl font-bold mb-4">{pageData.title}</h1>
        <div
          className="prose mx-auto"
          dangerouslySetInnerHTML={{ __html: pageData.content }}
        />
        {siteConfig && (
          <div className="mt-8">
            <h2 className="text-2xl font-semibold mb-2">Contact Information</h2>
            <p>Email: {siteConfig.contactemail}</p>
            <p>Phone: {siteConfig.contactphone}</p>
          </div>
        )}
      </main>
      <WebSiteFooter projectName={appTitle} />
    </div>
  );
}

export const getServerSideProps: GetServerSideProps = async ({ params }) => {
  const slug = params?.slug as string;
  const res = await fetch(`${baseURLApi}/pages?slug=${slug}`);
  const data = await res.json();
  const pageData = Array.isArray(data) && data.length > 0 ? data[0] : null;
  let siteConfig = null;
  if (slug === 'contact') {
    const resSC = await fetch(`${baseURLApi}/siteconfigs`);
    const sc = await resSC.json();
    siteConfig = Array.isArray(sc) && sc.length > 0 ? sc[0] : null;
  }
  return { props: { pageData, siteConfig } };
};
