"use client";

import { FC, useState, useEffect } from "react";
import { getTicketAction, getTicketArticlesAction } from "app/_actions/tickets";
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 [ticket, setTicket] = useState<any>(null);
  const [ticketArticles, setTicketArticles] = useState<any>(null);
  const { poppins, roboto } = fonts;
  const { veryLightGray, lightGray } = colors;
  const [dialogOpen, setDialogOpen] = useState(false);
  const [articleKind, setArticleKind] = useState("note");

  useEffect(() => {
    const fetchTicket = async () => {
      const result = await getTicketAction(id);
      setTicket(result);
    };

    fetchTicket();

    const interval = setInterval(fetchTicket, 20000);

    return () => clearInterval(interval);
  }, [id]);

  useEffect(() => {
    const fetchTicketArticles = async () => {
      const result = await getTicketArticlesAction(id);
      setTicketArticles(result);
    };

    fetchTicketArticles();

    const interval = setInterval(fetchTicketArticles, 5000);

    return () => clearInterval(interval);
  }, [id]);

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

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

  return (
    <Box sx={{ height: "100%", width: "100%", background: veryLightGray }}>
      {shouldRender && (
        <>
          <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>
  );
};
