import { notFound } from 'next/navigation';

import { createClient } from '@supabase/supabase-js';

import { SiteRenderer } from '@kit/site-builder/components';
import type { SiteData } from '@kit/site-builder/context';

interface Props {
  params: Promise<{ slug: string; page: string[] }>;
}

export default async function ClubSubPage({ params }: Props) {
  const { slug, page: pagePath } = await params;
  const pageSlug = pagePath.join('/');

  const supabase = createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLIC_KEY!,
  );

  const { data: account } = await supabase
    .from('accounts')
    .select('id')
    .eq('slug', slug)
    .single();
  if (!account) notFound();

  const { data: settings } = await supabase
    .from('site_settings')
    .select('*')
    .eq('account_id', account.id)
    .eq('is_public', true)
    .maybeSingle();
  if (!settings) notFound();

  const { data: sitePageData } = await supabase
    .from('site_pages')
    .select('*')
    .eq('account_id', account.id)
    .eq('slug', pageSlug)
    .eq('is_published', true)
    .maybeSingle();
  if (!sitePageData) notFound();

  // Pre-fetch CMS data for Puck components
  const [eventsRes, coursesRes, postsRes] = await Promise.all([
    supabase
      .from('events')
      .select('id, name, event_date, event_time, location, fee, status')
      .eq('account_id', account.id)
      .order('event_date', { ascending: true })
      .limit(20),
    supabase
      .from('courses')
      .select('id, name, start_date, end_date, fee, capacity, status')
      .eq('account_id', account.id)
      .order('start_date', { ascending: true })
      .limit(20),
    supabase
      .from('cms_posts')
      .select('id, title, excerpt, cover_image, published_at, slug')
      .eq('account_id', account.id)
      .eq('status', 'published')
      .order('published_at', { ascending: false })
      .limit(20),
  ]);

  const siteData: SiteData = {
    accountId: account.id,
    events: eventsRes.data ?? [],
    courses: (coursesRes.data ?? []).map((c) => ({ ...c, enrolled_count: 0 })),
    posts: postsRes.data ?? [],
  };

  return (
    <div
      style={
        {
          '--primary': settings.primary_color,
          fontFamily: settings.font_family,
        } as React.CSSProperties
      }
    >
      <SiteRenderer
        data={(sitePageData.puck_data ?? {}) as Record<string, unknown>}
        siteData={siteData}
      />
    </div>
  );
}
