import Link from "next/link";
import { useRouter } from "next/router";
import { useSelector, useDispatch } from 'react-redux';
import { toggleDirection } from '../store/themeConfigSlice';
import { IRootState } from "../store";
import { useEffect, useState } from "react";

export default function LocaleSwitcher() {
    const router = useRouter();
    const { locales, locale: activeLocale } = router;
    const dispatch = useDispatch();
  
    const [storedLocale, setStoredLocale] = useState<string | null>(null);
  

  
    const isRtl = useSelector((state: IRootState) => state.themeConfig.direction) === 'rtl';
  
    const otherLocales = (locales || []).filter(
      (locale) => locale !== activeLocale
    );
  
    const handleLocaleChange = (locale: any) => {
      const newDirection = locale === 'ar' ||'' ? 'rtl' : 'ltr';
      dispatch(toggleDirection(newDirection));
      router.push({ pathname: router.pathname, query: router.query }, router.asPath, { locale });
      // router.push({ pathname: '/' }, router.asPath, { locale });
     
      localStorage.setItem('selectedLocale', locale);
      
    };
  
    const getLocaleDisplay = (locale: any) => {
      if (locale === 'ar') {
        return 'Arabic';
        
      } else if (locale === 'en') {
        return 'English';
      }
      return locale;
      
    };
  










  return (
    <div>
      <ul>
        {otherLocales.map((locale) => {
          return (
            <li key={locale}>
              <button
                type="button"
                onClick={() => handleLocaleChange(locale)}
              >
                {getLocaleDisplay(locale)}
              </button>
            </li>
          );
        })}
      </ul>
    </div>
  );
}
