import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { getBackgroundImage } from "@/lib/preferences";
import NavigationWrapper from "@/components/navigation/NavigationWrapper";
import HousesSection from "@/components/houses/HousesSection";
import { houseService } from "@/services/houses/house.service";
import { prisma } from "@/services/database";
import type { House, HouseMembership, HouseInvitation } from "@/prisma/generated/prisma/client";

export const dynamic = "force-dynamic";

// Types pour les données sérialisées
type HouseWithRelations = House & {
  creator?: {
    id: string;
    username: string;
    avatar: string | null;
  } | null;
  creatorId?: string;
  memberships?: Array<HouseMembership & {
    user: {
      id: string;
      username: string;
      avatar: string | null;
      score: number | null;
      level: number | null;
    };
  }>;
};

type InvitationWithRelations = HouseInvitation & {
  house: {
    id: string;
    name: string;
  };
  inviter: {
    id: string;
    username: string;
    avatar: string | null;
  };
};

export default async function HousesPage() {
  const session = await auth();

  if (!session?.user?.id) {
    redirect("/login");
  }

  const [housesData, myHouseData, invitationsData, users, backgroundImage] = await Promise.all([
    // Récupérer les maisons
    houseService.getAllHouses({
      include: {
        memberships: {
          include: {
            user: {
              select: {
                id: true,
                username: true,
                avatar: true,
                score: true,
                level: true,
              },
            },
          },
          orderBy: [
            { role: "asc" }, // OWNER, ADMIN, MEMBER
            { user: { score: "desc" } }, // Puis par score décroissant
          ],
        },
        creator: {
          select: {
            id: true,
            username: true,
            avatar: true,
          },
        },
      },
    }),
    // Récupérer la maison de l'utilisateur
    houseService.getUserHouse(session.user.id, {
      memberships: {
        include: {
          user: {
            select: {
              id: true,
              username: true,
              avatar: true,
              score: true,
              level: true,
            },
          },
        },
      },
      creator: {
        select: {
          id: true,
          username: true,
          avatar: true,
        },
      },
    }),
    // Récupérer les invitations de l'utilisateur
    houseService.getUserInvitations(session.user.id, "PENDING"),
    // Récupérer tous les utilisateurs sans maison pour les invitations
    prisma.user.findMany({
      where: {
        houseMemberships: {
          none: {},
        },
      },
      select: {
        id: true,
        username: true,
        avatar: true,
      },
      orderBy: {
        username: "asc",
      },
    }),
    getBackgroundImage("challenges", "/got-2.jpg"),
  ]);

  // Sérialiser les données pour le client
  const houses = (housesData as HouseWithRelations[]).map((house: HouseWithRelations) => ({
    id: house.id,
    name: house.name,
    description: house.description,
    creator: house.creator || { id: house.creatorId || "", username: "Unknown", avatar: null },
    memberships: (house.memberships || []).map((m) => ({
      id: m.id,
      role: m.role,
      user: {
        id: m.user.id,
        username: m.user.username,
        avatar: m.user.avatar,
        score: m.user.score ?? 0,
        level: m.user.level ?? 1,
      },
    })),
  }));

  const myHouse = myHouseData
    ? {
        id: myHouseData.id,
        name: myHouseData.name,
        description: myHouseData.description,
        creator: (myHouseData as HouseWithRelations).creator || { id: (myHouseData as HouseWithRelations).creatorId || "", username: "Unknown", avatar: null },
        memberships: ((myHouseData as HouseWithRelations).memberships || []).map((m) => ({
          id: m.id,
          role: m.role,
          user: {
            id: m.user.id,
            username: m.user.username,
            avatar: m.user.avatar,
            score: m.user.score ?? 0,
            level: m.user.level ?? 1,
          },
        })),
      }
    : null;

  const invitations = (invitationsData as InvitationWithRelations[]).map((inv: InvitationWithRelations) => ({
    id: inv.id,
    house: {
      id: inv.house.id,
      name: inv.house.name,
    },
    inviter: inv.inviter,
    status: inv.status,
    createdAt: inv.createdAt.toISOString(),
  }));

  return (
    <main className="min-h-screen bg-black relative">
      <NavigationWrapper />
      <HousesSection
        initialHouses={houses}
        initialMyHouse={myHouse}
        initialUsers={users}
        initialInvitations={invitations}
        backgroundImage={backgroundImage}
      />
    </main>
  );
}
