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 dispatch = useAppDispatch();

  const { messengerHistories, loading, error } = useAppSelector(
    (state: RootState) => state.messengerHistory
  );

  const fetchMessengerHistories = () => {
    if (selectedDevice?.id) {
      dispatch(
        fetchMessengerHistory({
          deviceId: selectedDevice.id,
          messengerId: selectedMessenger.id,
          dateFrom: new Date(fromDate),
          dateTo: new Date(toDate),
          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>}

          {messengerHistories.length === 0 && !loading && (
            <p>{t("messengers.empty")}</p>
          )}
        </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;
