import React, { useEffect, useState } from "react";
import "./Messengers.css";
import SectionHeader from "../../layouts/SectionHeader";
import { MdInfoOutline } from "react-icons/md";
import CButton from "../../components/CButton";
import { MESSENGERS, type IMessenger } from "../../constants/messengers";
import { useTranslation } from "react-i18next";
import {
  useAppDispatch,
  useAppSelector,
  type RootState,
} from "../../stores/store";
import { fetchMessengerHistory } from "../../stores/slices/messengerHistorySlice";
import CLoading from "../../components/CLoading";

const Messengers: React.FC = () => {
  const today = new Date().toISOString().split("T")[0];
  const [fromDate, setFromDate] = useState(today);
  const [toDate, setToDate] = useState(today);
  const [selectedMessenger, setSelectedMessenger] = useState<IMessenger>(
    MESSENGERS[0]
  );
  const { t } = useTranslation();
  const { selectedDevice } = useAppSelector((state: RootState) => state.device);
  const { chats, loading, error } = useAppSelector(
    (state: RootState) => state.messengerHistory
  );
  const dispatch = useAppDispatch();

  const fetchMessengerHistories = () => {
    if (selectedDevice?.id) {
      const from = new Date(fromDate);
      const to = new Date(toDate);

      const today = new Date().toISOString().split("T")[0];
      const isToday = toDate === today;

      if (isToday) {
        const now = new Date();
        to.setHours(
          now.getHours(),
          now.getMinutes(),
          now.getSeconds(),
          now.getMilliseconds()
        );
      } else {
        to.setHours(23, 59, 59, 999);
      }

      dispatch(
        fetchMessengerHistory({
          deviceId: selectedDevice.id,
          messengerId: selectedMessenger.id,
          dateFrom: from,
          dateTo: to,
          recStart: 0,
        })
      );
    }
  };

  useEffect(() => {
    fetchMessengerHistories();
  }, [dispatch, selectedDevice]);

  return (
    <div className="messengers wrapper">
      <SectionHeader to="/home" />

      <div className="messengers__content">
        <div>
          <div className="messengers__content__header">
            <h3>{t("messengers.title")}</h3>
            <MdInfoOutline className="messengers__content__header__icon" />
          </div>

          {loading && (
            <div className="cloading__center">
              <CLoading />
            </div>
          )}

          {error && <p className="text-danger">{error}</p>}

          {chats.length === 0 && !loading && <p>{t("messengers.empty")}</p>}

          <div className="messenger__chats__list">
            {chats.map((chat) => {
              return (
                <div key={chat.dialog_id} className="messenger__chats__item">
                  <p>{chat.group_name}</p>
                </div>
              );
            })}
          </div>
        </div>

        <div className="messengers__filter">
          <p className="messengers__filter__title">
            {t("common.selectAppAndDates")}
          </p>

          <div className="messengers__filter__messengers">
            {MESSENGERS.map((messenger) => {
              const isSelected = selectedMessenger?.id === messenger.id;

              return (
                <div
                  key={messenger.id}
                  className={`messengers__filter__messenger ${
                    isSelected ? "selected" : ""
                  }`}
                  onClick={() => setSelectedMessenger(messenger)}
                >
                  {messenger.icon}
                  <p>{messenger.name}</p>
                </div>
              );
            })}
          </div>

          <div className="messengers__filter__dates">
            <div className="messengers__filter__date">
              <label htmlFor="from">{t("common.from")}</label>
              <input
                type="date"
                id="from"
                value={fromDate}
                onChange={(e) => setFromDate(e.target.value)}
              />
            </div>

            <div className="messengers__filter__date">
              <label htmlFor="to">{t("common.to")}</label>
              <input
                type="date"
                id="to"
                value={toDate}
                onChange={(e) => setToDate(e.target.value)}
              />
            </div>
          </div>

          <CButton
            title={t("button.search")}
            isLoading={loading}
            onClick={fetchMessengerHistories}
          />
        </div>
      </div>
    </div>
  );
};

export default Messengers;
