'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 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 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}
                className="object-cover"
              />
            ) : (
              <Image
                src="/flags/ru.png"
                alt="ru"
                width={20}
                height={20}
                className="object-cover"
              />
            )}
          </div>
          <span className="text-white font-medium text-sm">
            {languages.find((e) => e.key === locale)?.name}
          </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"
          >
            {e.name}
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
