import type { DashboardGuild } from '@nexumi/shared';
import Link from 'next/link';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { requireAuthOrRedirect } from '@/lib/auth';
import { env } from '@/lib/env';
import { getManageableGuilds } from '@/lib/guilds';
import { getLocale, t } from '@/lib/i18n';

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('') || '?'
  );
}

function buildInviteUrl(guildId: string): string {
  const url = new URL('https://discord.com/api/oauth2/authorize');
  url.searchParams.set('client_id', env.BOT_CLIENT_ID);
  url.searchParams.set('permissions', '4786708802825463');
  url.searchParams.set('scope', 'bot applications.commands');
  url.searchParams.set('guild_id', guildId);
  return url.toString();
}

export default async function DashboardGuildListPage() {
  const session = await requireAuthOrRedirect();
  const guilds = await getManageableGuilds(session);
  const locale = await getLocale();

  return (
    <main className="flex min-h-screen justify-center px-6 py-10">
      <div className="w-full max-w-[1200px] space-y-6">
        <div>
          <h1 className="text-2xl font-semibold">{t(locale, 'dashboard.guildList.title')}</h1>
          <p className="text-sm text-muted-foreground">{t(locale, 'dashboard.guildList.subtitle')}</p>
        </div>

        {guilds.length === 0 ? (
          <Card>
            <CardContent className="py-10 text-center text-sm text-muted-foreground">
              {t(locale, 'dashboard.guildList.empty')}
            </CardContent>
          </Card>
        ) : (
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {guilds.map((guild) => (
              <Card key={guild.id}>
                <CardContent className="flex flex-col gap-4 p-5">
                  <div className="flex items-center gap-3">
                    <Avatar className="size-10">
                      <AvatarImage src={guildIconUrl(guild)} alt={guild.name} />
                      <AvatarFallback>{initials(guild.name)}</AvatarFallback>
                    </Avatar>
                    <div className="min-w-0">
                      <p className="truncate font-medium">{guild.name}</p>
                      {!guild.botPresent && (
                        <Badge variant="outline" className="mt-1">
                          {t(locale, 'dashboard.guildList.botMissing')}
                        </Badge>
                      )}
                    </div>
                  </div>
                  {guild.botPresent ? (
                    <Button asChild>
                      <Link href={`/dashboard/${guild.id}`}>{t(locale, 'dashboard.guildList.manage')}</Link>
                    </Button>
                  ) : (
                    <Button asChild variant="outline">
                      <a href={buildInviteUrl(guild.id)} target="_blank" rel="noreferrer">
                        {t(locale, 'dashboard.guildList.invite')}
                      </a>
                    </Button>
                  )}
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>
    </main>
  );
}
