import { For, onMount, type Component, type JSX } from "solid-js";
import Scaffold from "~material/Scaffold";
import {
  AppBar,
  IconButton,
  List,
  ListItemButton,
  ListItemSecondaryAction,
  ListItemText,
  Radio,
  Toolbar,
} from "@suid/material";
import { Close as CloseIcon } from "@suid/icons-material";
import iso639_1 from "iso-639-1";
import { createTranslator } from "~platform/i18n";
import { Title } from "~material/typography";
import "./TootLangPicker.css";

type ChooseTootLangProps = {
  code: string;
  onCodeChange: (ncode: string) => void;
  onClose?: JSX.EventHandlerUnion<HTMLButtonElement, MouseEvent>;
};

const ChooseTootLang: Component<ChooseTootLangProps> = (props) => {
  let listRef: HTMLUListElement;
  const [t] = createTranslator(
    (code) =>
      import(`./i18n/${code}.json`) as Promise<{
        default: Record<string, string | undefined>;
      }>,
  );

  onMount(() => {
    const code = props.code;
    const el = listRef.querySelector(`[data-langcode="${code}"]`);
    if (el) {
      el.scrollIntoView({ behavior: "auto" });
    }
  });

  return (
    <Scaffold
      topbar={
        <AppBar position="static">
          <Toolbar
            variant="dense"
            sx={{ paddingTop: "var(--safe-area-inset-top, 0px)" }}
          >
            <IconButton color="inherit" onClick={props.onClose} disableRipple>
              <CloseIcon />
            </IconButton>
            <Title>{t("Choose Language")}</Title>
          </Toolbar>
        </AppBar>
      }
      class="TootLangPicker"
    >
      <List
        ref={listRef!}
        sx={{
          paddingBottom: "var(--safe-area-inset-bottom, 0)",
        }}
      >
        <For each={iso639_1.getAllCodes()}>
          {(code) => (
            <ListItemButton
              data-langcode={code}
              onClick={() => props.onCodeChange(code)}
            >
              <ListItemText>{iso639_1.getNativeName(code)}</ListItemText>
              <ListItemSecondaryAction>
                <Radio checked={props.code == code}></Radio>
              </ListItemSecondaryAction>
            </ListItemButton>
          )}
        </For>
      </List>
    </Scaffold>
  );
};

export default ChooseTootLang;
