import React, { useEffect, useState } from "react";
import "./Recording.css";
import SectionHeader from "../../layouts/SectionHeader";
import { MdInfoOutline } from "react-icons/md";
import CButton from "../../components/CButton";
import { useTranslation } from "react-i18next";
import { FaMicrophoneLines } from "react-icons/fa6";
import { FaImage } from "react-icons/fa";
import { IoCloudDownloadOutline, IoPlay } from "react-icons/io5";
import {
  useAppDispatch,
  useAppSelector,
  type RootState,
} from "../../stores/store";
import { fetchAudioFiles } from "../../stores/slices/deviceSlice";
import { AiOutlineAudio } from "react-icons/ai";
import { APPS, type IApp } from "../../constants/apps";

const Recording: React.FC = () => {
  const [selectedApp, setSelectedApp] = useState<IApp>(APPS[0]);
  const [selectedTab, setSelectedTab] = useState<"audio" | "image">("audio");
  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 { audioList, isAudioListLoading } = useAppSelector(
    (state: RootState) => state.device
  );
  const dispatch = useAppDispatch();

  const filterAudioHistory = () => {
    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(
        fetchAudioFiles({
          deviceId: selectedDevice.id,
          dateFrom: from,
          dateTo: to,
          appId: selectedApp.id,
        })
      );
    }
  };

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

  const renderTabContent = () => {
    switch (selectedTab) {
      case "audio":
        return (
          <div className="recording__content">
            <div>
              <div className="recording__content__header">
                <h3>{t("recording.audioFiles")}</h3>
                <MdInfoOutline className="recording__content__header__icon" />
              </div>

              {audioList.length === 0 && (
                <p className="recording__content__empty">
                  {t("recording.audioFilesEmpty")}
                </p>
              )}

              <div className="recording__audio__list">
                {audioList.map((audio, index) => {
                  return (
                    <div key={index} className="recording__audio__item">
                      <div className="recording__audio__item__info">
                        <AiOutlineAudio className="recording__audio__item__icon" />

                        <div>
                          <h4>{audio.date}</h4>
                          <p>{audio.file_size}</p>
                        </div>
                      </div>

                      <div className="recording__audio__item__info">
                        <IoCloudDownloadOutline className="recording__audio__item__icon" />
                        <IoPlay className="recording__audio__item__icon" />
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            <div className="recording__filter">
              <p className="recording__filter__title">
                {t("common.selectAppAndDates")}
              </p>

              <div className="apps__filter__messengers">
                {APPS.map((app) => {
                  const isSelected = selectedApp?.id === app.id;

                  return (
                    <div
                      key={app.id}
                      className={`apps__filter__messenger ${
                        isSelected ? "selected" : ""
                      }`}
                      onClick={() => setSelectedApp(app)}
                    >
                      {app.icon}
                      <p>{app.name}</p>
                    </div>
                  );
                })}
              </div>

              <div className="recording__filter__dates">
                <div className="recording__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="recording__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={filterAudioHistory}
                isLoading={isAudioListLoading}
              />
            </div>
          </div>
        );
      case "image":
        return (
          <div className="recording__content">
            <div>
              <div className="recording__content__header">
                <h3>{t("recording.imageFiles")}</h3>
                <MdInfoOutline className="recording__content__header__icon" />
              </div>

              <p className="recording__content__empty">
                {t("recording.imageFilesEmpty")}
              </p>
            </div>

            <div className="recording__filter">
              <p className="recording__filter__title">
                {t("common.selectAppAndDates")}
              </p>

              <div className="recording__filter__dates">
                <div className="recording__filter__date">
                  <label htmlFor="from">{t("common.from")}</label>
                  <input type="date" id="from" />
                </div>

                <div className="recording__filter__date">
                  <label htmlFor="to">{t("common.to")}</label>
                  <input type="date" id="to" />
                </div>
              </div>

              <CButton title={t("button.search")} />
            </div>
          </div>
        );
      default:
        return null;
    }
  };

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

      {renderTabContent()}

      <div className="recording__tabs">
        <div
          onClick={() => setSelectedTab("audio")}
          className={`recording__tab ${
            selectedTab === "audio" ? "active" : ""
          }`}
        >
          <FaMicrophoneLines />
          <p>{t("recording.audio")}</p>
        </div>

        <div
          onClick={() => setSelectedTab("image")}
          className={`recording__tab ${
            selectedTab === "image" ? "active" : ""
          }`}
        >
          <FaImage />
          <p>{t("recording.image")}</p>
        </div>
      </div>
    </div>
  );
};

export default Recording;
