'use client';

import type { LanguageRoutes } from '@/shared/config/i18n/types';
import { Button } from '@/shared/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/shared/ui/dropdown-menu';
import { useTranslations } from 'next-intl';
import Image from 'next/image';
import { useParams, usePathname, useRouter } from 'next/navigation';
import { languages } from '../lib/data';

export function ChangeLang() {
  const { locale } = useParams();
  const pathname = usePathname();
  const router = useRouter();
  const t = useTranslations();

  const changeLocale = (locale: LanguageRoutes) => {
    const segments = pathname.split('/');
    segments[1] = locale;
    const newPath = segments.join('/');
    router.push(newPath);
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild className="h-7">
        <Button
          variant="ghost"
          className="bg-white/20 hover:bg-white/30 backdrop-blur-sm rounded-sm px-3"
        >
          <div className="w-5 h-5 rounded-full overflow-hidden border border-white/50 mr-2">
            {languages.find((e) => e.key === locale)?.key === 'uz' ? (
              <Image
                src="/flags/uz.png"
                alt="uz"
                width={20}
                height={20}
                unoptimized
                className="object-cover w-full h-full"
              />
            ) : (
              <Image
                src="/flags/ru.png"
                alt="ru"
                width={20}
                unoptimized
                height={20}
                className="object-cover w-full h-full"
              />
            )}
          </div>
          <span className="text-white font-medium text-sm">
            {t(languages.find((e) => e.key === locale)?.name ?? "O'zbekcha")}
          </span>
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        align="end"
        className="bg-white border border-slate-200 shadow-lg rounded-lg"
      >
        {languages.map((e, i) => (
          <DropdownMenuItem
            key={i}
            onClick={() => changeLocale(e.key)}
            className="hover:bg-blue-50 cursor-pointer text-slate-700 hover:text-blue-700 px-3 py-2"
          >
            {t(e.name)}
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
