'use client';

import { useRouter } from 'next/navigation';
import { usePathname } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import i18nConfig from '@/i18nConfig';
import { ChangeEvent, useState } from 'react';
import { Select, Space } from 'antd';
import { LanguageAIItem } from './TranslationsProvider';

export default function LanguageChanger() {
  const { i18n } = useTranslation();
  const currentLocale = i18n.language;
  const router = useRouter();
  const currentPathname = usePathname();



  // const handleChange = (e: ChangeEvent<HTMLSelectElement>) => {
  // const newLocale = e.target.value;
  const handleChange = (value: string) => {
    const newLocale = value

    // set cookie for next-i18n-router
    const days = 30;
    const date = new Date();
    date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = `NEXT_LOCALE=${newLocale};expires=${date.toUTCString()};path=/`;

    // redirect to the new locale path
    if (
      currentLocale === i18nConfig.defaultLocale &&
      !i18nConfig.prefixDefault
    ) {
      router.push('/' + newLocale + currentPathname);
    } else {
      router.push(
        currentPathname.replace(`/${currentLocale}`, `/${newLocale}`)
      );
    }

    localStorage.setItem(LanguageAIItem, newLocale)

    router.refresh();
  };

  return (
    // <select onChange={handleChange} value={currentLocale}>
    //   <option value="en">English</option>
    //   <option value="zh-CN">简体中文</option>
    // </select>

    <Space wrap>
      <Select
        defaultValue={currentLocale}
        style={{ width: 120 }}
        onChange={handleChange}
        options={[
          { value: 'en', label: 'English' },
          { value: 'zh-CN', label: '简体中文' },
          // { value: 'disabled', label: 'Disabled', disabled: true },
        ]}
      />

    </Space>
  );
}
