import React from "react";
import { Button, Divider, Typography } from "@mui/material";
import Tooltip, { tooltipClasses } from "@mui/material/Tooltip";

import { motion } from "framer-motion";
import DoneAllIcon from "@mui/icons-material/DoneAll";
import CheckIcon from "@mui/icons-material/Check";
import ShowImage from "../../../../components/show-image/ShowImage";
import persianDate from "persian-date";
import { Grid } from "../../../../components/grid/Grid";
import DownloadIcon from "@mui/icons-material/Download";
import { styled } from "@mui/material/styles";

const containerVariants = {
  hidden: { opacity: 0, y: 10 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.3 } },
};

const HtmlTooltip = styled(({ className, ...props }) => (
  <Tooltip {...props} classes={{ popper: className }} />
))(({ theme }) => ({
  [`& .${tooltipClasses.tooltip}`]: {
    backgroundColor: "#f5f5f9",
    color: "rgba(0, 0, 0, 0.87)",
    maxWidth: 220,
    fontSize: theme.typography.pxToRem(12),
    border: "1px solid #dadde9",
  },
}));

const formatMessage = (message) => {
  if (!message) return "";

  const formattedText = message.replace(/\*\*\*/g, "\n").trim();

  const lines = formattedText.split("\n");

  return lines.map((line, index) => (
    <React.Fragment key={index}>
      {line}
      <br />
    </React.Fragment>
  ));
};

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

  return (
    <Grid container gap={2}>
      {data?.map((item, i) => (
        <Grid
          item
          xs={12}
          key={i}
          component={motion.div}
          variants={containerVariants}
          initial="hidden"
          animate="visible"
          sx={{
            border: "1px ridge gray",
            borderRadius: "10px",
            p: 2,
            backgroundColor: isReffered(item) ? "#e7b2b2" : "background.paper",
            boxShadow: 4,
          }}
        >
          <Grid container justifyContent="space-between" alignItems="center">
            <Typography color="text.secondary">
              {item?.createdBy?.fullname}
            </Typography>
            <Grid
              container
              alignItems="center"
              spacing={1}
              justifyContent="flex-start"
            >
              <Typography color="text.secondary">
                {`${new persianDate(new Date(item?.createdAt)).format(
                  "dddd DD MMMM"
                )} (${new Date(item?.createdAt).toLocaleTimeString([], {
                  hour: "2-digit",
                  minute: "2-digit",
                  hour12: false,
                })})`}
              </Typography>
              {item?.lastSeen ? (
                <HtmlTooltip
                  disableHoverListener={!item?.readBy}
                  title={
                    <Grid container xs={12} direction="column">
                      <Typography variant="body1" color="primary">
                        بازدید شده توسط
                      </Typography>
                      {item?.readBy?.map((item, i) => (
                        <Typography variant="body2" key={i}>
                          {item?.fullname} ({item?.mobile})
                        </Typography>
                      ))}
                    </Grid>
                  }
                >
                  <DoneAllIcon sx={{ marginLeft: "10px" }} color="primary" />
                </HtmlTooltip>
              ) : (
                <CheckIcon sx={{ marginLeft: "10px" }} color="error" />
              )}
            </Grid>
          </Grid>

          <Divider sx={{ my: 1 }} />

          <Typography
            color={isReffered(item) ? "#202077" : "black"}
            mt={1}
            sx={{
              textAlign: "left",
              width: "100%",
            }}
          >
            {formatMessage(item?.message)}
          </Typography>

          {(item?.picture || item?.file) && (
            <>
              <Divider sx={{ width: "100%", my: 2 }} />

              <Grid
                container
                spacing={2}
                mt={2}
                justifyContent="space-between"
                alignItems="center"
                gap={2}
              >
                {item?.picture && (
                  <ShowImage src={item?.picture} size="100px" />
                )}

                {item?.file && (
                  <Button
                    color="success"
                    onClick={() => {
                      const link = item?.file;
                      window.location.href = link;
                    }}
                    endIcon={<DownloadIcon />}
                  >
                    دانلود فایل پیوست
                  </Button>
                )}
              </Grid>
            </>
          )}
        </Grid>
      ))}
    </Grid>
  );
};
