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-20 h-10 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 after:left-1 after:bg-white  after:rounded-full after:h-8
      after:w-8 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;
