"use client";

import { FC, useState } from "react";
import useSWR from "swr";
import { getTicketQuery } from "app/_graphql/getTicketQuery";
import { getTicketArticlesQuery } from "app/_graphql/getTicketArticlesQuery";
import { Grid, Box, Typography } from "@mui/material";
import { Button, fonts, colors } from "@link-stack/ui";

import "@chatscope/chat-ui-kit-styles/dist/default/styles.min.css";
import {
  MainContainer,
  ChatContainer,
  MessageList,
  Message,
  ConversationHeader,
} from "@chatscope/chat-ui-kit-react";
import { ArticleCreateDialog } from "./ArticleCreateDialog";

interface TicketDetailProps {
  id: string;
}

export const TicketDetail: FC<TicketDetailProps> = ({ id }) => {
  const { poppins, roboto } = fonts;
  const { veryLightGray, lightGray } = colors;
  const [dialogOpen, setDialogOpen] = useState(false);
  const [articleKind, setArticleKind] = useState("note");
  const { data: ticketData, error: ticketError }: any = useSWR(
    {
      document: getTicketQuery,
      variables: { ticketId: `gid://zammad/Ticket/${id}` },
    },
    { refreshInterval: 10000 },
  );
  const { data: ticketArticlesData, error: ticketArticlesError }: any = useSWR(
    {
      document: getTicketArticlesQuery,
      variables: { ticketId: `gid://zammad/Ticket/${id}` },
    },
    { refreshInterval: 2000 },
  );

  const { data: recentViewData, error: recentViewError }: any = useSWR({
    url: "/api/v1/recent_view",
    method: "POST",
    body: JSON.stringify({ object: "Ticket", o_id: id }),
  });

  const closeDialog = () => setDialogOpen(false);

  const ticket = ticketData?.ticket;
  const ticketArticles = ticketArticlesData?.ticketArticles;
  const firstArticle = ticketArticles?.edges[0]?.node;
  const firstArticleKind = firstArticle?.type?.name ?? "phone";
  const firstEmailSender = firstArticle?.from?.parsed?.[0]?.emailAddress ?? "";
  const recipient = firstEmailSender;
  const shouldRender =
    ticketData && !ticketError && ticketArticlesData && !ticketArticlesError;

  return (
    shouldRender && (
      <Box sx={{ height: "100%", width: "100%" }}>
        <MainContainer>
          <ChatContainer>
            <ConversationHeader>
              <ConversationHeader.Content>
                <Box
                  sx={{
                    width: "100%",
                    textAlign: "center",
                    fontWeight: "bold",
                  }}
                >
                  <Typography
                    variant="h5"
                    sx={{
                      fontFamily: poppins.style.fontFamily,
                      fontWeight: 700,
                    }}
                  >
                    {ticket.title}
                  </Typography>
                  <Typography
                    variant="h6"
                    sx={{
                      fontFamily: roboto.style.fontFamily,
                      fontWeight: 400,
                    }}
                  >{`Ticket #${ticket.number} (created ${new Date(
                    ticket.createdAt,
                  ).toLocaleDateString()})`}</Typography>
                </Box>
              </ConversationHeader.Content>
            </ConversationHeader>
            <MessageList style={{ marginBottom: 80 }}>
              {ticketArticles.edges.map(({ node: article }: any) => (
                <Message
                  key={article.id}
                  className={
                    article.internal
                      ? "internal-note"
                      : article?.sender?.name === "Agent"
                        ? "outgoing-message"
                        : "incoming-message"
                  }
                  model={{
                    message: article.bodyWithUrls,
                    sentTime: article.updated_at,
                    sender: article.from,
                    direction:
                      article.sender === "Agent" ? "outgoing" : "incoming",
                    position: "single",
                  }}
                />
              ))}
            </MessageList>
          </ChatContainer>
          <Box
            sx={{
              height: 80,
              background: veryLightGray,
              borderTop: `1px solid ${lightGray}`,
              position: "absolute",
              bottom: 0,
              width: "100%",
              zIndex: 1000,
            }}
          >
            <Grid
              container
              spacing={6}
              justifyContent="center"
              alignItems="center"
              alignContent="center"
              sx={{ height: "100%", pt: 6 }}
            >
              <Grid item>
                <Button
                  text="Write note to agent"
                  color="#FFB620"
                  onClick={() => {
                    setArticleKind("note");
                    setDialogOpen(true);
                  }}
                />
              </Grid>
              <Grid item>
                <Button
                  text="Reply to ticket"
                  kind="primary"
                  onClick={() => {
                    setArticleKind(firstArticleKind);
                    setDialogOpen(true);
                  }}
                />
              </Grid>
            </Grid>
          </Box>
        </MainContainer>
        <ArticleCreateDialog
          ticketID={ticket.internalId}
          open={dialogOpen}
          closeDialog={closeDialog}
          kind={articleKind}
          recipient={recipient}
        />
      </Box>
    )
  );
};
