import React, { useCallback, useEffect, useMemo } from "react";

import classNames from "classnames";
import { useDispatch, useSelector } from "react-redux";

import RadioItem from "@enact/sandstone/RadioItem";
import SwitchItem from "@enact/sandstone/SwitchItem";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";

import appinfo from "../../../webos-meta/appinfo.json";
import { changeLocalSettings, setHidePopup } from "../../actions/commonActions";
import THeader from "../../components/THeader/THeader";
import TPanel from "../../components/TPanel/TPanel";
import TScroller from "../../components/TScroller/TScroller";
import css from "./DebugPanel.module.less";

const Container = SpotlightContainerDecorator(
  { enterTo: "last-focused" },
  "div"
);

export default function DebugPanel({ spotlightId }) {
  const dispatch = useDispatch();
  const appStatus = useSelector((state) => state.common.appStatus);
  const httpHeader = useSelector((state) => state.common.httpHeader);
  const localSettings = useSelector((state) => state.localSettings);
  const infos = useMemo(() => {
    let v = [];
    v.push({ title: "Version(App)", value: appinfo.version });
    v.push({
      title: "WebOS",
      value: appStatus.webOSVersion + "(" + httpHeader?.os_ver + ")",
    });
    v.push({ title: "serverHOST", value: appStatus.serverHOST });
    v.push({ title: "httpHeader", value: JSON.stringify(httpHeader) });
    v.push({ title: "href", value: window.location.href });
    v.push({ title: " ", value: " " });
    return v;
  }, [appStatus, httpHeader]);

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

  const switches = useMemo(() => {
    let v = [];
    v.push({
      title: "Log Enable",
      value: localSettings.logEnable,
      func: ({ selected }) => {
        dispatch(changeLocalSettings({ logEnable: selected }));
      },
    });
    return v;
  }, [dispatch, localSettings]);

  const onChangeServer = useCallback(
    (type) => () => {
      if (type === localSettings.serverType) {
        return;
      } else {
        dispatch(
          changeLocalSettings({ serverType: type, ricCodeSetting: "system" })
        );
        console.log("[DebugPanel] Server setting changed to:", type);
        // 즉시 리로드하지 않고 3초 후 자동 리로드
        setTimeout(() => {
          if (typeof window === "object") {
            console.log("[DebugPanel] Reloading after server change...");
            window.location.reload();
          }
        }, 3000);
      }
    },
    [dispatch, localSettings]
  );

  const onChangeServerRic = useCallback(
    (type) => () => {
      dispatch(changeLocalSettings({ ricCodeSetting: type }));
      console.log("[DebugPanel] RicCode setting changed to:", type);
      // 즉시 리로드하지 않고 3초 후 자동 리로드
      setTimeout(() => {
        if (typeof window === "object") {
          console.log("[DebugPanel] Reloading after ricCode change...");
          window.location.reload();
        }
      }, 3000);
    },
    [dispatch, localSettings]
  );

  const onChangeLanguage = useCallback(
    (type) => () => {
      dispatch(changeLocalSettings({ languageSetting: type }));
      console.log("[DebugPanel] Language setting changed to:", type);
      // 즉시 리로드하지 않고 3초 후 자동 리로드
      setTimeout(() => {
        if (typeof window === "object") {
          console.log("[DebugPanel] Reloading after language change...");
          window.location.reload();
        }
      }, 3000);
    },
    [dispatch]
  );
  console.log("###localSettings.serverType", localSettings.serverType);
  return (
    <TPanel isTabActivated={false} spotlightId={spotlightId}>
      <THeader title="Debug" />
      {infos.map((item, index) => {
        return (
          <div className={css.titleArea} key={"info" + index}>
            <div className={css.titleBox}>
              <div className={css.text}>{item.title}</div>
            </div>
            <div className={css.textArea}>
              <div className={css.text}>{item.value}</div>
            </div>
          </div>
        );
      })}
      <TScroller className={css.scroller}>
        <Container className={css.settingLayer}>
          <Container className={css.titleArea}>
            <div className={css.switchs}>
              <span className={css.switchTitle}>{"Server"}</span>
              <RadioItem
                className={css.switch}
                selected={localSettings.serverType === "system"}
                onClick={onChangeServer("system")}
                disabled={localSettings.preventServerChange}
              >
                system
              </RadioItem>
              <RadioItem
                className={css.switch}
                selected={localSettings.serverType === "qt2"}
                onClick={onChangeServer("qt2")}
                disabled={localSettings.preventServerChange}
              >
                qt2
              </RadioItem>
              <RadioItem
                className={css.switch}
                selected={localSettings.serverType === "qt"}
                onClick={onChangeServer("qt")}
                disabled={localSettings.preventServerChange}
              >
                qt
              </RadioItem>

              <RadioItem
                className={css.switch}
                selected={localSettings.serverType === "st"}
                onClick={onChangeServer("st")}
                disabled={localSettings.preventServerChange}
              >
                st
              </RadioItem>
              <RadioItem
                className={css.switch}
                selected={localSettings.serverType === "prd"}
                onClick={onChangeServer("prd")}
                disabled={localSettings.preventServerChange}
              >
                prd
              </RadioItem>
            </div>
          </Container>
          <Container className={css.titleArea}>
            <div className={css.switchs}>
              <span className={css.switchTitle}>{"RicCode(Reboot)"}</span>
              <RadioItem
                className={css.switch}
                selected={localSettings.ricCodeSetting === "system"}
                onClick={onChangeServerRic("system")}
                disabled={localSettings.preventServerChange}
              >
                system
              </RadioItem>
              <RadioItem
                className={css.switch}
                selected={localSettings.ricCodeSetting === "aic"}
                onClick={onChangeServerRic("aic")}
                disabled={localSettings.preventServerChange}
              >
                aic
              </RadioItem>
              <RadioItem
                className={css.switch}
                selected={localSettings.ricCodeSetting === "eic"}
                onClick={onChangeServerRic("eic")}
                disabled={localSettings.preventServerChange}
              >
                eic
              </RadioItem>
              <RadioItem
                className={css.switch}
                selected={localSettings.ricCodeSetting === "ruc"}
                onClick={onChangeServerRic("ruc")}
                disabled={localSettings.preventServerChange}
              >
                ruc
              </RadioItem>
            </div>
          </Container>
          <Container className={css.titleArea}>
            <div className={css.switchs}>
              <span className={css.switchTitle}>{"Language"}</span>
              <RadioItem
                className={css.switch}
                selected={localSettings.languageSetting === "system"}
                onClick={onChangeLanguage("system")}
                disabled={localSettings.preventServerChange}
              >
                system
              </RadioItem>
              <RadioItem
                className={css.switch}
                selected={localSettings.languageSetting === "US"}
                onClick={onChangeLanguage("US")}
                disabled={
                  localSettings.ricCodeSetting !== "system" &&
                  localSettings.ricCodeSetting !== "aic"
                }
              >
                US
              </RadioItem>
              <RadioItem
                className={css.switch}
                selected={localSettings.languageSetting === "GB"}
                onClick={onChangeLanguage("GB")}
                disabled={
                  localSettings.ricCodeSetting !== "system" &&
                  localSettings.ricCodeSetting !== "eic"
                }
              >
                GB
              </RadioItem>
              <RadioItem
                className={css.switch}
                selected={localSettings.languageSetting === "DE"}
                onClick={onChangeLanguage("DE")}
                disabled={
                  localSettings.ricCodeSetting !== "system" &&
                  localSettings.ricCodeSetting !== "eic"
                }
              >
                DE
              </RadioItem>
              <RadioItem
                className={css.switch}
                selected={localSettings.languageSetting === "RU"}
                onClick={onChangeLanguage("RU")}
                disabled={
                  localSettings.ricCodeSetting !== "system" &&
                  localSettings.ricCodeSetting !== "ruc"
                }
              >
                RU
              </RadioItem>
            </div>
          </Container>
          {switches.map((item, index) => {
            return (
              <div className={css.titleArea} key={"switch" + index}>
                <div className={css.switchs}>
                  <span
                    className={classNames(
                      css.switchTitle,
                      item.important && css.important
                    )}
                  >
                    {item.title}
                  </span>
                  <SwitchItem
                    selected={item.value}
                    onToggle={item.func}
                    className={css.switch}
                  >
                    {item.value ? "On" : "Off"}
                  </SwitchItem>
                </div>
              </div>
            );
          })}
        </Container>
      </TScroller>
    </TPanel>
  );
}
