import React, {
  forwardRef,
  useImperativeHandle,
  useState,
} from 'react';

import { CheckIcon, XIcon } from 'lucide-react';

import { LangsBDEFHIJPRZEnum } from '@/api/types';
import {
  Item,
  ItemActions,
  ItemContent,
  ItemTitle,
} from '@/components/ui/item';
import {
  MobileLink,
  MobileList,
  MobileListItem,
  MobileNavbar,
  MobilePage,
  MobilePopup,
} from '@/components/ui/mobile';
import { SystemWindowDialog } from '@/components/ui/system-window-dialog';
import { Lang, useAvailableLangs, useCanChangeLang, useLang } from '@/lang/Lang';
import useAppConfigStore from '@/stores/appConfig';

export const LANGUAGES: { label: string; value: LangsBDEFHIJPRZEnum }[] = [
  { label: '🇷🇺 Русский', value: 'ru' },
  { label: '🇺🇸 English', value: 'en' },
  { label: '🇩🇪 Deutsch', value: 'de' },
  { label: '🇫🇷 Français', value: 'fr' },
  { label: '🇮🇹 Italiano', value: 'it' },
  { label: '🇪🇸 Español', value: 'es' },
  { label: '🇵🇹 Português', value: 'pt' },
  { label: '🇮🇩 Bahasa Indonesia', value: 'id' },
  { label: '🇨🇳 中文', value: 'zh' },
  { label: '🇯🇵 日本語', value: 'ja' },
];

export const changeLangDialogRef = React.createRef<ChangeLangDialogHandle>();

export type ChangeLangDialogHandle = {
  open: () => void;
  close: () => void;
};

const ChangeLangDialog = forwardRef<ChangeLangDialogHandle>((_props, ref) => {
  const [open, setOpen] = useState(false);
  const { isMobile } = useAppConfigStore();
  const currentLang = useLang();
  const canChangeLang = useCanChangeLang();
  const availableLangs = useAvailableLangs();
  const languages = LANGUAGES.filter((item) => availableLangs.includes(item.value));

  useImperativeHandle(ref, () => ({
    open: () => setOpen(true),
    close: () => setOpen(false),
  }));

  const onSelectLang = (lang: LangsBDEFHIJPRZEnum) => {
    setOpen(false);
    Lang.manualChangeLang(lang);
  };

  if (!canChangeLang) {
    return null;
  }

  if (isMobile) {
    return (
      <MobilePopup
        opened={open}
        onBackdropClick={() => setOpen(false)}
      >
        <MobilePage>
          <MobileNavbar
            title={Lang.key('change_language')}
            right={
              <MobileLink onClick={() => setOpen(false)}>
                <XIcon />
              </MobileLink>
            }
          />
          <MobileList outline>
            {languages.map((item) => (
              <MobileListItem
                key={item.value}
                title={item.label}
                link
                chevron={false}
                onClick={() => onSelectLang(item.value)}
                after={
                  currentLang === item.value ? (
                    <CheckIcon size={20} />
                  ) : undefined
                }
              />
            ))}
          </MobileList>
        </MobilePage>
      </MobilePopup>
    );
  }

  return (
    <SystemWindowDialog
      open={open}
      onOpenChange={setOpen}
      title={Lang.key('change_language')}
      width={400}
      height="auto"
      className="max-h-[calc(100vh-2rem)]"
      bodyClassName="flex-none overflow-y-auto min-h-0"
    >
      {languages.map((item) => (
        <Item
          key={item.value}
          variant="outline"
          className="cursor-pointer hover:bg-accent/50"
          onClick={() => onSelectLang(item.value)}
        >
          <ItemContent>
            <ItemTitle>{item.label}</ItemTitle>
          </ItemContent>
          {currentLang === item.value && (
            <ItemActions>
              <CheckIcon size={20} />
            </ItemActions>
          )}
        </Item>
      ))}
    </SystemWindowDialog>
  );
});

ChangeLangDialog.displayName = 'ChangeLangDialog';

export default ChangeLangDialog;
