import { DashboardGuildGrid } from '@/components/dashboard/dashboard-guild-grid';
import { requireAuthOrRedirect } from '@/lib/auth';
import { env } from '@/lib/env';
import { getManageableGuilds } from '@/lib/guilds';
import { getLocale, t } from '@/lib/i18n';

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();

  const inviteUrls: Record<string, string> = {};
  for (const guild of guilds) {
    inviteUrls[guild.id] = buildInviteUrl(guild.id);
  }

  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>

        <DashboardGuildGrid
          guilds={guilds}
          inviteUrls={inviteUrls}
          labels={{
            empty: t(locale, 'dashboard.guildList.empty'),
            botMissing: t(locale, 'dashboard.guildList.botMissing'),
            manage: t(locale, 'dashboard.guildList.manage'),
            invite: t(locale, 'dashboard.guildList.invite')
          }}
        />
      </div>
    </main>
  );
}
