import React, { useContext, useEffect, useRef, useState } from "react";
import {
  Fab,
  Box,
  Paper,
  Typography,
  IconButton,
  TextField,
  Button,
  Avatar,
  Tooltip,
} from "@mui/material";
import ChatIcon from "@mui/icons-material/Chat";
import CloseIcon from "@mui/icons-material/Close";
// import SendIcon from "@mui/icons-material/Send";
import { motion, AnimatePresence } from "framer-motion";
import { Formik, Form, Field } from "formik";
import * as Yup from "yup";
import { useDispatch, useSelector } from "react-redux";
import { getTickets } from "./services/getTickets";
import ArrowBackIosIcon from "@mui/icons-material/ArrowBackIos";
import ContactSupportIcon from "@mui/icons-material/ContactSupport";
import { getMessages } from "./services/getMessages";
import { submitTicket } from "./services/submitTicket";
import { AppContext } from "../../contexts/AppContext";
import DoDisturbOffIcon from "@mui/icons-material/DoDisturbOff";
import { closeTicket } from "./services/closeTicket";
import messageSound from "../../assets/message.mp3";
import { submitMessage } from "./services/submitMessage";

const ChatButton = () => {
  const dispatch = useDispatch();
  const [showChat, setShowChat] = useState(false);
  const [tickets, setTickets] = useState([]);
  const [single, setSingle] = useState(false);
  const [singleId, setSingleId] = useState();
  const [openNotif] = useContext(AppContext);
  const { role } = useSelector((item) => item.userSlice);

  const [messages, setMessages] = useState([]);

  const toggleChat = () => {
    setShowChat(!showChat);
  };

  const getTicketsFunction = () => {
    if (showChat === true) {
      dispatch(getTickets()).then((r) => {
        setTickets(r.payload.data);
      });
    }
  };
  const prevLengthRef = useRef(messages.length);

  const getMessagesFunction = (id) => {
    const mlength = prevLengthRef.current;
    const audio = new Audio(messageSound);

    dispatch(getMessages({ ticketId: id })).then((r) => {
      const d = r.payload.data.map((item) => {
        return {
          text: item?.message,
          sender: item?.sender,
        };
      });
      setMessages(d);
      if (prevLengthRef === 0) {
        prevLengthRef.current = d.length;
      } else if (
        d.length > mlength &&
        !role.includes("SuperAdmin") &&
        d[d.length - 1].sender === "admin"
      ) {
        prevLengthRef.current = d.length;

        audio.play();
      }
    });
  };
  useEffect(() => {
    if (singleId) {
      getMessagesFunction(singleId, true);
      const intervalId = setInterval(() => {
        getMessagesFunction(singleId, true);
      }, 5000);

      return () => clearInterval(intervalId);
    }
  }, [singleId]);

  useEffect(() => {
    getTicketsFunction();
  }, [showChat]);

  const handleSendMessage = (values, { resetForm }) => {
    if (!single) {
      dispatch(
        submitTicket({
          title: values.ticket,
          userlocation: window.location.pathname,
          picture: null,
          text: null,
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
        getTicketsFunction();
      });
      resetForm();
    } else {
      setMessages([
        ...messages,
        {
          text: values.message,
          sender: role.includes("SuperAdmin") ? "admin" : "user",
        },
      ]);
      resetForm();
      dispatch(
        submitMessage({
          message: values.message,
          sender: role.includes("SuperAdmin") ? "admin" : "user",
          user_location: window.location.pathname,
          ticket: singleId,
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
        getMessagesFunction(singleId);
      });
    }
  };

  return (
    <div>
      <AnimatePresence>
        {!showChat && (
          <motion.div
            initial={{ opacity: 0, x: -100 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -100 }}
            transition={{ duration: 0.3 }}
            style={{ position: "fixed", bottom: 16, left: 16, zIndex: 1000 }}
          >
            <Fab color="primary" aria-label="chat" onClick={toggleChat}>
              <ChatIcon />
            </Fab>
          </motion.div>
        )}
      </AnimatePresence>

      <AnimatePresence>
        {showChat && (
          <>
            {!single ? (
              <motion.div
                initial={{ opacity: 0, y: 0 }}
                animate={{ opacity: 1, y: -16 }}
                exit={{ opacity: 0, y: 0 }}
                transition={{ duration: 0.2 }}
                style={{
                  position: "fixed",
                  bottom: 16,
                  left: 16,
                  width: 350,
                  height: "80%",
                  background: "white",
                  boxShadow: "0 -2px 10px rgba(0,0,0,0.3)",
                  padding: 14,
                  zIndex: 1000,
                  borderRadius: "8px",
                }}
              >
                <Paper
                  elevation={3}
                  style={{
                    height: "100%",
                    overflow: "hidden",
                    display: "flex",
                    flexDirection: "column",
                  }}
                >
                  <Box
                    sx={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      padding: "16px",
                      borderBottom: "1px solid #ddd",
                    }}
                  >
                    <Typography variant="h6">گفتگو با پشتیبان</Typography>
                    <IconButton
                      size="small"
                      color="secondary"
                      onClick={toggleChat}
                    >
                      <CloseIcon />
                    </IconButton>
                  </Box>
                  <Box
                    sx={{
                      flex: 1,
                      overflowY: "auto",
                      display: "flex",
                      flexDirection: "column",
                    }}
                  >
                    {tickets?.map((item) => {
                      return (
                        <Box
                          key={item?.id}
                          sx={{
                            display: "flex",
                            justifyContent: "space-between",
                            alignItems: "center",
                            padding: "8px",
                            borderBottom: "1px solid #ddd",
                          }}
                        >
                          <Typography
                            onClick={() => {
                              setSingle(true);
                              setSingleId(item?.id);
                            }}
                            style={{ color: "gray", cursor: "pointer" }}
                          >
                            {item?.title}
                          </Typography>

                          {item?.status === "open" ? (
                            <Tooltip title="جهت بستن تیکت کلیک کنید">
                              <Avatar
                                onClick={() => {
                                  dispatch(
                                    closeTicket({ ticket: item.id })
                                  ).then(() => {
                                    getTicketsFunction();
                                  });
                                }}
                                className="bluehover"
                                style={{ cursor: "pointer" }}
                              >
                                <ContactSupportIcon />
                              </Avatar>
                            </Tooltip>
                          ) : (
                            <Tooltip title="این تیکت بسته شده است!">
                              <Avatar className="bluehover">
                                <DoDisturbOffIcon />
                              </Avatar>
                            </Tooltip>
                          )}
                        </Box>
                      );
                    })}
                  </Box>
                  {!role?.includes("SuperAdmin") && (
                    <Box sx={{ padding: "16px", borderTop: "1px solid #ddd" }}>
                      <Formik
                        initialValues={{ ticket: "" }}
                        validationSchema={Yup.object({
                          ticket: Yup.string()
                            .required("لطفا موضوع تیکت را وارد کنید")
                            .max(60, "عنوان تیکت باید نهایتا 25 کاراکتر باشد!"),
                        })}
                        onSubmit={handleSendMessage}
                      >
                        {({ errors, touched }) => (
                          <Form
                            style={{ display: "flex", alignItems: "center" }}
                          >
                            <Field
                              as={TextField}
                              name="ticket"
                              variant="outlined"
                              multiline
                              rows={2}
                              size="small"
                              placeholder="یک تیکت جدید ایجاد کنید..."
                              error={touched.ticket && Boolean(errors.ticket)}
                              helperText={touched.ticket && errors.ticket}
                              // InputProps={{
                              //   endAdornment: (
                              //     <InputAdornment position="end">
                              //       <IconButton edge="end">
                              //         <SendIcon />
                              //       </IconButton>
                              //     </InputAdornment>
                              //   ),
                              // }}
                              sx={{
                                flex: 1,
                                marginRight: "8px",
                              }}
                            />
                            <Button
                              type="submit"
                              variant="contained"
                              color="primary"
                              sx={{ borderRadius: "24px" }}
                            >
                              ارسال
                            </Button>
                          </Form>
                        )}
                      </Formik>
                    </Box>
                  )}
                </Paper>
              </motion.div>
            ) : (
              <motion.div
                initial={{ opacity: 0, y: 0 }}
                animate={{ opacity: 1, y: -16 }}
                exit={{ opacity: 0, y: 0 }}
                transition={{ duration: 0.2 }}
                style={{
                  position: "fixed",
                  bottom: 16,
                  left: 16,
                  width: 350,
                  height: "80%",
                  background: "white",
                  boxShadow: "0 -2px 10px rgba(0,0,0,0.3)",
                  padding: 14,
                  zIndex: 1000,
                  borderRadius: "8px",
                }}
              >
                <Paper
                  elevation={3}
                  style={{
                    height: "100%",
                    overflow: "hidden",
                    display: "flex",
                    flexDirection: "column",
                  }}
                >
                  <Box
                    sx={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      padding: "16px",
                      borderBottom: "1px solid #ddd",
                    }}
                  >
                    <Typography variant="h6">
                      گفتگو با{" "}
                      {role.includes("SuperAdmin") ? "کاربر" : "پشتیبان"}
                    </Typography>
                    <IconButton
                      size="small"
                      color="secondary"
                      onClick={() => {
                        setSingle(false);
                        setSingleId("");
                        getTicketsFunction();
                      }}
                    >
                      <ArrowBackIosIcon />
                    </IconButton>
                  </Box>

                  {messages.length ? (
                    <Box
                      sx={{
                        flex: 1,
                        padding: "16px",
                        overflowY: "auto",
                        display: "flex",
                        flexDirection: "column",
                        gap: "16px",
                      }}
                    >
                      {messages.map((message, index) => (
                        <Message
                          key={index}
                          message={message}
                          sender={message.sender}
                        />
                      ))}
                    </Box>
                  ) : (
                    <Box
                      sx={{
                        flex: 1,
                        padding: "16px",
                        overflowY: "auto",
                        display: "flex",
                        flexDirection: "column",
                        gap: "16px",
                        marginTop: "60%",
                      }}
                    >
                      <Typography variant="body2">پیامی موجود نیست!</Typography>
                    </Box>
                  )}

                  <Box sx={{ padding: "16px", borderTop: "1px solid #ddd" }}>
                    <Formik
                      initialValues={{ message: "" }}
                      validationSchema={Yup.object({
                        message: Yup.string()
                          .required("لطفا پیامی تایپ کنید")
                          .max(300, "متن شما باید نهایتا 300 کاراکتر باشد!"),
                      })}
                      onSubmit={handleSendMessage}
                    >
                      {({ errors, touched }) => (
                        <Form style={{ display: "flex", alignItems: "center" }}>
                          <Field
                            as={TextField}
                            name="message"
                            variant="outlined"
                            multiline
                            rows={3}
                            size="small"
                            placeholder="سوال خود را مطرح کنید..."
                            error={touched.message && Boolean(errors.message)}
                            helperText={touched.message && errors.message}
                            // InputProps={{
                            //   endAdornment: (
                            //     <InputAdornment position="end">
                            //       <IconButton edge="end">
                            //         <SendIcon />
                            //       </IconButton>
                            //     </InputAdornment>
                            //   ),
                            // }}
                            sx={{
                              flex: 1,
                              marginRight: "8px",
                            }}
                          />
                          <Button
                            type="submit"
                            variant="contained"
                            color="primary"
                            sx={{ borderRadius: "24px" }}
                          >
                            ارسال
                          </Button>
                        </Form>
                      )}
                    </Formik>
                  </Box>
                </Paper>
              </motion.div>
            )}
          </>
        )}
      </AnimatePresence>
    </div>
  );
};

const Message = ({ message, sender }) => {
  const isUser = sender === "user";
  const [tooltipTitle, setTooltipTitle] = useState("جهت کپی محل کلیک کنید");

  const handleClickMessage = () => {
    navigator.clipboard
      .writeText(message?.userLocation)
      .then(() => {
        setTooltipTitle("کپی شد");
        setTimeout(() => {
          setTooltipTitle("جهت کپی محل کلیک کنید");
        }, 1000);
      })
      .catch((err) => {
        console.error(err);
        console.error("مشکلی بوجود آمد!!");
      });
  };

  return (
    <Box
      sx={{
        alignSelf: isUser ? "flex-end" : "flex-start",
        backgroundColor: isUser ? "#1976d2" : "#e0e0e0",
        color: isUser ? "white" : "black",
        padding: "12px",
        borderRadius: "12px",
        maxWidth: "75%",
        boxShadow: "0 1px 3px rgba(0,0,0,0.2)",
      }}
    >
      {" "}
      {isUser ? (
        <Tooltip title={tooltipTitle}>
          <motion.div
            initial={{ opacity: 0, y: 0, x: -10 }}
            animate={{ opacity: 1, y: -2, x: 0 }}
            exit={{ opacity: 0, y: 0 }}
            transition={{ duration: 0.2 }}
            onClick={handleClickMessage}
            style={{ cursor: "pointer" }}
          >
            {message.text}
          </motion.div>
        </Tooltip>
      ) : (
        <motion.div
          initial={{ opacity: 0, y: 0, x: -10 }}
          animate={{ opacity: 1, y: -2, x: 0 }}
          exit={{ opacity: 0, y: 0 }}
          transition={{ duration: 0.2 }}
          onClick={handleClickMessage}
          style={{ cursor: "pointer" }}
        >
          {message.text}
        </motion.div>
      )}
    </Box>
  );
};

export default ChatButton;
