import React, { useEffect, useState } 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,
  postTimeLimits,
} from "../../stores/slices/usageLimitSlice";
import CLoading from "../../components/CLoading";
import { useForm } from "react-hook-form";
import CInput from "../../components/CInput";
import CModal from "../../components/CModal";

type FormValues = {
  hours: string;
  minutes: string;
};

const UsageLimits: React.FC = () => {
  const [isOpenModal, setIsOpenModal] = useState(false);
  const [selectedDayIndex, setSelectedDayIndex] = useState<number | null>(null);

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

  const {
    register,
    setValue,
    handleSubmit,
    formState: { errors },
  } = useForm<FormValues>({
    defaultValues: {
      hours: "",
      minutes: "",
    },
  });

  const onToggleModal = () => {
    setIsOpenModal((prev) => !prev);
  };

  const openDayModal = (day: number, index: number) => {
    setSelectedDayIndex(index);

    const hrs = Math.floor(day / 60);
    const mins = day % 60;

    setValue("hours", String(hrs));
    setValue("minutes", String(mins));

    setIsOpenModal(true);
  };

  const onSubmit = async (data: FormValues) => {
    if (selectedDayIndex === null || !selectedDevice?.id) return;

    const hrs = parseInt(data.hours) || 0;
    const mins = parseInt(data.minutes) || 0;
    const totalMinutes = hrs * 60 + mins;

    const updatedDays = [...days];
    updatedDays[selectedDayIndex] = totalMinutes;

    try {
      await dispatch(
        postTimeLimits({
          deviceId: selectedDevice.id,
          days: updatedDays,
        })
      ).unwrap();

      setIsOpenModal(false);
    } catch (error) {
      console.error("Error updating time limits: ", error);
    }
  };

  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}
                    onClick={() => openDayModal(day, index)}
                  >
                    <p>{weekDays[index]}</p>
                    <p>{formatTime(day)}</p>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      <CModal
        isOpen={isOpenModal}
        onToggle={onToggleModal}
        content={
          <form className="modal__box" onSubmit={handleSubmit(onSubmit)}>
            <h3 className="modal__box__title">Set a limit</h3>

            <div className="modal__box__actions">
              <CInput
                label="Hours"
                placeholder="0"
                {...register("hours", {
                  required: "Hours are required",
                  min: { value: 0, message: "Minimum hours is 0" },
                  max: { value: 23, message: "Maximum hours is 23" },
                })}
                error={errors.hours?.message}
              />

              <CInput
                label="Minutes"
                placeholder="0"
                {...register("minutes", {
                  required: "Minutes are required",
                  min: { value: 0, message: "Minimum minutes is 0" },
                  max: { value: 59, message: "Maximum minutes is 59" },
                })}
                error={errors.minutes?.message}
              />
            </div>

            <div className="modal__box__actions">
              <CButton title={t("button.cancel")} onClick={onToggleModal} />

              <CButton
                title={t("button.confirm")}
                type="submit"
                variant="primary"
                isLoading={loadingPostLimits}
              />
            </div>
          </form>
        }
      />
    </div>
  );
};

export default UsageLimits;
