import React, { useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { BackButton } from "../../../../components/back-button/BackButton";
import { useParams } from "react-router-dom";
import { CreateTicket } from "../create-ticket/CreateTicket";
import { ShowMissages } from "../show-messages/ShowMissages";
import { useDispatch } from "react-redux";
import { getMessagesService } from "../../services/get-messages";
import { Button, Typography } from "@mui/material";
import { formatJustDate } from "../../../../utils/formatTime";
import ForwardToInboxIcon from "@mui/icons-material/ForwardToInbox";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { SubmitRefferTicket } from "../submit-reffer-ticket/SubmitRefferTicket";

export const TicketView = () => {
  const { create, id } = useParams();
  const dispatch = useDispatch();
  const [data, setData] = useState();
  const [canSeeMessages, setCanSeeMessages] = useState();
  const fetchMessages = () => {
    dispatch(getMessagesService({ ticket: id })).then((r) => {
      setData(r.payload.data);
    });
  };

  useEffect(() => {
    let intervalId;

    if (create === "false") {
      fetchMessages();
      intervalId = setInterval(fetchMessages, 3000);
    }

    return () => {
      if (intervalId) {
        clearInterval(intervalId);
      }
    };
  }, [dispatch, id, create]);

  useEffect(() => {
    if (data?.length) {
      if (
        data[0]?.ticket?.readOnly === true ||
        data[0]?.ticket?.status === "closed"
      ) {
        setCanSeeMessages(false);
      }
    } else {
      setCanSeeMessages(true);
    }
  }, [data]);

  const isReffered = (data) => {
    if (data) {
      if (
        data.some(
          (item) =>
            item.message?.includes("ارجاع داده شد.") &&
            item?.message?.includes("تیکت شماره")
        )
      ) {
        return true;
      } else {
        return false;
      }
    }
  };

  return (
    <Grid container xs={12} justifyContent="center">
      <Grid container xs={12}>
        <BackButton />
      </Grid>

      {data && (
        <Grid
          container
          xs={12}
          justifyContent="space-between"
          alignItems="center"
          p={2}
          mb={2}
          gap={2}
          direction={{ xs: "column", sm: "row" }}
          sx={{
            borderStyle: "solid",
            borderWidth: "1px",
            borderRadius: "30px",
            backgroundColor: "#e5e5e5",
          }}
        >
          <Grid container alignItems="center">
            <Typography>عنوان: {"‌‌"}</Typography>
            <Typography>{data[0]?.ticket?.title}</Typography>
          </Grid>
          <Grid container alignItems="center">
            <Typography>تاریخ ایجاد: {"‌‌"}</Typography>
            <Typography>
              {formatJustDate(data[0]?.ticket?.createDate)}
            </Typography>
          </Grid>
          <Grid container alignItems="center">
            <Typography>وضعیت تیکت: {"‌‌"}</Typography>
            <Typography>
              {data[0]?.ticket?.status === "open"
                ? "باز"
                : data[0]?.ticket?.status === "answered"
                ? "باز"
                : "بسته"}
              {isReffered(data) && " (ارجاع داده شده) "}
              {data[0]?.ticket?.readOnly && "(فقط خواندنی)"}
            </Typography>
          </Grid>
          {Object.prototype.hasOwnProperty.call(data[0], "readBy") && (
            <Grid container alignItems="center">
              <Button
                variant="outlined"
                endIcon={<ForwardToInboxIcon />}
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      title: "ارجاع تیکت",
                      content: (
                        <SubmitRefferTicket
                          fetchMessages={fetchMessages}
                          ticket={id}
                        />
                      ),
                    })
                  );
                }}
              >
                ارجاع
              </Button>
            </Grid>
          )}
          {/* <Grid container alignItems="center">
            <Typography>دریافت کنندگان: {"‌‌"}</Typography>
            <Typography>
              {data[0]?.ticket?.toUser.length
                ? data[0]?.ticket?.toUser?.map(
                    (option, index) =>
                      `${option?.fullname} ${
                        index + 1 !== data[0]?.ticket?.toUser?.length
                          ? " - "
                          : ""
                      }`
                  )
                : data[0]?.ticket?.toRole?.map(
                    (option, index) =>
                      `${getFaUserRole(option.name)} ${
                        index + 1 !== data[0]?.ticket?.toRole?.length
                          ? " - "
                          : ""
                      }`
                  )}
            </Typography>
          </Grid> */}
        </Grid>
      )}

      {canSeeMessages && (
        <Grid
          xs={12}
          md={4}
          justifyContent="center"
          alignItems="center"
          sx={{ paddingRight: "17px" }}
        >
          <CreateTicket id={id} fetchMessages={fetchMessages} />
        </Grid>
      )}
      {create === "false" && (
        <Grid
          xs={12}
          md={8}
          sx={{ marginTop: { xs: 2, md: 0 } }}
          justifyContent="center"
          alignItems="center"
        >
          <ShowMissages id={id} data={data} />
        </Grid>
      )}
    </Grid>
  );
};
