'use client';

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

export function LanguageSwitcher() {
  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="bg-white/16 flex gap-2 h-8 items-center justify-center px-2 py-2 rounded-lg shrink-0 hover:bg-white/20 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
      aria-label={locale === 'ar' ? tCommon("switchToEnglish") : tCommon("switchToArabic")}
    >
      <div className="relative shrink-0 size-4">
        <Image
          src="/images/login/icons/global.svg"
          alt=""
          width={16}
          height={16}
          className="size-full brightness-0 invert"
        />
      </div>
      <p className="font-medium leading-normal text-sm text-white">
        {locale === 'ar' ? tCommon("en") : tCommon("arShort")}
      </p>
    </button>
  );
}
