'use client';

import type { DashboardGuild } from '@nexumi/shared';
import { ChevronsUpDown, LayoutGrid } from 'lucide-react';
import Link from 'next/link';
import { useTranslations } from '@/components/locale-provider';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';

function guildIconUrl(guild: Pick<DashboardGuild, 'id' | 'icon'>): string | undefined {
  return guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.png?size=64` : undefined;
}

function initials(name: string): string {
  return name
    .split(' ')
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase())
    .join('');
}

interface ServerSwitcherProps {
  currentGuild: DashboardGuild;
  otherGuilds: DashboardGuild[];
}

export function ServerSwitcher({ currentGuild, otherGuilds }: ServerSwitcherProps) {
  const t = useTranslations();
  const botGuilds = otherGuilds.filter((guild) => guild.botPresent);

  return (
    <DropdownMenu>
      <DropdownMenuTrigger className="flex items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium outline-none hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring">
        <Avatar className="size-7">
          <AvatarImage src={guildIconUrl(currentGuild)} alt={currentGuild.name} />
          <AvatarFallback>{initials(currentGuild.name)}</AvatarFallback>
        </Avatar>
        <span className="max-w-40 truncate">{currentGuild.name}</span>
        <ChevronsUpDown className="size-4 text-muted-foreground" />
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="w-64">
        <DropdownMenuLabel>{t('serverSwitcher.switchServer')}</DropdownMenuLabel>
        <DropdownMenuSeparator />
        {botGuilds.length === 0 ? (
          <p className="px-2 py-1.5 text-sm text-muted-foreground">{t('serverSwitcher.noOtherServers')}</p>
        ) : (
          botGuilds.map((guild) => (
            <DropdownMenuItem key={guild.id} asChild>
              <Link href={`/dashboard/${guild.id}`} className="flex items-center gap-2">
                <Avatar className="size-6">
                  <AvatarImage src={guildIconUrl(guild)} alt={guild.name} />
                  <AvatarFallback>{initials(guild.name)}</AvatarFallback>
                </Avatar>
                <span className="truncate">{guild.name}</span>
              </Link>
            </DropdownMenuItem>
          ))
        )}
        <DropdownMenuSeparator />
        <DropdownMenuItem asChild>
          <Link href="/dashboard" className="flex items-center gap-2">
            <LayoutGrid className="size-4" />
            {t('serverSwitcher.allServers')}
          </Link>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
