import React, { useEffect, useState } from "react";
import "./BrowserHistory.css";
import SectionHeader from "../../layouts/SectionHeader";
import { MdInfoOutline } from "react-icons/md";
import CButton from "../../components/CButton";
import {
  useAppDispatch,
  useAppSelector,
  type RootState,
} from "../../stores/store";
import { fetchBrowserHistory } from "../../stores/slices/browserHistorySlice";
import { useTranslation } from "react-i18next";
import CLoading from "../../components/CLoading";

const BrowserHistory: 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 { browserHistories, loading, error } = useAppSelector(
    (state: RootState) => state.browserHistory
  );
  const dispatch = useAppDispatch();

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

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

      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(
        fetchBrowserHistory({
          deviceId: selectedDevice.id,
          dateFrom: from,
          dateTo: to,
          recStart: 0,
        })
      );
    }
  };

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

      <div className="browserhistory__content">
        <div>
          <div className="browserhistory__content__header">
            <h3>{t("browserHistory.title")}</h3>
            <MdInfoOutline className="browserhistory__content__header__icon" />
          </div>

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

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

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

          <div className="browserhistory__list">
            {browserHistories.map((history, index) => {
              return (
                <div className="browserhistory__item" key={index}>
                  <p className="browserhistory__item__title">
                    {t("browserHistory.website")}: {history.name}
                  </p>
                  <p>
                    {t("browserHistory.date")}: {history.date}
                  </p>
                </div>
              );
            })}
          </div>
        </div>

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

          <div className="browserhistory__filter__dates">
            <div className="browserhistory__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="browserhistory__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={filterBrowserHistory}
            isLoading={loading}
          />
        </div>
      </div>
    </div>
  );
};

export default BrowserHistory;
