import { GetServerSideProps } from "next";
import Head from "next/head";
import Link from "next/link";
import styles from "../styles/Home.module.css";

interface HomeProps {
  serverTime: string;
  userAgent: string;
}

export default function Home({ serverTime, userAgent }: HomeProps) {
  return (
    <div className={styles.container}>
      <Head>
        <title>Next.js SSR Demo</title>
        <meta name="description" content="Server-side rendered Next.js app" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>
          Welcome to <a href="https://nextjs.org">Next.js!</a>
        </h1>

        <p className={styles.description}>
          This page was server-side rendered at:{" "}
          <code className={styles.code}>{serverTime}</code>
        </p>

        <div className={styles.grid}>
          <Link href="/about" className={styles.card}>
            <h2>About &rarr;</h2>
            <p>Learn more about this SSR demo application.</p>
          </Link>

          <Link href="/api/hello" className={styles.card}>
            <h2>API Route &rarr;</h2>
            <p>Test the API route functionality.</p>
          </Link>

          <a
            href="https://nextjs.org/docs"
            className={styles.card}
            target="_blank"
            rel="noopener noreferrer"
          >
            <h2>Documentation &rarr;</h2>
            <p>Find in-depth information about Next.js features and API.</p>
          </a>

          <a
            href="https://nextjs.org/learn"
            className={styles.card}
            target="_blank"
            rel="noopener noreferrer"
          >
            <h2>Learn &rarr;</h2>
            <p>Learn about Next.js in an interactive course with quizzes!</p>
          </a>
        </div>

        <div className={styles.info}>
          <p>
            Your user agent: <code>{userAgent}</code>
          </p>
        </div>
      </main>

      <footer className={styles.footer}>
        <a
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by Next.js SSR
        </a>
      </footer>
    </div>
  );
}

// This function runs on the server before the page is sent to the client
export const getServerSideProps: GetServerSideProps = async ({ req }) => {
  const serverTime = new Date().toISOString();
  const userAgent = req.headers["user-agent"] || "Unknown";

  return {
    props: {
      serverTime,
      userAgent,
    },
  };
};
