import React, { useEffect, useState } from "react";
import "./Settings.css";
import { useLanguage } from "../../contexts/LanguageContext/useLanguage";
import CSelect from "../../components/CSelect";
import en from "../../assets/images/flag-en.png";
import ru from "../../assets/images/flag-ru.png";
import uz from "../../assets/images/flag-uz.png";
import { FiUserMinus } from "react-icons/fi";
import { IoKeyOutline, IoPhonePortraitOutline } from "react-icons/io5";
import {
  MdOutlineCreditCardOff,
  MdOutlineEdit,
  MdOutlineLogout,
} from "react-icons/md";
import { useTranslation } from "react-i18next";
import {
  useAppDispatch,
  useAppSelector,
  type RootState,
} from "../../stores/store";
import { logout } from "../../stores/slices/authSlice";
import CModal from "../../components/CModal";
import CButton from "../../components/CButton";
import { Link } from "react-router-dom";
import CInput from "../../components/CInput";
import {
  checkPassword,
  deleteAudio,
  deleteImage,
  deleteMedia,
  setTimezone,
} from "../../stores/slices/accountSlice";
import { TIME_ZONES } from "../../constants/timezones";
import { FaChevronDown, FaChevronUp, FaImages } from "react-icons/fa";
import { FaRegTrashCan } from "react-icons/fa6";
import { RiHeadphoneFill } from "react-icons/ri";
import { GrMultimedia } from "react-icons/gr";
import {
  deleteDevice,
  editDevice,
  refreshDevices,
} from "../../stores/slices/deviceSlice";
import {
  checkBalance,
  toggleSubscriptionAuto,
} from "../../stores/slices/billingSlice";

const deleteDatas = [
  {
    id: 1,
    name: "settings.deleteAudio",
    icon: <RiHeadphoneFill className="settings__data__item__info__icon" />,
  },
  {
    id: 2,
    name: "settings.deleteImages",
    icon: <FaImages className="settings__data__item__info__icon" />,
  },
  {
    id: 3,
    name: "settings.deleteMedia",
    icon: <GrMultimedia className="settings__data__item__info__icon" />,
  },
];

const Settings: React.FC = () => {
  const [password, setPassword] = useState("");
  const [selectedTimezone, setSelectedTimezone] = useState({
    ianaId: "Asia/Tashkent",
    name: "(UTC+05:00) Ashgabat, Tashkent",
  });
  const [isOpenLogoutModal, setIsOpenLogoutModal] = useState(false);
  const [isOpenDeleteAccountModal, setIsOpenDeleteAccountModal] =
    useState(false);
  const [isOpenDeleteData, setIsOpenDeleteData] = useState(false);
  const [selectedDeleteData, setSelectedDeleteData] = useState<null | number>(
    null
  );
  const [selectedDevice, setSelectedDevice] = useState<{
    id: string;
    name: string;
  } | null>(null);
  const [isOpenDevices, setIsOpenDevices] = useState(false);
  const [isOpenEditDevice, setIsOpenEditDevice] = useState(false);
  const [isOpenDeleteDevice, setIsOpenDeleteDevice] = useState(false);
  const [isOpenDeleteDataModal, setIsOpenDeleteDataModal] = useState(false);
  const [isOpenUnsubscribeModal, setIsOpenUnsubscribeModal] = useState(false);
  const { language, changeLanguage } = useLanguage();
  const { t } = useTranslation();
  const { isCheckPasswordLoading, errorCheckPassword } = useAppSelector(
    (state: RootState) => state.account
  );
  const { session, deletingData } = useAppSelector(
    (state: RootState) => state.account
  );
  const { devices, isDeletingDevice, isEditingDevice } = useAppSelector(
    (state: RootState) => state.device
  );
  const { balance, isToggleSubAutoLoading } = useAppSelector(
    (state: RootState) => state.billing
  );
  const dispatch = useAppDispatch();

  const toggleLogoutModal = () => {
    setIsOpenLogoutModal((prev) => !prev);
  };

  const toggleDeleteAccountModal = () => {
    setIsOpenDeleteAccountModal((prev) => !prev);
  };

  const toggleIsOpenDeleteData = () => {
    setIsOpenDeleteData((prev) => !prev);
  };

  const toggleIsOpenDeleteDataModal = () => {
    setIsOpenDeleteDataModal((prev) => !prev);
  };

  const toggleIsOpenDevices = () => {
    setIsOpenDevices((prev) => !prev);
  };

  const toggleIsOpenEditDevice = () => {
    setIsOpenEditDevice((prev) => !prev);
  };

  const toggleIsOpenDeleteDevice = () => {
    setIsOpenDeleteDevice((prev) => !prev);
  };

  const toggleIsOpenUnsubscribeModal = () => {
    setIsOpenUnsubscribeModal((prev) => !prev);
  };

  const handleEditDevice = async () => {
    try {
      if (selectedDevice) {
        await dispatch(
          editDevice({ deviceId: selectedDevice.id, name: selectedDevice.name })
        );

        await dispatch(refreshDevices());
      }
    } catch (error) {
      console.error("Error editing device: ", error);
    } finally {
      setIsOpenEditDevice(false);
    }
  };

  const handleDeleteDevice = async () => {
    try {
      if (selectedDevice) {
        await dispatch(deleteDevice(selectedDevice.id));
      }

      await dispatch(refreshDevices());
    } catch (error) {
      console.error("Error deleting device: ", error);
    } finally {
      setIsOpenDeleteDevice(false);
    }
  };

  const handleDeleteData = async () => {
    try {
      if (selectedDeleteData) {
        if (selectedDeleteData === 1) {
          await dispatch(deleteAudio());
        } else if (selectedDeleteData === 2) {
          await dispatch(deleteImage());
        } else if (selectedDeleteData === 3) {
          await dispatch(deleteMedia());
        }
      }
    } catch (error) {
      console.error("Error deleting data:", error);
    } finally {
      setIsOpenDeleteDataModal(false);
      setSelectedDeleteData(null);
    }
  };

  useEffect(() => {
    if (session.timeZoneStr) {
      const tz = TIME_ZONES.find((tz) => tz.ianaId === session.timeZoneStr);
      if (tz) {
        setSelectedTimezone(tz);
      }
    }
  }, [session]);

  useEffect(() => {
    dispatch(checkBalance());
  }, [dispatch]);

  return (
    <div className="settings">
      <h3 className="settings__title">{t("settings.title")}</h3>

      <div className="settings__content">
        <CSelect
          value={language}
          onChange={(flag: string) =>
            changeLanguage(flag as "en" | "ru" | "uz")
          }
          options={[
            {
              label: "English",
              value: "en",
              image: (
                <img
                  src={en}
                  alt="en"
                  style={{ width: 20, height: 20, objectFit: "cover" }}
                />
              ),
            },
            {
              label: "Русский",
              value: "ru",
              image: (
                <img
                  src={ru}
                  alt="ru"
                  style={{ width: 20, height: 20, objectFit: "cover" }}
                />
              ),
            },
            {
              label: "Uzbek",
              value: "uz",
              image: (
                <img
                  src={uz}
                  alt="uz"
                  style={{ width: 20, height: 20, objectFit: "cover" }}
                />
              ),
            },
          ]}
        />

        <CSelect
          value={selectedTimezone.ianaId}
          options={TIME_ZONES.map((tz) => ({
            label: tz.name,
            value: tz.ianaId,
          }))}
          onChange={(ianaId: string) => {
            const tz = TIME_ZONES.find((tz) => tz.ianaId === ianaId);
            if (tz) {
              setSelectedTimezone(tz);
              dispatch(setTimezone({ zone: tz.ianaId, offset: tz.offset }));
            }
          }}
        />

        <div>
          <div onClick={toggleIsOpenDevices} className="settings__data__header">
            <p>{t("settings.myDevices")}</p>
            {isOpenDevices ? <FaChevronUp /> : <FaChevronDown />}
          </div>

          {isOpenDevices && (
            <div className="settings__data__list">
              {devices.length > 0 ? (
                <>
                  {devices.map((device) => {
                    return (
                      <div key={device.id} className="settings__data__item">
                        <div className="settings__data__item__info">
                          <IoPhonePortraitOutline className="settings__data__item__info__icon" />
                          <p>{device.name}</p>
                        </div>

                        <div className="settings__data__item__actions">
                          <MdOutlineEdit
                            className="settings__data__item__actions__icon"
                            onClick={() => {
                              setSelectedDevice(device);
                              setIsOpenEditDevice(true);
                            }}
                          />
                          <FaRegTrashCan
                            className="settings__data__item__actions__icon text-danger"
                            onClick={() => {
                              setSelectedDevice(device);
                              setIsOpenDeleteDevice(true);
                            }}
                          />
                        </div>
                      </div>
                    );
                  })}
                </>
              ) : (
                <p className="settings__data__no">{t("settings.noDevices")}</p>
              )}
            </div>
          )}
        </div>

        <div>
          <div
            onClick={toggleIsOpenDeleteData}
            className="settings__data__header"
          >
            <p>{t("settings.deleteData")}</p>
            {isOpenDeleteData ? <FaChevronUp /> : <FaChevronDown />}
          </div>

          {isOpenDeleteData && (
            <div className="settings__data__list">
              {deleteDatas.map((data) => {
                return (
                  <div key={data.id} className="settings__data__item">
                    <div className="settings__data__item__info">
                      {data.icon}
                      <p>{t(data.name)}</p>
                    </div>

                    <div className="settings__data__item__actions">
                      <FaRegTrashCan
                        className="settings__data__item__actions__icon text-danger"
                        onClick={() => {
                          setSelectedDeleteData(data.id);
                          toggleIsOpenDeleteDataModal();
                        }}
                      />
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        <h3>{t("settings.account")}</h3>

        <div
          className="settings__content__action"
          onClick={toggleDeleteAccountModal}
        >
          <FiUserMinus className="settings__content__action__icon" />{" "}
          {t("settings.deleteAccount")}
        </div>

        {balance.subAuto && (
          <div
            className="settings__content__action"
            onClick={toggleIsOpenUnsubscribeModal}
          >
            <MdOutlineCreditCardOff className="settings__content__action__icon" />
            {t("settings.unsubscribe")}
          </div>
        )}

        <Link
          to={"/settings/recover-password"}
          className="settings__content__action"
        >
          <IoKeyOutline className="settings__content__action__icon" />{" "}
          {t("settings.recoverPassword")}
        </Link>

        <div className="settings__content__action" onClick={toggleLogoutModal}>
          <MdOutlineLogout className="settings__content__action__icon" />{" "}
          {t("settings.logout")}
        </div>
      </div>

      <CModal
        isOpen={isOpenLogoutModal}
        onToggle={toggleLogoutModal}
        content={
          <div className="modal__box">
            <h3 className="modal__box__title">{t("logout.title")}</h3>
            <p>{t("logout.desc")}</p>
            <div className="modal__box__actions">
              <CButton title={t("button.cancel")} onClick={toggleLogoutModal} />
              <CButton
                title={t("button.logout")}
                variant="danger"
                onClick={() => dispatch(logout())}
              />
            </div>
          </div>
        }
      />

      <CModal
        isOpen={isOpenEditDevice}
        onToggle={toggleIsOpenEditDevice}
        content={
          <div className="modal__box">
            <h3 className="modal__box__title">{t("common.rename")}</h3>
            <CInput
              placeholder={t("common.deviceName")}
              value={selectedDevice?.name || ""}
              onChange={(e) => {
                if (selectedDevice) {
                  setSelectedDevice({
                    ...selectedDevice,
                    name: e.target.value,
                  });
                }
              }}
            />

            <div className="modal__box__actions">
              <CButton
                title={t("button.cancel")}
                onClick={toggleIsOpenEditDevice}
              />
              <CButton
                title={t("button.ok")}
                onClick={handleEditDevice}
                isLoading={isEditingDevice}
              />
            </div>
          </div>
        }
      />

      <CModal
        isOpen={isOpenDeleteDevice}
        onToggle={toggleIsOpenDeleteDevice}
        content={
          <div className="modal__box">
            <h3 className="modal__box__title">
              {t("device.deleteDevice")} <br />
              {selectedDevice?.name}
            </h3>
            <p style={{ textAlign: "center" }}>
              {t("device.deleteDeviceDesc")}
            </p>
            <div className="modal__box__actions">
              <CButton
                title={t("button.cancel")}
                onClick={toggleIsOpenDeleteDevice}
              />
              <CButton
                title={t("button.delete")}
                variant="danger"
                onClick={handleDeleteDevice}
                isLoading={isDeletingDevice}
              />
            </div>
          </div>
        }
      />

      <CModal
        isOpen={isOpenDeleteAccountModal}
        onToggle={toggleDeleteAccountModal}
        content={
          <div className="modal__box">
            <h3 className="modal__box__title">{t("common.confirm")}</h3>
            <CInput
              placeholder={t("common.passwordPlaceholder")}
              label={t("common.password")}
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />

            {errorCheckPassword && (
              <p className="text-danger text-center">{errorCheckPassword}</p>
            )}

            <div className="modal__box__actions">
              <CButton
                title={t("button.cancel")}
                onClick={toggleDeleteAccountModal}
              />
              <CButton
                title={t("button.confirm")}
                variant="danger"
                isLoading={isCheckPasswordLoading}
                onClick={() => dispatch(checkPassword(password))}
              />
            </div>
          </div>
        }
      />

      <CModal
        isOpen={isOpenDeleteDataModal}
        onToggle={toggleIsOpenDeleteDataModal}
        content={
          <div className="modal__box">
            <h3 className="modal__box__title">{t("settings.deleteData")}</h3>
            <p style={{ textAlign: "center" }}>
              {selectedDeleteData === 1 && t("settings.deleteAudioDesc")}
              {selectedDeleteData === 2 && t("settings.deleteImagesDesc")}
              {selectedDeleteData === 3 && t("settings.deleteMediaDesc")}
            </p>
            <div className="modal__box__actions">
              <CButton
                title={t("button.cancel")}
                onClick={toggleIsOpenDeleteDataModal}
              />
              <CButton
                title={t("button.delete")}
                variant="danger"
                onClick={handleDeleteData}
                isLoading={deletingData}
              />
            </div>
          </div>
        }
      />

      <CModal
        isOpen={isOpenUnsubscribeModal}
        onToggle={toggleIsOpenUnsubscribeModal}
        content={
          <div className="modal__box">
            <h3 className="modal__box__title">{t("settings.unsubscribe")}</h3>
            <p style={{ textAlign: "center" }}>
              {t("settings.unsubscribeDesc")}
            </p>
            <div className="modal__box__actions">
              <CButton
                title={t("button.cancel")}
                onClick={toggleIsOpenUnsubscribeModal}
              />
              <CButton
                title={t("button.ok")}
                variant="danger"
                isLoading={isToggleSubAutoLoading}
                onClick={async () => {
                  await dispatch(toggleSubscriptionAuto(false));
                  toggleIsOpenUnsubscribeModal();
                }}
              />
            </div>
          </div>
        }
      />
    </div>
  );
};

export default Settings;
