'use client';

import { 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 const MobileLanguageSelector = () => {
  const { locale } = useParams();
  const pathname = usePathname();
  const router = useRouter();

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

  const currentLanguage = languages.find((e) => e.key === locale);

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="ghost"
          size="icon"
          className="h-10 w-10 rounded-lg hover:bg-slate-100"
        >
          <div className="w-6 h-6 rounded-full overflow-hidden border-2 border-slate-200">
            <Image
              src={
                currentLanguage?.key === 'uz'
                  ? '/flags/uz.png'
                  : '/flags/ru.png'
              }
              alt={currentLanguage?.key || 'language'}
              width={24}
              height={24}
              unoptimized
              className="object-cover w-full h-full"
            />
          </div>
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        align="end"
        className="bg-white border border-slate-200 shadow-lg rounded-lg min-w-[120px]"
      >
        {languages.map((lang) => (
          <DropdownMenuItem
            key={lang.key}
            onClick={() => changeLocale(lang.key)}
            className="hover:bg-blue-50 cursor-pointer text-slate-700 hover:text-blue-700 px-3 py-2 flex items-center gap-2"
          >
            <div className="w-5 h-5 rounded-full overflow-hidden border border-slate-200">
              <Image
                src={lang.key === 'uz' ? '/flags/uz.png' : '/flags/ru.png'}
                alt={lang.key}
                width={20}
                unoptimized
                height={20}
                className="object-cover w-full h-full"
              />
            </div>
            <span className="font-medium">{lang.name}</span>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
};
