import { GetServerSideProps, GetServerSidePropsContext } from "next";
import Head from "next/head";
import useSWR from "swr";
import { NextPage } from "next";
import { Grid, } from "@mui/material";
import { Layout } from "components/Layout";
import { TicketDetail } from "components/TicketDetail";
import { TicketEdit } from "components/TicketEdit";

type TicketProps = {
  id: string;
};

const Ticket: NextPage<TicketProps> = ({ id }) => {
  const fetcher = async (url: string) => {
    const res = await fetch(url);
    return res.json();
  }

  const { data: ticketData, error: ticketError } = useSWR(
    `https://redaranj-bookish-tribble-56jwjx5wh4j4w-8003.preview.app.github.dev/api/v1/tickets/${id}`,
    fetcher
  );

  const { data: articlesData, error: articlesError } = useSWR(
    `https://redaranj-bookish-tribble-56jwjx5wh4j4w-8003.preview.app.github.dev/api/v1/ticket_articles/by_ticket/${id}`,
    fetcher
  );

  const shouldRender = !ticketError && !articlesError && ticketData && articlesData && !ticketData.error && !articlesData.error;

  return (
    <Layout>
      <Head>
        <title>Link Shell</title>
      </Head>
      {shouldRender && (
        <Grid container spacing={0} sx={{ height: "100vh" }} direction="row">
          <Grid item sx={{ height: "100vh" }} xs={10}>

            <TicketDetail ticket={ticketData} articles={articlesData} />
          </Grid>
          <Grid item xs={2} sx={{ height: "100vh" }}>
            <TicketEdit ticket={ticketData} />
          </Grid>
        </Grid>)}
      {ticketError && <div>{ticketError.toString()}</div>}
    </Layout>
  );
}

export const getServerSideProps: GetServerSideProps = async (
  context: GetServerSidePropsContext) => {
  const { id } = context.query;
  return { props: { id } };
}

export default Ticket;
