import {
  children,
  createSignal,
  For,
  Show,
  type ParentComponent,
} from "solid-js";
import Scaffold from "../material/Scaffold.js";
import {
  AppBar,
  Divider,
  IconButton,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemSecondaryAction,
  ListItemText,
  ListSubheader,
  Switch,
  Toolbar,
} from "@suid/material";
import {
  Animation as AnimationIcon,
  Close as CloseIcon,
  Logout,
  Public as PublicIcon,
  Refresh as RefreshIcon,
  Translate as TranslateIcon,
} from "@suid/icons-material";
import { A, useNavigate } from "@solidjs/router";
import { Title } from "../material/typography.jsx";
import { css } from "solid-styled";
import { useSignedInProfiles } from "../masto/acct.js";
import { signOut, type Account } from "../accounts/stores.js";
import { format } from "date-fns";
import { useStore } from "@nanostores/solid";
import { $settings } from "./stores.js";
import { useRegisterSW } from "virtual:pwa-register/solid";
import {
  autoMatchLangTag,
  autoMatchRegion,
  createTranslator,
  SUPPORTED_LANGS,
  SUPPORTED_REGIONS,
  useDateFnLocale,
} from "../platform/i18n.jsx";
import { type Template } from "@solid-primitives/i18n";
import BottomSheet from "../material/BottomSheet.jsx";
import ChooseLang from "./ChooseLang.jsx";
import ChooseRegion from "./ChooseRegion.jsx";
import { Portal } from "solid-js/web";

type Strings = {
  ["lang.auto"]: Template<{ detected: string }>;
} & Record<string, string | undefined>;

const Settings: ParentComponent = (props) => {
  const [t] = createTranslator(
    (code) =>
      import(`./i18n/${code}.json`) as Promise<{
        default: Strings;
      }>,
    () => import(`./i18n/lang-names.json`),
  );
  const navigate = useNavigate();
  const settings$ = useStore($settings);
  const {
    needRefresh: [needRefresh],
  } = useRegisterSW();
  const dateFnLocale = useDateFnLocale();
  const [langPickerOpen, setLangPickerOpen] = createSignal(false);
  const [regionPickerOpen, setRegionPickerOpen] = createSignal(false);

  const [profiles] = useSignedInProfiles();

  const doSignOut = (acct: Account) => {
    signOut((a) => a.site === acct.site && a.accessToken === acct.accessToken);
  };

  const subpage = children(() => props.children);

  css`
    ul {
      padding: 0;
    }

    .setting-list {
      padding-bottom: calc(var(--safe-area-inset-bottom, 0px) + 16px);
    }
  `;
  return (
    <Scaffold
      topbar={
        <AppBar position="static">
          <Toolbar
            variant="dense"
            sx={{ paddingTop: "var(--safe-area-inset-top, 0px)" }}
          >
            <IconButton color="inherit" onClick={[navigate, -1]} disableRipple>
              <CloseIcon />
            </IconButton>
            <Title>{t("Settings")}</Title>
          </Toolbar>
        </AppBar>
      }
    >
      <BottomSheet open={!!subpage()} onClose={() => navigate(-1)}>
        {subpage()}
      </BottomSheet>

      <List class="setting-list" use:solid-styled>
        <li>
          <ul>
            <ListSubheader>{t("Accounts")}</ListSubheader>
            <ListItemButton disabled>
              <ListItemText>{t("All Notifications")}</ListItemText>
              <ListItemSecondaryAction>
                <Switch value={false} disabled />
              </ListItemSecondaryAction>
            </ListItemButton>
            <Divider />
            <ListItemButton disabled>
              <ListItemText>{t("Sign in...")}</ListItemText>
            </ListItemButton>
            <Divider />
          </ul>
          <For each={profiles()}>
            {({ account: acct, inf }) => (
              <ul data-site={acct.site} data-username={inf?.username}>
                <ListSubheader>{`@${inf?.username ?? "..."}@${new URL(acct.site).host}`}</ListSubheader>
                <ListItemButton disabled>
                  <ListItemText>{t("Notifications")}</ListItemText>
                  <ListItemSecondaryAction>
                    <Switch value={false} disabled />
                  </ListItemSecondaryAction>
                </ListItemButton>
                <Divider />
                <ListItemButton onClick={[doSignOut, acct]}>
                  <ListItemIcon>
                    <Logout />
                  </ListItemIcon>
                  <ListItemText>{t("Sign out")}</ListItemText>
                </ListItemButton>
                <Divider />
              </ul>
            )}
          </For>
        </li>
        <li>
          <ListSubheader>{t("timelines")}</ListSubheader>
          <ListItemButton
            onClick={(e) =>
              $settings.setKey(
                "prefetchTootsDisabled",
                !settings$().prefetchTootsDisabled,
              )
            }
          >
            <ListItemText secondary={t("Prefetch Toots.2nd")}>
              {t("Prefetch Toots")}
            </ListItemText>
            <ListItemSecondaryAction>
              <Switch checked={!settings$().prefetchTootsDisabled} />
            </ListItemSecondaryAction>
          </ListItemButton>
          <Divider />
          <ListItemButton component={A} href="./motions">
            <ListItemIcon>
              <AnimationIcon></AnimationIcon>
            </ListItemIcon>
            <ListItemText>{t("motions")}</ListItemText>
          </ListItemButton>
          <Divider />
        </li>
        <li>
          <ListSubheader>{t("This Application")}</ListSubheader>
          <ListItemButton onClick={[setLangPickerOpen, true]}>
            <ListItemIcon>
              <TranslateIcon />
            </ListItemIcon>
            <ListItemText
              secondary={
                settings$().language === undefined
                  ? t("lang.auto", {
                      detected:
                        t("lang." + autoMatchLangTag()) ?? autoMatchLangTag(),
                    })
                  : t("lang." + settings$().language)
              }
            >
              {t("Language")}
            </ListItemText>
          </ListItemButton>
          <BottomSheet open={langPickerOpen()}>
            <ChooseLang
              code={settings$().language}
              onCodeChange={(nval) => $settings.setKey("language", nval)}
              onClose={[setLangPickerOpen, false]}
            />
          </BottomSheet>
          <Divider />
          <ListItemButton onClick={[setRegionPickerOpen, true]}>
            <ListItemIcon>
              <PublicIcon />
            </ListItemIcon>
            <ListItemText
              secondary={
                settings$().region === undefined
                  ? t("region.auto", {
                      detected:
                        t("region." + autoMatchRegion()) ?? autoMatchRegion(),
                    })
                  : t("region." + settings$().region)
              }
            >
              {t("Region")}
            </ListItemText>
          </ListItemButton>
          <BottomSheet open={regionPickerOpen()}>
            <ChooseRegion
              code={settings$().region}
              onCodeChange={(nval) => $settings.setKey("region", nval)}
              onClose={[setRegionPickerOpen, false]}
            />
          </BottomSheet>
          <Divider />
          <ListItem>
            <ListItemText secondary={t("About Tutu.2nd")}>
              {t("About Tutu")}
            </ListItemText>
          </ListItem>
          <Divider />
          <ListItem>
            <ListItemText
              secondary={t("version", {
                packageVersion: import.meta.env.PACKAGE_VERSION,
                builtAt: format(
                  import.meta.env.BUILT_AT,
                  t("datefmt") || "yyyy/MM/dd",
                  { locale: dateFnLocale() },
                ),
                buildMode: import.meta.env.MODE,
              })}
            >
              {needRefresh() ? t("updates.ready") : t("updates.no")}
            </ListItemText>
            <Show when={needRefresh()}>
              <ListItemSecondaryAction>
                <IconButton
                  aria-label="Restart Now"
                  onClick={() => window.location.reload()}
                >
                  <RefreshIcon />
                </IconButton>
              </ListItemSecondaryAction>
            </Show>
          </ListItem>
          <Divider />
        </li>
      </List>
    </Scaffold>
  );
};

export default Settings;
