import type { MenuProps } from "antd";
import { Avatar, Dropdown } from "antd";

import { setLocalesThunk } from "features/locale/localeSlice";
import { LOCALES } from "i18n/helper";
import { useCallback, useEffect, useMemo, useState } from "react";

import i18n from "i18n/i18n";
import { useAppDispatch } from "redux/hooks";
import { DEFAULT_LANGUAGE } from "utils/constants";
import "./LangSelect.css";

type Locale = {
  id: string;
  title: string;
  iconPath: string;
};

export default function LangSelect() {
  const dispatch = useAppDispatch();

  const [currentLanguage, setCurrentLanguage] = useState<Locale>(LOCALES[0]);

  useEffect(() => {
    const selectedLocale = LOCALES.find(
      (item) => item.id === localStorage.getItem(DEFAULT_LANGUAGE)
    );
    if (selectedLocale && selectedLocale.id !== currentLanguage.id)
      setCurrentLanguage(selectedLocale);
  }, [currentLanguage?.id]);

  const changeLocale = useCallback(
    (key: string) => {
      dispatch(setLocalesThunk(key));
      setCurrentLanguage(LOCALES.find((item) => item.id === key) || LOCALES[0]);
      i18n.changeLanguage(key);
    },
    [dispatch]
  );

  const items: MenuProps["items"] = useMemo(
    () =>
      LOCALES.map((_locale) => ({
        className: "lang-item",
        key: _locale.id,
        icon: (
          <span>
            <Avatar className="avatar"  src={_locale.iconPath} />
          </span>
        ),
        label: _locale.title,
      })),
    []
  );

  return (
    <Dropdown
      menu={{
        items,
        onClick: ({ key }) => {
          changeLocale(key as string);
        },
      }}
      overlayClassName="lang-dropdown-container"
    >
      <Avatar
        style={{
          position: "relative",
          top: 25,
          borderRadius: "35%",
          width: 30,
          height: 30,
        }}
        
        src={currentLanguage?.iconPath}
      />
    </Dropdown>
  );
}
