
import type { MenuProps } from "antd";
import { Avatar, Dropdown } from "antd";

import { useMemo } from "react";

import { usePathname, useRouter, useSearchParams } from "next/navigation";
import "./LangSelect.css";

type Locale = {
  id: string;
  title: string;
  iconPath: string;
};

export const LOCALES: Locale[] = [
  { id: "ar", title: "العربية", iconPath: "/saudi-arabia.svg" },
  { id: "en", title: "English", iconPath: "/america.svg" },
];

export default function LangSelect() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const items: MenuProps["items"] = useMemo(
    () =>
      LOCALES.map((_locale) => ({
        className: "lang-item",
        key: _locale.id,
        icon: (
          <span>
            <Avatar className="avatar" src={_locale.iconPath} />
          </span>
        ),
        label: _locale.title,
      })),
    []
  );

  return (
    <Dropdown
      menu={{
        items,
        onClick: ({ key }) => {
          router.push(
            pathname
              .split("/")
              .map((item, index) => {
                if (index === 1) {
                  return key;
                }
                return item;
              })
              .join("/") +
              (searchParams.toString() ? `?${searchParams.toString()}` : "")
          );
        },
      }}
      overlayClassName="lang-dropdown-container"
    >
      <Avatar
        style={{
          position: "relative",
          top: 1,
          borderRadius: "35%",
          width: 30,
          height: 30,
        }}
        src={LOCALES[0]?.iconPath}
      />
    </Dropdown>
  );
}
