/**
 * ╔══════════════════════════════════════════════════════════════════╗
 * ║                                                                  ║
 * ║                        +-+-+-+-+-+-+-+-+                         ║
 * ║                        |H|e|x|a|H|o|s|t|                         ║
 * ║                        +-+-+-+-+-+-+-+-+                         ║
 * ║                                                                  ║
 * ║              © 2026 HexaHost — All Rights Reserved               ║
 * ║                                                                  ║
 * ║             discord  ──  https://discord.gg/hexahost             ║
 * ║        github   ──  https://github.com/theoneandonlymace         ║
 * ║                                                                  ║
 * ╚══════════════════════════════════════════════════════════════════╝
 */
import React from "react";
import Image from "next/image";
import Link from "next/link";
import { Users, ShieldCheck, ChevronRight, Hash, Plus, ExternalLink } from "lucide-react";
import { api } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { getBotInviteUrl } from "@/lib/discord-invite";

import { GuildSummary } from "@/types/api";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth";
import { redirect } from "next/navigation";

export const dynamic = "force-dynamic";
export const revalidate = 0;

function AddBotButton({ className }: { className?: string }) {
  return (
    <Button className={className} asChild>
      <a href="/api/invite" target="_blank" rel="noopener noreferrer">
        <Plus className="h-4 w-4 mr-2" />
        Add Bot to your Server
        <ExternalLink className="h-3.5 w-3.5 ml-2 opacity-60" />
      </a>
    </Button>
  );
}

export default async function GuildsPage() {
  const session = await getServerSession(authOptions);

  if (!session || !session.accessToken) {
    redirect("/");
  }

  if (session.error === "RefreshAccessTokenError" || session.error === "RefreshTokenMissing") {
    redirect("/");
  }

  let botGuilds: GuildSummary[] = [];
  let userGuilds: any[] = [];
  let userDiscordError: string | null = null;
  let botError: string | null = null;

  try {
    botGuilds = await api.listGuilds();
  } catch (err: any) {
    console.error("Failed to fetch bot guilds:", err);
    botError = err.message || "Failed to load bot servers.";
  }

  try {
    const { fetchUserGuilds } = await import("@/lib/guild-auth");
    userGuilds = await fetchUserGuilds(session.accessToken);
  } catch (err: any) {
    console.error("Discord API Error:", err);
    userDiscordError = err?.message || "Error connecting to Discord.";
  }

  const MANAGE_GUILD = BigInt(0x20);
  const ADMINISTRATOR = BigInt(0x8);
  const adminUserGuilds = userGuilds.filter((g) => {
    try {
      const perms = BigInt(g.permissions);
      return (
        (perms & ADMINISTRATOR) === ADMINISTRATOR ||
        (perms & MANAGE_GUILD) === MANAGE_GUILD ||
        g.owner === true
      );
    } catch {
      return g.owner === true;
    }
  });

  const adminGuildIds = new Set(adminUserGuilds.map((g) => String(g.id)));
  const guilds = botGuilds.filter((g) => adminGuildIds.has(String(g.id)));

  const inviteConfigured = Boolean(getBotInviteUrl());
  // Hard failure only when bot API is down — Discord sync issues still show invite CTA
  const hardError = botError;

  return (
    <div className="space-y-8">
      <div className="flex flex-col gap-4 sm:flex-row sm:justify-between sm:items-end">
        <div>
          <h1 className="text-3xl font-bold text-white">Your Servers</h1>
          <p className="text-slate-400 mt-2">
            Select a server to manage its unique configuration and modules.
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          {inviteConfigured && <AddBotButton className="shadow-lg shadow-primary/20" />}
          <div className="text-sm font-medium px-4 py-2 bg-slate-800 rounded-xl border border-slate-700 text-slate-300">
            Showing <span className="text-white">{guilds.length}</span> active guilds
          </div>
        </div>
      </div>

      {hardError ? (
        <div className="bg-red-500/10 border border-red-500/20 p-8 rounded-2xl text-center">
          <ShieldCheck className="h-12 w-12 text-red-500 mx-auto mb-4 opacity-50" />
          <h3 className="text-white font-bold text-lg">Connection Error</h3>
          <p className="text-slate-400 mt-2">{hardError}</p>
          <div className="mt-6 flex flex-col sm:flex-row gap-3 justify-center">
            <Button variant="outline" asChild>
              <Link href="/dashboard/guilds">Retry Connection</Link>
            </Button>
            {inviteConfigured && <AddBotButton />}
          </div>
        </div>
      ) : guilds.length === 0 ? (
        <div className="bg-slate-800/30 border border-slate-800 border-dashed p-12 md:p-16 rounded-3xl text-center">
          <div className="h-16 w-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-6 border border-primary/20">
            <Users className="h-8 w-8 text-primary" />
          </div>
          <h3 className="text-white font-bold text-xl">No Servers Found</h3>
          <p className="text-slate-400 mt-2 max-w-md mx-auto">
            Invite Axiom to a Discord server where you have <span className="text-slate-200">Manage Server</span>{" "}
            permissions, then come back here to configure it.
          </p>
          {userDiscordError && (
            <p className="text-amber-400/90 text-sm mt-4 max-w-md mx-auto">
              Note: {userDiscordError}
            </p>
          )}
          <div className="mt-8 flex flex-col sm:flex-row gap-3 justify-center items-center">
            {inviteConfigured ? (
              <AddBotButton className="px-8 h-12 text-base shadow-lg shadow-primary/25" />
            ) : (
              <p className="text-sm text-red-400">
                Invite link not configured — set <code className="text-xs">DISCORD_CLIENT_ID</code> in the
                dashboard environment.
              </p>
            )}
            <Button variant="outline" asChild>
              <Link href="/dashboard/guilds">Refresh list</Link>
            </Button>
          </div>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
          {guilds.map((guild) => (
            <div
              key={guild.id}
              className="bg-[#141B2D] border border-slate-800 rounded-3xl group hover:border-primary/50 hover:bg-[#202c3f] transition-all duration-300 overflow-hidden shadow-sm hover:shadow-primary/5 shadow-black/20"
            >
              <div className="p-6">
                <div className="flex items-start justify-between mb-6">
                  <div className="relative">
                    {guild.icon_url ? (
                      <Image
                        src={guild.icon_url}
                        alt={guild.name}
                        width={64}
                        height={64}
                        className="rounded-2xl border-2 border-slate-800 shadow-xl group-hover:scale-105 transition-transform"
                      />
                    ) : (
                      <div className="h-16 w-16 bg-primary/20 rounded-2xl flex items-center justify-center border-2 border-slate-800 text-primary font-bold text-2xl shadow-xl group-hover:scale-105 transition-transform">
                        {guild.name.charAt(0)}
                      </div>
                    )}
                    <div
                      className="absolute -bottom-1 -right-1 h-4 w-4 rounded-full bg-emerald-500 border-2 border-[#141B2D]"
                      title="Bot Online"
                    />
                  </div>

                  <div className="flex flex-col items-end text-right">
                    <span className="text-[10px] uppercase font-bold text-slate-500 tracking-widest mb-1">
                      Guild ID
                    </span>
                    <span className="text-xs font-mono text-slate-400 bg-black/20 px-2 py-1 rounded-lg border border-white/5 truncate max-w-[120px]">
                      {guild.id}
                    </span>
                  </div>
                </div>

                <div>
                  <h3 className="text-xl font-bold text-white truncate group-hover:text-primary transition-colors">
                    {guild.name}
                  </h3>
                  <div className="flex items-center gap-4 mt-4 text-slate-400">
                    <div className="flex items-center gap-1.5 bg-slate-800/50 px-3 py-1.5 rounded-xl border border-white/5">
                      <Users className="h-4 w-4 text-slate-500" />
                      <span className="text-sm font-semibold text-slate-300">
                        {guild.member_count.toLocaleString()}
                      </span>
                    </div>
                    <div className="flex items-center gap-1.5 bg-slate-800/50 px-3 py-1.5 rounded-xl border border-white/5">
                      <Hash className="h-4 w-4 text-slate-500" />
                      <span className="text-sm font-semibold text-slate-300">Active</span>
                    </div>
                  </div>
                </div>
              </div>

              <div className="px-6 py-4 bg-slate-800/20 border-t border-slate-800/80 group-hover:bg-primary/5 transition-colors">
                <Button className="w-full justify-between group/btn py-6" variant="secondary" asChild>
                  <Link href={`/dashboard/guild/${guild.id}`}>
                    <span>Manage Server</span>
                    <ChevronRight className="h-4 w-4 group-hover/btn:translate-x-1 transition-transform" />
                  </Link>
                </Button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
