"use client";

import { FC, useState, useEffect } from "react";
import { Box, Typography } from "@mui/material";
import { fonts } from "@link-stack/ui";
import "@chatscope/chat-ui-kit-styles/dist/default/styles.min.css";
import {
  ConversationHeader,
  ConversationHeaderProps,
} from "@chatscope/chat-ui-kit-react";
import { getTicketAction } from "@/app/_actions/tickets";

interface TicketHeaderProps {
  id?: string;
  ticket?: any;
}

export const TicketHeader: FC<ConversationHeaderProps & TicketHeaderProps> = (
  props,
) => {
  const { poppins, roboto } = fonts;

  const [ticket, setTicket] = useState<any>(props.ticket || null);

  useEffect(() => {
    if (!ticket) {
      const fetchTicket = async () => {
        const result = await getTicketAction(props.id);
        setTicket(result);
      };

      fetchTicket();

      const interval = setInterval(fetchTicket, 20000);
      return () => clearInterval(interval);
    }
  }, [props.id]);

  return (
    <>
      <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 #${ticket.number} (created ${new Date(
                ticket.createdAt,
              ).toLocaleDateString()})`
            : ""}
        </Typography>
      </Box>
    </>
  );
};
