import { createClient } from '@/lib/supabase/server'
import { createAdminClient } from '@/lib/supabase/admin'
import { getProducts, getCategories } from '@/lib/actions/products'
import { getEndCustomers } from '@/lib/actions/end-customers'
import { OrderWizard } from '@/components/order-wizard'
import { redirect } from 'next/navigation'
import { Suspense } from 'react'

export default async function OrderPage() {
  return (
    <div className="min-h-screen bg-[#0a0a0a] text-white selection:bg-primary/30">
      <div className="container mx-auto py-10">
        <div className="text-center mb-12">
          <h1 className="text-5xl font-extrabold tracking-tight mb-4 text-gradient">
            Konfigurieren Sie Ihre Lösung
          </h1>
          <p className="text-slate-400 text-lg max-w-2xl mx-auto">
            Wählen Sie das passende Paket und die benötigten Module für Ihr Business.
          </p>
        </div>
        
        <Suspense fallback={<div className="h-96 w-full animate-pulse bg-white/5 rounded-2xl" />}>
          <OrderDataWrapper />
        </Suspense>
      </div>
    </div>
  )
}

async function OrderDataWrapper() {
  const supabase = await createClient()
  const { data: { user } } = await supabase.auth.getUser()

  if (!user) {
    redirect('/auth/login?next=/order')
  }

  // Check user role
  const { data: userData } = await supabase
    .from('users')
    .select('role')
    .eq('id', user.id)
    .single()

  const products = await getProducts().catch(() => [])
  const categories = await getCategories().catch(() => [])
  
  // Admin sees all end customers across partners
  let endCustomers = []
  if (userData?.role === 'admin') {
    try {
      const adminClient = createAdminClient()
      const { data } = await adminClient
        .from('end_customers')
        .select('*')
        .order('company_name', { ascending: true })
      endCustomers = data || []
    } catch (e) {
      console.error('Fehler beim Laden aller Endkunden für Admin:', e)
    }
  } else {
    endCustomers = await getEndCustomers().catch(() => [])
  }

  // Fetch profile safely using maybeSingle
  let profile = null
  try {
    const { data } = await supabase
      .from('profiles')
      .select('*')
      .eq('id', user.id)
      .maybeSingle()
    profile = data
  } catch (e) {
    console.error('Fehler beim Laden des Profils:', e)
  }

  return <OrderWizard products={products} categories={categories} initialProfile={profile} initialEndCustomers={endCustomers} />
}
