import React, { useState } from 'react';
import { Avatar, Dropdown, Spinner } from '@/components/ui';
import classNames from 'classnames';
import withHeaderItem from '@/utils/hoc/withHeaderItem';
import { useSelector, useDispatch } from 'react-redux';
import { setLang } from '@/store/locale/localeSlice';
import { dateLocales } from '@/locales';
import dayjs from 'dayjs';
import i18n, { t } from 'i18next';

import { HiCheck } from 'react-icons/hi';
import { BiWorld } from 'react-icons/bi';
import useDirection from '@/utils/hooks/useDirection';

import { THEME_ENUM } from '@/constants/theme.constant';

const languageList = [
  { label: 'English', value: 'en', flag: 'us' },
  { label: 'العربية', value: 'ar', flag: 'ar' },
];

export const LanguageSelector = ({ className }) => {
  const [loading, setLoading] = useState(false);

  const locale = useSelector((state) => state.locale.currentLang);
  const dispatch = useDispatch();

  /* A@N change directions */
  // eslint-disable-next-line no-unused-vars
  const [direction, updateDirection] = useDirection();

  const selectedLanguage = (
    <div className={classNames(className, 'flex items-center')}>
      {loading ? (
        <Spinner size={20} />
      ) : (
        <BiWorld className="bg-transparent  " size={26} shape="circle" alt="lang" title={t('CHANGE_LANGAUGE')} />
      )}
    </div>
  );
  const onDirSelect = (val) => {
    updateDirection(val === 'ar' ? THEME_ENUM.DIR_RTL : THEME_ENUM.DIR_LTR);
    //dispatch(setDirection(val === 'ar' ? THEME_ENUM.DIR_RTL : THEME_ENUM.DIR_LTR));
  };

  const onLanguageSelect = (lang) => {
    onDirSelect(lang);
    const formattedLang = lang.replace(/-([a-z])/g, function (g) {
      i18n.changeLanguage(lang);

      return g[1].toUpperCase();
    });

    setLoading(true);

    const dispatchLang = () => {
      i18n.changeLanguage(formattedLang);
      dispatch(setLang(lang));

      setLoading(false);
    };

    dateLocales[formattedLang]()
      .then(() => {
        dayjs.locale(formattedLang);

        dispatchLang();
      })
      .catch((_) => {
        dispatchLang();
      });
  };

  return (
    <Dropdown renderTitle={selectedLanguage} placement="bottom-end">
      {languageList.map((lang) => (
        <Dropdown.Item
          className="mb-1 justify-between"
          eventKey={lang.label}
          key={lang.label}
          onClick={() => {
            onLanguageSelect(lang.value);
          }}
        >
          <span className="flex items-center">
            <Avatar size={18} shape="circle" src={`/img/countries/${lang.flag}.png`} />
            <span className="ltr:ml-2 rtl:mr-2">{lang.label}</span>
          </span>
          {locale === lang.value && <HiCheck className="text-emerald-500 text-lg" />}
        </Dropdown.Item>
      ))}
    </Dropdown>
  );
};

export default withHeaderItem(LanguageSelector);
