'use client';

import { useLocale } from 'next-intl';
import { useTranslations } from 'next-intl';
import { useRouter, usePathname } from '@/i18n/routing';
import { cn } from "@/lib/utils";
import { useTransition } from 'react';
import Image from 'next/image';

type LanguageSwitcherProps = {
  className?: string;
  size?: "default" | "compact";
};

export function LanguageSwitcher({
  className,
  size = "default",
}: LanguageSwitcherProps) {
  const tCommon = useTranslations("common");
  const locale = useLocale();
  const router = useRouter();
  const pathname = usePathname();
  const [isPending, startTransition] = useTransition();

  const switchLocale = (newLocale: 'ar' | 'en') => {
    startTransition(() => {
      router.replace(pathname, { locale: newLocale });
    });
  };

  return (
    <button
      onClick={() => switchLocale(locale === 'ar' ? 'en' : 'ar')}
      disabled={isPending}
      className={cn(
        "inline-flex shrink-0 items-center justify-center rounded-lg bg-white/16 transition-colors hover:bg-white/20 disabled:cursor-not-allowed disabled:opacity-50",
        size === "compact"
          ? "h-8 gap-2 p-2"
          : "h-10 gap-2.5 px-2.5 py-2",
        className
      )}
      aria-label={locale === 'ar' ? tCommon("switchToEnglish") : tCommon("switchToArabic")}
    >
      <div className={cn("relative shrink-0 size-6")}>
        <Image
          src="/images/login/icons/global.svg"
          alt=""
          width={24}
          height={24}
          className="size-full brightness-0 invert"
        />
      </div>
      <p
        className={cn(
          "font-medium text-white",
          size === "compact" ? "text-[14px] leading-normal" : "text-sm leading-none"
        )}
      >
        {locale === 'ar' ? tCommon("en") : tCommon("arShort")}
      </p>
    </button>
  );
}
