import { getLocale, setLocale, useIntl } from '@umijs/max';
import { Button, Dropdown, Space } from 'antd';
import React from 'react';

export interface LanguageSwitcherProps {
  className?: string;
  type?: 'dropdown' | 'button';
  size?: 'small' | 'middle' | 'large';
}

const LanguageSwitcher: React.FC<LanguageSwitcherProps> = ({
  className,
  type = 'dropdown',
  size = 'middle',
}) => {
  const intl = useIntl();

  const languageItems = [
    {
      key: 'vi-VN',
      label: intl.formatMessage({ id: 'common.vietnamese' }),
      flag: '🇻🇳',
    },
    {
      key: 'en-US',
      label: intl.formatMessage({ id: 'common.english' }),
      flag: '🇺🇸',
    },
  ];

  const handleLanguageChange = (locale: string) => {
    setLocale(locale, false);
  };

  const getCurrentLanguage = () => {
    const currentLocale = intl.locale || getLocale() || 'vi-VN';
    return (
      languageItems.find((item) => item.key === currentLocale) ||
      languageItems[0]
    );
  };

  const dropdownItems = languageItems.map((item) => ({
    key: item.key,
    label: (
      <Space>
        <span>{item.flag}</span>
        <span>{item.label}</span>
      </Space>
    ),
    onClick: () => handleLanguageChange(item.key),
  }));

  if (type === 'button') {
    const currentLang = getCurrentLanguage();

    return (
      <Button
        size={size}
        onClick={() => {
          const nextLocale = currentLang.key === 'vi-VN' ? 'en-US' : 'vi-VN';
          handleLanguageChange(nextLocale);
        }}
        className={className}
      >
        <Space>
          <span>{currentLang.flag}</span>
          <span>{currentLang.label}</span>
        </Space>
      </Button>
    );
  }

  const currentLang = getCurrentLanguage();

  return (
    <Dropdown
      menu={{ items: dropdownItems }}
      placement="bottomRight"
      trigger={['click']}
      className={className}
    >
      <Button size={size} type="text">
        <Space>
          <span>{currentLang.flag}</span>
          <span>{currentLang.label}</span>
        </Space>
      </Button>
    </Dropdown>
  );
};

export default LanguageSwitcher;
