"use client";
import React, { useEffect, useState } from "react";
import BreadcrumbComBS from "../breadcrumb/BreadcrumbComBS";
import getImage from "../../utils/getImage";
import { useMutation, useQuery } from "@tanstack/react-query";
import { contactData } from "../../services/services";
import queryKeys from "../../services/queryKeys";
import getCustomTime from "../../utils/getCustomTime";

export default function Contacts() {
  // const {data:contacts, isFetching, isError, error} = useQuery({
  //     queryKey: queryKeys.contacts,
  //     queryFn: () => contactData()
  // })

  const [activeCategoryUID, setActiveCategoryUID] = useState("0"); // HOLDS VALUE OF THE ACTIVE CATEGORY

  const [activeContactUID, setActiveContactUID] = useState("");
  const [activeDetail, setActiveDetail] = useState([]);

  const [filteredContactData, setFiltererdContactData] = useState([]);

  const getContactData = useMutation({
    mutationFn: (reqData) => {
      return contactData(reqData);
    },
    onError: (error) => {
      console.log(error);
    },
    onSuccess: (res) => {
      if (res?.data?.resultCode != "0") {
        throw { message: "Something went wrong" };
      }
      setFiltererdContactData(res?.data?.contacts);
    },
  });

  const changeActiveUID = (uid) => {
    setActiveContactUID(uid);
    let detail = contactsData.filter((item) => item.uid == uid);
    setActiveDetail(detail);
  };

  const changeActiveCategoryUID = (id) => {
    let filteredConData = [];
    setActiveCategoryUID(id);
    if (id == "0") {
      filteredConData = contactsData;
    } else {
      filteredConData = contactsData.filter((item) => item.category == `A00000${id}`);
    }
    setFiltererdContactData(filteredConData);
    changeActiveUID(filteredConData[0]?.uid);
  };

  useEffect(() => {
    let reqData = {
      token: localStorage.getItem("token"), // USER TOKEN
      uid: localStorage.getItem("uid"), // USER UID
    };
    getContactData.mutate(reqData);
  }, []);

  const contactsData = getContactData?.data?.data?.contacts; // LIST OF CONTACTS
  const contactsCategory = getContactData?.data?.data?.category; // LIST OF CATEGORY

  return (
    <>
      <BreadcrumbComBS title="Contacts" paths={["Dashboard", "Contacts"]} />
      {getContactData?.isPending ? (
        <>
          <div className="row">
            <div className="col-12">
              <p className="text-mute">Loading...</p>
            </div>
          </div>
        </>
      ) : getContactData?.error ? (
        <div className="row">
          <div className="col-12">
            <p className="text-danger">{getContactData?.error?.message}</p>
          </div>
        </div>
      ) : (
        <div className="row">
          {/*<div className="vh-100 col-12 flex align-items-center">Coming Soon</div>*/}
          <div className="col-12">
            <div
              className="card card-statistics mail-contant"
              style={{ minHeight: "550px", borderRadius: "10px" }}
            >
              <div className="card-body p-0">
                <div className="row no-gutters">
                  <div className="col-md-4 col-xxl-2 col-md-4">
                    <div className="mail-sidebar">
                      <div className="row justify-content-center">
                        <div className="d-none col-12">
                          <div className="text-center mail-sidebar-title px-4">
                            <a
                              href="#"
                              className="btn btn-primary btn-block py-3 font-weight-bold font-18"
                            >
                              <i className="fa fa-plus pl-2"></i>
                            </a>
                          </div>
                        </div>
                        <div className="col-12">
                          <div className="px-4 py-4">
                            <ul className="pl-0">
                              <li className="py-2">
                                <a href="#">
                                  <span className="nav align-items-center">
                                    <span>
                                      <i className="fa fa-envelope-o text-primary pr-4"></i>
                                    </span>
                                    <span>
                                      <span>Inbox</span>
                                    </span>
                                    <span className="nav-item ml-auto text-right">
                                      <span className="badge badge-pill badge-primary float-right">
                                        {contactsData?.length}
                                      </span>
                                    </span>
                                  </span>
                                </a>
                              </li>
                              {/*<li className="py-2">*/}
                              {/*    <a href="#">*/}
                              {/*                <span*/}
                              {/*                    className="nav align-items-center">*/}
                              {/*                            <span>*/}
                              {/*                                <i className="fa fa-paper-plane-o pr-4"></i>*/}
                              {/*                            </span>*/}
                              {/*                <span>*/}
                              {/*                                <span>Replied Mail</span>*/}
                              {/*                </span>*/}
                              {/*                </span>*/}
                              {/*    </a>*/}
                              {/*</li>*/}
                            </ul>

                            <ul className="pl-0 mt-5">
                              <li
                                className="py-2"
                                onClick={() => changeActiveCategoryUID("0")}
                                style={{ cursor: "pointer" }}
                              >
                                <div>
                                  <span className="nav align-items-center">
                                    <span>
                                      <i
                                        className={`fa fa-circle-o pr-4 ${
                                          activeCategoryUID == "0"
                                            ? "text-primary"
                                            : "text-warning"
                                        }`}
                                      ></i>
                                    </span>
                                    <span>
                                      <span>All</span>
                                    </span>
                                  </span>
                                </div>
                              </li>
                              {contactsCategory &&
                                contactsCategory.map((item) => (
                                  <li
                                    key={item?.cid}
                                    className="py-2"
                                    onClick={() =>
                                      changeActiveCategoryUID(`${item?.cid}`)
                                    }
                                    style={{ cursor: "pointer" }}
                                  >
                                    <div>
                                      <span className="nav align-items-center">
                                        <span>
                                          <i
                                            className={`fa fa-circle-o pr-4 ${
                                              activeCategoryUID ==
                                              `${item?.cid}`
                                                ? "text-primary"
                                                : "text-warning"
                                            }`}
                                          ></i>
                                        </span>
                                        <span>
                                          <span>{item?.description}</span>
                                        </span>
                                      </span>
                                    </div>
                                  </li>
                                ))}
                            </ul>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="col-md-8  col-xxl-4 border-md-t">
                    <div className="mail-content  border-right border-n h-100">
                      <div className="mail-search border-bottom">
                        <div className="row align-items-center mx-0">
                          <div className="col-12">
                            {/*<div className="form-group pt-3">*/}
                            {/*    <input type="text" className="form-control" id="search" placeholder="Search.." />*/}
                            {/*        <i className="fa fa-search"></i>*/}
                            {/*</div>*/}
                          </div>
                        </div>
                      </div>
                      <div className="mail-msg scrollbar scroll_dark">
                        {contactsData &&
                          filteredContactData?.map((contact, index) => {
                            const isActive =
                              contact?.uid == activeContactUID ||
                              (!activeContactUID && index == 0);
                            const avtarImage =
                              contact?.category === undefined
                                ? "avtar/01.jpg"
                                : "avtar/" + contact.category + ".png";
                            return (
                              <div
                                key={contact?.uid}
                                onClick={() => changeActiveUID(contact?.uid)}
                                className={`mail-msg-item ${
                                  isActive && "bg-light"
                                }`}
                              >
                                <a href="#">
                                  <div className="media align-items-center">
                                    <div className="mr-3">
                                      <div className="bg-img">
                                        <img
                                          src={getImage(avtarImage)}
                                          className="img-fluid"
                                          alt="user"
                                        />
                                      </div>
                                    </div>
                                    <div className="w-100">
                                      <div className="mail-msg-item-titel justify-content-between">
                                        <p>
                                          <span
                                            style={{
                                              fontSize: "14px",
                                              color: "#148399",
                                              fontWeight: "bolder",
                                            }}
                                          >
                                            {contact?.sender}
                                          </span>
                                        </p>
                                        {/* <p className="d-none d-xl-block">06:59 <span> PM </span></p> */}
                                        <p className="d-none d-xl-block">
                                          <span style={{ fontSize: "14px" }}>
                                            {new Date(
                                              contact?.added
                                            ).toDateString()}
                                          </span>
                                        </p>
                                      </div>
                                      <h5 className="mb-0 my-2">
                                        {contact?.title}
                                      </h5>
                                      <p>
                                        {contact?.message?.length < 100
                                          ? contact?.message
                                          : contact?.message.substring(0, 101) +
                                            " ..."}
                                      </p>
                                      <p className="d-xl-none">
                                        <span>
                                          {new Date(
                                            contact?.added
                                          ).toDateString()}
                                          {/* {getCustomTime(contact.added)} */}
                                        </span>
                                      </p>
                                    </div>
                                  </div>
                                </a>
                              </div>
                            );
                          })}
                      </div>
                    </div>
                  </div>
                  <div className="col-xxl-6 border-t border-xxl-t">
                    <div className="mail-chat py-5 px-5">
                      <div className="media align-items-center">
                        <div className="bg-img mr-3">
                          <img
                            src={activeContactUID ? getImage("avtar/" + activeDetail[0].category + ".png") : contactsData ? getImage("avtar/" + contactsData[0]?.category + ".png") : getImage("avtar/01.jpg")}
                            className="img-fluid"
                            alt="user"
                          />
                        </div>
                        <div>
                          <h4 className="mb-0" style={{ color: "#148399" }}>
                            {activeContactUID
                              ? activeDetail[0]?.sender
                              : filteredContactData[0]?.sender}
                          </h4>
                          <p>
                            {activeContactUID
                              ? new Date(activeDetail[0]?.added).toDateString()
                              : new Date(
                                  filteredContactData[0]?.added
                                ).toDateString()}
                          </p>
                        </div>
                      </div>
                      <div className="mt-4 d-flex justify-content-between">
                        <div>
                          <h3>
                            {activeContactUID
                              ? activeDetail[0]?.title
                              : filteredContactData[0]?.title}
                          </h3>
                        </div>
                        <div className="d-flex">
                          {/*<a href="javascript:void(0)"><i className="fa fa-reply font-22 pr-3"></i></a>*/}
                          {/*<a href="javascript:void(0)"><i className="fa fa-print font-22"></i></a>*/}
                        </div>
                      </div>
                      <div>
                        <p>
                          {activeContactUID
                            ? activeDetail[0]?.message
                            : filteredContactData[0]?.message}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}