import { createMemo, For, type Component, type JSX } from "solid-js";
import Scaffold from "../material/Scaffold";
import {
  AppBar,
  IconButton,
  List,
  ListItem,
  ListItemButton,
  ListItemSecondaryAction,
  ListItemText,
  ListSubheader,
  Radio,
  Switch,
  Toolbar,
} from "@suid/material";
import { ArrowBack } from "@suid/icons-material";
import iso639_1 from "iso-639-1";
import {
  autoMatchLangTag,
  createTranslator,
  SUPPORTED_LANGS,
} from "../platform/i18n";
import { Title } from "../material/typography";
import type { Template } from "@solid-primitives/i18n";
import { useStore } from "@nanostores/solid";
import { $settings } from "./stores";
import { useNavigate } from "@solidjs/router";

const ChooseLang: Component = () => {
  const navigate = useNavigate()
  const [t] = createTranslator(
    () => import("./i18n/lang-names.json"),
    (code) =>
      import(`./i18n/${code}.json`) as Promise<{
        default: Record<string, string | undefined> & {
          ["lang.auto"]: Template<{ detected: string }>;
        };
      }>,
  );
  const settings = useStore($settings)

  const code = () => settings().language

  const unsupportedLangCodes = createMemo(() => {
    return iso639_1.getAllCodes().filter((x) => !["zh", "en"].includes(x));
  });

  const matchedLangCode = createMemo(() => autoMatchLangTag());

  const onCodeChange = (code?: string) => {
    $settings.setKey("language", code)
  }

  return (
    <Scaffold
      topbar={
        <AppBar position="static">
          <Toolbar
            variant="dense"
            sx={{ paddingTop: "var(--safe-area-inset-top, 0px)" }}
          >
            <IconButton color="inherit" onClick={[navigate, -1]} disableRipple>
              <ArrowBack />
            </IconButton>
            <Title>{t("Choose Language")}</Title>
          </Toolbar>
        </AppBar>
      }
    >
      <List
        sx={{
          paddingBottom: "var(--safe-area-inset-bottom, 0)",
        }}
      >
        <ListItemButton
          onClick={() => {
            onCodeChange(code() ? undefined : matchedLangCode());
          }}
        >
          <ListItemText>
            {t("lang.auto", {
              detected: t(`lang.${matchedLangCode()}`) ?? matchedLangCode(),
            })}
          </ListItemText>
          <ListItemSecondaryAction>
            <Switch checked={typeof code() === "undefined"} />
          </ListItemSecondaryAction>
        </ListItemButton>
        <List subheader={<ListSubheader>{t("Supported")}</ListSubheader>}>
          <For each={SUPPORTED_LANGS}>
            {(c) => (
              <ListItemButton
                disabled={typeof code() === "undefined"}
                onClick={[onCodeChange, c]}
              >
                <ListItemText>{t(`lang.${c}`)}</ListItemText>
                <ListItemSecondaryAction>
                  <Radio
                    checked={code() === c || (code() === undefined && matchedLangCode() == c)}
                  />
                </ListItemSecondaryAction>
              </ListItemButton>
            )}
          </For>
        </List>

        <List subheader={<ListSubheader>{t("Unsupported")}</ListSubheader>}>
          <For each={unsupportedLangCodes()}>
            {(code) => (
              <ListItem>
                <ListItemText>{iso639_1.getNativeName(code)}</ListItemText>
              </ListItem>
            )}
          </For>
        </List>
      </List>
    </Scaffold>
  );
};

export default ChooseLang;
