import CatalogsClient from "@/app/catalogs/catalogs-client";
import LoginClient from "@/app/login/login-client";
import { createAdminClient } from "@/lib/supabase-admin";
import { createClient } from "@/lib/supabase-server";
import { isOwnerUser } from "@/lib/owner-auth";

type CatalogRow = {
  id: string;
  slug: string;
  store_name: string | null;
  catalog_name: string | null;
  logo_url: string | null;
  catalog_logo_url: string | null;
  product_count?: number;
  monthly_visits?: number;
};

type ProfileRow = {
  id: string;
  slug: string | null;
  store_name: string | null;
  catalog_name: string | null;
  logo_url: string | null;
  catalog_logo_url: string | null;
};

export default async function CatalogsPage() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    return <LoginClient />;
  }

  if (!isOwnerUser({ id: user.id, email: user.email })) {
    return (
      <div className="min-h-screen flex items-center justify-center p-6">
        <div className="w-full max-w-lg rounded-2xl bg-white p-6 shadow-lg border border-zinc-200 text-center">
          <h1 className="text-xl font-semibold text-zinc-900">Acesso negado</h1>
          <p className="text-sm text-zinc-500 mt-2">
            Seu usuário não tem permissão para acessar este painel.
          </p>
        </div>
      </div>
    );
  }

  const admin = createAdminClient();
  
  // 1. Fetch profiles first
  const { data: profiles, error: profilesError } = await admin
    .from("profiles")
    .select("id,slug,store_name,catalog_name,logo_url,catalog_logo_url")
    .not("slug", "is", null)
    .order("updated_at", { ascending: false })
    .limit(500);
    
  if (profilesError) {
    console.error("Error fetching catalogs:", profilesError);
  }

  // 2. Fetch product counts manually since relation embedding might fail
  // We fetch only user_id for active products to count them in memory
  // This is a workaround for missing FK constraints for embedding
  const profileIds = (profiles || []).map((p) => p.id);
  const productCounts: Record<string, number> = {};

  if (profileIds.length > 0) {
    // Determine chunks to avoid too large query if many profiles
    const chunkSize = 100;
    for (let i = 0; i < profileIds.length; i += chunkSize) {
      const chunk = profileIds.slice(i, i + chunkSize);
      const { data: products } = await admin
        .from("products")
        .select("user_id")
        .eq("active", true)
        .in("user_id", chunk);

      if (products) {
        products.forEach((p) => {
          if (p.user_id) {
            productCounts[p.user_id] = (productCounts[p.user_id] || 0) + 1;
          }
        });
      }
    }
  }

  const baseUrl =
    process.env.NEXT_PUBLIC_PUBLIC_CATALOG_BASE_URL?.replace(/\/$/, "") || "https://ktalogu.com.br";

  const rows: CatalogRow[] = ((profiles || []) as ProfileRow[]).map((item) => {
    return {
      id: item.id,
      slug: item.slug || "",
      store_name: item.store_name,
      catalog_name: item.catalog_name,
      logo_url: item.logo_url,
      catalog_logo_url: item.catalog_logo_url,
      product_count: productCounts[item.id] || 0,
      monthly_visits: undefined // Not tracking visits yet
    };
  });

  return <CatalogsClient baseUrl={baseUrl} rows={rows} />;
}
