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";
import { getTicketQuery } from "graphql/getTicketQuery";

type TicketProps = {
  id: string;
};

const Ticket: NextPage<TicketProps> = ({ id }) => {
  const { data: ticketData, error: ticketError }: any = useSWR(
    {
      document: getTicketQuery,
      variables: { ticketId: `gid://zammad/Ticket/${id}` },
    },
    { refreshInterval: 100000 }
  );

  const shouldRender = !ticketError && ticketData;

  return (
    <Layout>
      <Head>
        <title>Link Shell</title>
      </Head>
      {shouldRender && (
        <Grid container spacing={0} sx={{ height: "100vh" }} direction="row">
          <Grid item sx={{ height: "100vh" }} xs={9}>
            <TicketDetail ticket={ticketData.ticket} />
          </Grid>
          <Grid item xs={3} sx={{ height: "100vh" }}>
            <TicketEdit ticket={ticketData.ticket} />
          </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;
