import React, { useEffect, useState } from "react";
import "./Calls.css";
import SectionHeader from "../../layouts/SectionHeader";
import { MdInfoOutline } from "react-icons/md";
import CButton from "../../components/CButton";
import { useTranslation } from "react-i18next";
import {
  useAppDispatch,
  useAppSelector,
  type RootState,
} from "../../stores/store";
import { fetchCallHistory } from "../../stores/slices/callHistorySlice";
import { HiOutlinePhoneMissedCall } from "react-icons/hi";
import { VscCallOutgoing } from "react-icons/vsc";
import { IoCallOutline } from "react-icons/io5";
import CLoading from "../../components/CLoading";

const Calls: React.FC = () => {
  const today = new Date().toISOString().split("T")[0];
  const [fromDate, setFromDate] = useState(today);
  const [toDate, setToDate] = useState(today);
  const { t } = useTranslation();
  const { selectedDevice } = useAppSelector((state: RootState) => state.device);
  const { callHistories, loading, error } = useAppSelector(
    (state: RootState) => state.callHistory
  );
  const dispatch = useAppDispatch();

  const getCallIcon = (callType: string) => {
    if (callType == "3") {
      return (
        <HiOutlinePhoneMissedCall
          style={{ color: "#F44336", fontSize: "18px" }}
        />
      );
    } else if (callType == "2") {
      return <VscCallOutgoing style={{ color: "#4CAF50", fontSize: "18px" }} />;
    } else {
      return <IoCallOutline style={{ color: "#448AFF", fontSize: "18px" }} />;
    }
  };

  useEffect(() => {
    if (selectedDevice?.id) {
      filterCallHistory();
    }
  }, [dispatch, selectedDevice]);

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

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

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

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

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

      <div className="calls__content">
        <div>
          <div className="calls__content__header">
            <h3>{t("callHistory.title")}</h3>
            <MdInfoOutline className="calls__content__header__icon" />
          </div>

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

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

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

          <div className="callhistory__list">
            {callHistories.map((history, index) => {
              return (
                <div className="callhistory__item" key={index}>
                  <div>
                    {getCallIcon(history.call_type)}
                    <p className="callhistory__item__title">{history.name}</p>
                  </div>

                  <p>{history.date}</p>
                </div>
              );
            })}
          </div>
        </div>

        <div className="calls__filter">
          <p className="calls__filter__title">{t("common.selectDates")}</p>

          <div className="calls__filter__dates">
            <div className="calls__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="calls__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")}
            onClick={filterCallHistory}
            isLoading={loading}
          />
        </div>
      </div>
    </div>
  );
};

export default Calls;
