import { useEffect, useRef, useState } from "react";
import { useBackLayer } from "../../app/useBackLayer.js";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { useTheme } from "../../shared/ThemeProvider.jsx";
import { useOutsideDismiss } from "../../shared/hooks/useOutsideDismiss.js";
import { AccountManagementPage } from "../accounts/AccountManagementPage.jsx";
import { readSavedServerOrigin } from "../../api-base.js";
import { platformRuntime } from "../../platform/runtime.js";
import { disconnectPcConnection, requestPcConnectionChange } from "../connection/connection-mode.js";
import { fetchPcStatus } from "../connection/pc-status.js";
import { UsageSettingsPage } from "../status/UsageSettingsPage.jsx";
import { NotificationSettingsPage } from "../notifications/NotificationSettingsPage.jsx";
import { ActionDialog } from "../../shared/ActionDialog.jsx";
import { resetThisDeviceData } from "./device-data-reset.js";
import { PcDataResetDialog } from "./PcDataResetDialog.jsx";
import { AccountsSettingsIcon, BackIcon, ChatsSettingsIcon, DeviceResetIcon, ForwardIcon, LanguageSettingsIcon, NotificationsSettingsIcon, PcDataResetIcon, ThemeSettingsIcon } from "../../shared/ActionIcons.jsx";
import { LegalSupportSection } from "./LegalSupportSection.jsx";

export function SettingsWindow({ accounts = [], accountMosaic = false, conversationAccountVisible = true, manager, pro, onAccountMosaicChange = () => {}, onConversationAccountVisibleChange = () => {}, onArchivedOpen, onBack }) {
  const { language, setLanguage, t } = useI18n();
  const { theme, setTheme } = useTheme();
  const [languageMenuOpen, setLanguageMenuOpen] = useState(false);
  const [themeMenuOpen, setThemeMenuOpen] = useState(false);
  const [accountManagementOpen, setAccountManagementOpen] = useState(false);
  const [usageOpen, setUsageOpen] = useState(false);
  const [notificationsOpen, setNotificationsOpen] = useState(false);
  const [deviceResetOpen, setDeviceResetOpen] = useState(false);
  const [deviceResetPending, setDeviceResetPending] = useState(false);
  const [deviceResetError, setDeviceResetError] = useState("");
  const [pcDataResetOpen, setPcDataResetOpen] = useState(false);
  const savedPcOrigin = platformRuntime.isNative ? readSavedServerOrigin() : "";
  const [pcStatus, setPcStatus] = useState({ state: "checking", name: "", checkedAt: null });
  const languageMenuRef = useRef(null);
  const themeMenuRef = useRef(null);
  const closeLanguageMenu = useBackLayer(languageMenuOpen, () => setLanguageMenuOpen(false), "settings-language-menu");
  const closeThemeMenu = useBackLayer(themeMenuOpen, () => setThemeMenuOpen(false), "settings-theme-menu");
  const closeAccountManagement = useBackLayer(accountManagementOpen, () => setAccountManagementOpen(false), "settings-account-management");
  const closeUsage = useBackLayer(usageOpen, () => setUsageOpen(false), "settings-usage");
  const closeNotifications = useBackLayer(notificationsOpen, () => setNotificationsOpen(false), "settings-notifications");
  useOutsideDismiss(languageMenuRef, () => setLanguageMenuOpen(false), languageMenuOpen);
  useOutsideDismiss(themeMenuRef, () => setThemeMenuOpen(false), themeMenuOpen);
  useEffect(() => {
    if (!savedPcOrigin) return;
    let active = true;
    fetchPcStatus(savedPcOrigin).then((status) => { if (active) setPcStatus(status); });
    return () => { active = false; };
  }, [savedPcOrigin]);
  // A choice is an in-place settings update, not a navigation action.  Closing
  // the menu locally avoids consuming the settings screen's history layer.
  function selectLanguage(nextLanguage) { setLanguage(nextLanguage); setLanguageMenuOpen(false); }
  function selectTheme(nextTheme) { setTheme(nextTheme); setThemeMenuOpen(false); }
  function changePc() {
    requestPcConnectionChange();
    globalThis.location.reload();
  }
  function removePc() {
    if (!globalThis.confirm(t("settings.removePcConfirm"))) return;
    disconnectPcConnection();
    globalThis.location.reload();
  }
  async function confirmDeviceReset() {
    if (deviceResetPending) return;
    setDeviceResetPending(true);
    setDeviceResetError("");
    try {
      await resetThisDeviceData();
      globalThis.location.reload();
    } catch (error) {
      setDeviceResetError(error?.message === "device_reset_incomplete" ? "settings.resetThisDeviceIncomplete" : "settings.resetThisDeviceFailed");
      setDeviceResetPending(false);
    }
  }
  function closeDeviceReset() {
    if (deviceResetPending) return;
    setDeviceResetOpen(false);
    setDeviceResetError("");
  }

  if (usageOpen) return <UsageSettingsPage accounts={accounts} accountMosaic={accountMosaic} onBack={closeUsage} />;
  if (accountManagementOpen) return <AccountManagementPage accounts={accounts} manager={manager} pro={pro} accountMosaic={accountMosaic} conversationAccountVisible={conversationAccountVisible} onAccountMosaicChange={onAccountMosaicChange} onConversationAccountVisibleChange={onConversationAccountVisibleChange} onUsageOpen={() => setUsageOpen(true)} onBack={closeAccountManagement} />;
  if (notificationsOpen) return <NotificationSettingsPage onBack={closeNotifications} />;

  return <section className="settings-page" aria-labelledby="settings-title">
    <button type="button" className="screen-back conversation-back" aria-label={t("settings.back")} onClick={onBack}><BackIcon /></button>
    <div className="settings-content">
      <h1 id="settings-title" className="settings-prompt">{t("settings.title")}</h1>
      <section className="settings-section" aria-labelledby="settings-accounts-title"><h2 id="settings-accounts-title">{t("settings.accounts")}</h2><button className="settings-action settings-navigation-action" type="button" onClick={() => setAccountManagementOpen(true)}><AccountsSettingsIcon className="settings-row-icon" /><span>{t("settings.accountManagement")}</span><ForwardIcon className="settings-navigation-chevron" /></button></section>
      <section className="settings-section" aria-labelledby="settings-chats-title"><h2 id="settings-chats-title">{t("settings.chats")}</h2><button className="settings-action settings-navigation-action" type="button" onClick={onArchivedOpen}><ChatsSettingsIcon className="settings-row-icon" /><span>{t("settings.archivedChats")}</span><ForwardIcon className="settings-navigation-chevron" /></button></section>
      <section className="settings-section" aria-labelledby="settings-notifications-title"><h2 id="settings-notifications-title">{t("settings.notifications")}</h2><button className="settings-action settings-navigation-action" type="button" onClick={() => setNotificationsOpen(true)}><NotificationsSettingsIcon className="settings-row-icon" /><span>{t("settings.manageNotifications")}</span><ForwardIcon className="settings-navigation-chevron" /></button></section>
      {platformRuntime.isNative && <section className="settings-section" aria-labelledby="settings-connection-title">
        <h2 id="settings-connection-title">{t("settings.pcManagement")}</h2>
        <div className="settings-connection">
          <strong>{pcStatus.name || t("settings.pcDefaultName")}</strong>
          <span className={`settings-pc-status ${pcStatus.state}`}>
            {pcStatus.state === "checking" ? t("settings.pcChecking") : pcStatus.state === "online" ? t("settings.pcOnline") : t("settings.pcOffline")}
          </span>
          {pcStatus.checkedAt && <span>{t("settings.pcLastChecked", { time: new Intl.DateTimeFormat(language, { hour: "2-digit", minute: "2-digit" }).format(pcStatus.checkedAt) })}</span>}
          <span>{savedPcOrigin}</span>
          <button type="button" onClick={changePc}>{t("settings.changePc")}</button>
          <button className="settings-remove-pc" type="button" onClick={removePc}>{t("settings.removePc")}</button>
        </div>
      </section>}
      <section className="settings-section" aria-labelledby="settings-appearance-title">
        <h2 id="settings-appearance-title">{t("settings.appearance")}</h2>
        <div className="settings-choice"><span className="settings-choice-label"><LanguageSettingsIcon className="settings-row-icon" /><span>Language</span></span><span className="settings-language-picker" ref={languageMenuRef}>
          <select className="settings-select settings-language-native" value={language} onChange={(event) => selectLanguage(event.target.value)} aria-label="Language"><option value="en">English</option><option value="ko">Korean</option></select>
          <button className="settings-language-trigger" type="button" aria-label="Language" aria-expanded={languageMenuOpen} onClick={() => languageMenuOpen ? closeLanguageMenu() : setLanguageMenuOpen(true)}><span>{language === "ko" ? "Korean" : "English"}</span><ForwardIcon className="settings-choice-chevron" /></button>
          {languageMenuOpen && <span className="settings-language-menu" role="menu"><button type="button" role="menuitemradio" aria-checked={language === "ko"} className={language === "ko" ? "active" : ""} onClick={() => selectLanguage("ko")}>Korean</button><button type="button" role="menuitemradio" aria-checked={language === "en"} className={language === "en" ? "active" : ""} onClick={() => selectLanguage("en")}>English</button></span>}
        </span></div>
        <div className="settings-choice"><span className="settings-choice-label"><ThemeSettingsIcon className="settings-row-icon" /><span>{t("settings.theme")}</span></span><span className="settings-theme-picker" ref={themeMenuRef}>
          <select className="settings-select settings-theme-native" value={theme} onChange={(event) => selectTheme(event.target.value)} aria-label={t("settings.theme")}><option value="system">{t("settings.systemTheme")}</option><option value="dark">{t("settings.dark")}</option><option value="light">{t("settings.light")}</option></select>
          <button className="settings-theme-trigger" type="button" aria-label={t("settings.theme")} aria-expanded={themeMenuOpen} onClick={() => themeMenuOpen ? closeThemeMenu() : setThemeMenuOpen(true)}><span>{theme === "system" ? t("settings.systemTheme") : theme === "dark" ? t("settings.dark") : t("settings.light")}</span><ForwardIcon className="settings-choice-chevron" /></button>
          {themeMenuOpen && <span className="settings-theme-menu" role="menu"><button type="button" role="menuitemradio" aria-checked={theme === "system"} className={theme === "system" ? "active" : ""} onClick={() => selectTheme("system")}>{t("settings.systemTheme")}</button><button type="button" role="menuitemradio" aria-checked={theme === "dark"} className={theme === "dark" ? "active" : ""} onClick={() => selectTheme("dark")}>{t("settings.dark")}</button><button type="button" role="menuitemradio" aria-checked={theme === "light"} className={theme === "light" ? "active" : ""} onClick={() => selectTheme("light")}>{t("settings.light")}</button></span>}
        </span></div>
      </section>
      <section className="settings-section settings-data-reset" aria-labelledby="settings-data-reset-title">
        <h2 id="settings-data-reset-title">{t("settings.dataReset")}</h2>
        <button className={`settings-action settings-reset-device settings-device-data${platformRuntime.isNative ? " native" : ""}`} type="button" onClick={() => setDeviceResetOpen(true)}><DeviceResetIcon className="settings-row-icon" /><span>{t("settings.resetThisDevice")}</span></button>
        <button className="settings-action settings-reset-device" type="button" onClick={() => setPcDataResetOpen(true)}><PcDataResetIcon className="settings-row-icon" /><span>{t("settings.resetPcData")}</span></button>
      </section>
      <LegalSupportSection />
    </div>
    <ActionDialog open={deviceResetOpen} title={t("settings.resetThisDeviceTitle")} description={t("settings.resetThisDeviceDescription")} cancelLabel={t("dialog.cancel")} confirmLabel={t("settings.resetThisDeviceConfirm")} pendingLabel={t("settings.resettingThisDevice")} pending={deviceResetPending} tone="danger" onCancel={closeDeviceReset} onConfirm={confirmDeviceReset}>
      <div className="action-dialog-content">
        <strong>{t("settings.resetDeletesTitle")}</strong>
        <ul><li>{t("settings.resetDeletesConnection")}</li><li>{t("settings.resetDeletesSelections")}</li><li>{t("settings.resetDeletesPreferences")}</li><li>{t("settings.resetDeletesTemporary")}</li></ul>
        <strong>{t("settings.resetKeepsTitle")}</strong>
        <ul><li>{t("settings.resetKeepsPcData")}</li><li>{t("settings.resetKeepsAccounts")}</li></ul>
        {deviceResetError && <p className="action-dialog-error" role="alert">{t(deviceResetError)}</p>}
      </div>
    </ActionDialog>
    <PcDataResetDialog open={pcDataResetOpen} onClose={() => setPcDataResetOpen(false)} />
  </section>;
}
