import React, { useEffect } from "react";
import "./UsageLimits.css";
import SectionHeader from "../../layouts/SectionHeader";
import CButton from "../../components/CButton";
import { useTranslation } from "react-i18next";
import { useAppDispatch, type RootState } from "../../stores/store";
import { useSelector } from "react-redux";
import { fetchTimeLimits } from "../../stores/slices/usageLimitSlice";
import CLoading from "../../components/CLoading";

const UsageLimits: React.FC = () => {
  const { selectedDevice } = useSelector((state: RootState) => state.device);
  const { days, isLoadingDays } = useSelector(
    (state: RootState) => state.usageLimit
  );
  const dispatch = useAppDispatch();
  const { t } = useTranslation();

  useEffect(() => {
    if (!selectedDevice?.id) return;

    dispatch(fetchTimeLimits(selectedDevice?.id));
  }, [dispatch, selectedDevice]);

  const weekDays = [
    t("weekdays.monday"),
    t("weekdays.tuesday"),
    t("weekdays.wednesday"),
    t("weekdays.thursday"),
    t("weekdays.friday"),
    t("weekdays.saturday"),
    t("weekdays.sunday"),
  ];

  const formatTime = (minutes: number) => {
    const hrs = String(Math.floor(minutes / 60)).padStart(2, "0");
    const mins = String(minutes % 60).padStart(2, "0");
    return `${hrs}:${mins}`;
  };

  return (
    <div className="usagelimits wrapper">
      <SectionHeader to="/home/manage-apps" />

      <div className="usagelimits__content">
        <div>
          <h3>{t("usageLimits.title")}</h3>
          <p>{t("usageLimits.desc")}</p>
          <p>{t("usageLimits.allowedApps")}</p>

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

          {!isLoadingDays && (
            <div className="usagelimits__days">
              {days.map((day, index) => {
                return (
                  <div className="usagelimits__day" key={index}>
                    <p>{weekDays[index]}</p>
                    <p>{formatTime(day)}</p>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        <CButton title={t("button.save")} />
      </div>
    </div>
  );
};

export default UsageLimits;
