import { getLocale, setLocale } from '@umijs/max';
import { useEffect, useState } from 'react';

const LangSwitches = () => {
  const [isEnglish, setIsEnglish] = useState(false);

  // Keep checkbox in sync with current Umi locale without forcing a reload
  useEffect(() => {
    const syncLocale = () => setIsEnglish(getLocale() === 'en-US');

    syncLocale();
    window.addEventListener('languagechange', syncLocale);

    return () => {
      window.removeEventListener('languagechange', syncLocale);
    };
  }, []);

  const handleLanguageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newLocale = e.target.checked ? 'en-US' : 'vi-VN';
    setIsEnglish(e.target.checked);
    setLocale(newLocale, false); // Update locale instantly without full page reload
  };

  return (
    <label className="relative inline-flex items-center cursor-pointer">
      <input
        className="sr-only peer"
        type="checkbox"
        checked={isEnglish}
        onChange={handleLanguageChange}
      />
      <div
        className="w-[70px] h-9 rounded-full bg-gradient-to-r from-orange-400 to-red-400 peer-checked:from-blue-400 peer-checked:to-indigo-500 
      transition-all duration-500 after:content-['🇻🇳'] after:absolute after:top-1 peer-checked:left-0 after:left-1 peer-checked:after:left-[-8px] after:bg-white after:rounded-full after:h-7
      after:w-7 after:flex after:items-center after:justify-center after:transition-all after:duration-500 peer-checked:after:translate-x-10
      peer-checked:after:content-['🏴󠁧󠁢󠁥󠁮󠁧󠁿'] after:shadow-md after:text-2xl"
      ></div>
    </label>
  );
};

export default LangSwitches;
