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 { getCompanies } from '@/lib/actions/companies'
import { redirect } from 'next/navigation'
import { Suspense } from 'react'

interface PageProps {
  searchParams: Promise<{ id?: string }>
}

export default async function OrderPage({ searchParams }: PageProps) {
  const params = await searchParams
  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 orderId={params.id} />
        </Suspense>
      </div>
    </div>
  )
}

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

  if (!user) {
    redirect(`/auth/login?next=/order${orderId ? `?id=${orderId}` : ''}`)
  }

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

  const isAdmin = userData?.role === 'admin'
  const hasCompany = !!userData?.company_id

  if (!isAdmin && !hasCompany) {
    return (
      <div className="max-w-md mx-auto mt-12 p-6 bg-red-500/10 border border-red-500/20 rounded-2xl text-center space-y-4">
        <h2 className="text-xl font-bold text-red-400">Kein Unternehmen zugewiesen</h2>
        <p className="text-slate-400 text-sm">
          Sie müssen einem Unternehmen zugewiesen sein, um Anfragen erstellen zu können. 
          Bitte wenden Sie sich an den Administrator.
        </p>
      </div>
    )
  }

  let initialOrder = null
  if (orderId) {
    const adminClient = createAdminClient()
    const { data: orderData, error } = await adminClient
      .from('orders')
      .select('*')
      .eq('id', orderId)
      .single()

    if (error || !orderData) {
      redirect('/order')
    }

    const isAdmin = userData?.role === 'admin'
    const isOwner = orderData.user_id === user.id
    const isCompanyMember = userData?.company_id && orderData.company_id === userData.company_id
    if (!isAdmin && !isOwner && !isCompanyMember) {
      redirect('/order')
    }

    if (orderData.status === 'completed' && !isAdmin) {
      redirect('/order')
    }

    initialOrder = orderData
  }

  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)
  }

  // Fetch companies list for admin
  let companies: any[] = []
  if (userData?.role === 'admin') {
    companies = await getCompanies().catch(() => [])
  }

  return (
    <OrderWizard
      products={products}
      categories={categories}
      initialProfile={profile}
      initialEndCustomers={endCustomers}
      initialOrder={initialOrder}
      isAdmin={userData?.role === 'admin'}
      companies={companies}
    />
  )
}
