import React, { useState, useContext, useEffect, useRef } from "react";
import { Button, Form, FormControl, InputGroup } from "react-bootstrap";
import { UserContext } from "../contexts/userContext";
import { useSelector, useDispatch } from "react-redux";
import { chatActions } from "../store/chat-slice";
import { BsCircleFill } from "react-icons/bs";
import TypingBar from "./TypingBar";
import {getDate,getMonth} from '../helpers'

const ChatWindow = ({ room }) => {
  const messagesEndRef = useRef(null);

  const [message, setMessage] = useState("");
  const { user } = useContext(UserContext);
  const connection = useSelector((state) => state.chat.connection);
  const connections = useSelector((state) => state.chat.connections);
  const activeRoom = useSelector((state) => state.chat.activeRoom);
  const messages = useSelector((state) => state.chat.messages);
  const dispatch = useDispatch();
  const [proba,setProba] = useState([])

  useEffect(() => {
    showDate()
  },[messages])

  const showDate = () => {
    let temp = [...messages];
    if(temp[0] !== undefined){
      let date = getDate(temp[0].createdAtUtc)
      let d = date.getDate();
      let m = date.getMonth();
      let y = date.getFullYear();
      temp.splice(0,0,{
        content:getMonth(m) + " " + d.toString() + ", " +  y.toString(),
        senderId:undefined,  //is information about date not message
        username:undefined,
        id:null,
        createdAtUtc: undefined,
      })
      for (let index = 0; index < temp.length; index++) {
        const element = temp[index];
        let day = getDate(element.createdAtUtc).getDate();
        if(temp[index + 1] !== undefined){
          if(temp[index + 1].createdAtUtc !== undefined)
          {
            if(temp[index].isAccessMessage === undefined){
              if(getDate(temp[index + 1].createdAtUtc).getDate() > day ){
                let elem = temp[index + 1].createdAtUtc;
                let d = getDate(elem).getDate()
                let m = getDate(elem).getMonth()
                let y = getDate(elem).getFullYear()
                temp.splice(index+1,0,{
                      content:getMonth(m) + " " + d.toString() + ", " +  y.toString(),
                      senderId:undefined, //is information about date not message
                      username:undefined,
                      id:null,
                      createdAtUtc: undefined,
                    })
              }
            }
          }
        }
      }
    }
    setProba(temp)
  }

  useEffect(() => {
    dispatch(chatActions.setMessages(room.messages));
  }, [dispatch, room.messages]);

  const leftRoomHandler = async () => {
    const userToFetch = connections.filter(
      (conn) => conn.userId === user.id && conn.roomId === activeRoom.id
    );

    await connection.invoke("LeaveRoom", {
      connId: userToFetch[0].connId,
    });
    dispatch(
      chatActions.leaveRoom({ roomId: activeRoom.id, customerId: user.id })
    );
  };

  const onSendMessageToGroupHandler = async (e) => {
    e.preventDefault();

    const userToFetch = connections.filter(
      (conn) => conn.userId === user.id && conn.roomId === activeRoom.id
    );

    await connection.invoke("SendMessageToGroup", {
      userId: user.id,
      message,
      connId: userToFetch[0].connId,
    });

    setMessage("");
  };

  const status = useSelector((s) => s.status);
  const { activeUsers } = status;

  const messageOnChangeHandler = async (e) => {
    setMessage(e.target.value);

    const userToFetch = connections.filter(
      (conn) => conn.userId === user.id && conn.roomId === activeRoom.id
    );

    await connection.send("SeeWhoIsTyping", {
      message: `${user.username} is typing...`,
      connId: userToFetch[0].connId,
      roomId: activeRoom.id,
    });
  };

  return (
    <div className="p-2 position-relative bg-main rounded h-100 d-flex flex-column">
    <div className="p-2 px-3 pt-3 position-relative bg-light rounded h-100 d-flex flex-column">
      <div style={{ height: "60px" }}>
        <h2 className="p-0 m-0">{room.name}</h2>
        <button
          onClick={leftRoomHandler}
          className='btn btn-danger mb-2 leave-btn'
        >
          Leave Room
        </button>
      </div>

      <div className="messages bg-white border ">
        <div className="overlay p-3 px-4 d-flex flex-column-reverse">
        {/* mapirane poruke */}
        {user &&
          proba
            .map((n, index) => (
              <div
                key={index}
                className={
                  n.isAccessMessage === true || n.senderId === undefined
                    ? "d-flex flex-column align-items-center"
                    : n.senderId === user.id
                    ? "d-flex flex-column align-items-end"
                    : "d-flex flex-column align-items-start"
                }
              >
                <div
                  className={`p-2 px-3 mb-0 rounded message ${
                    n.isAccessMessage === true || n.senderId === undefined
                    ? "text-muted small"
                    : n.senderId !== user.id
                      ? "bg-main-primary text-light chatMsg"
                      : "bg-light text-dark chatMsg"
                  }`}
                >
                  <div style={{display:'flex',flexDirection:'column'}}>
                  {n.content}
                  {
                  n.senderId !== undefined ? 
                  <div style={{fontSize:12,alignSelf:'flex-end'}}>
                    {(new Date(Date.parse(n.createdAtUtc))).getHours().toString()}
                    :
                    {(new Date(Date.parse(n.createdAtUtc))).getMinutes().toString()}
                  </div> : ''
                  }
                  
                </div>
                </div>
                <p className="text-muted small m-0 p-0 mb-4">
                  {n.senderId !== user?.id && !n.isAccessMessage && n.senderId !== undefined ? (
                    activeUsers.some((m) => m === n.senderId) ? (
                      <BsCircleFill className="me-2 text-success" />
                    ) : (
                      <BsCircleFill className="me-2 text-danger" />
                    )
                  ) : (
                    ""
                  )}
                  {n.isAccessMessage !== true && n.senderId !== user?.id && n.username}
                </p>
              </div>
            ))
            .reverse()}
        <div ref={messagesEndRef} /></div>
      </div>

      <TypingBar id={activeRoom.id} />

      <Form
        style={{ height: "80px" }}
        className="d-flex align-items-center"
        onSubmit={onSendMessageToGroupHandler}
      >
        <InputGroup className="mb-3">
          <FormControl
            placeholder="Enter your messagge..."
            aria-label="Enter your messagge..."
            aria-describedby="basic-addon2"
            onChange={(e) => messageOnChangeHandler(e)}
            value={message}
          />

          <Button
            className="px-5"
            variant="outline-secondary"
            id="button-addon2"
            type="submit"
          >
            Send
          </Button>
        </InputGroup>
      </Form>
    </div>
    </div>
  );
};

export default ChatWindow;
