import { createClient } from '@/lib/supabase'
import type { BrandConfig, Question, Survey } from '@/lib/types'
import { SurveyForm } from '@/components/survey-form'

// Force dynamic rendering — page fetches from Supabase at request time.
export const dynamic = 'force-dynamic'

// In Next.js 15, searchParams is a Promise and must be awaited.
interface PageProps {
  searchParams: Promise<{ s?: string }>
}

export default async function Page({ searchParams }: PageProps) {
  const { s: surveyId } = await searchParams
  const supabase = createClient()

  // 1. Fetch survey — by ?s=UUID if provided, otherwise first live survey
  const surveyQuery = supabase
    .from('surveys')
    .select('id, org_id, title, status, is_anonymous, k_threshold, consent_version_id, brand_config')

  const { data: surveyRow, error: surveyError } = surveyId
    ? await surveyQuery.eq('id', surveyId).maybeSingle()
    : await surveyQuery.eq('status', 'live').maybeSingle()

  if (surveyError) {
    return (
      <div className="no-survey" role="main">
        <h1 className="no-survey-title">Error al cargar la encuesta</h1>
        <p>No fue posible conectarse a la base de datos. Revisá las variables de entorno.</p>
        <pre className="no-survey-hint">{surveyError.message}</pre>
      </div>
    )
  }

  if (!surveyRow) {
    return (
      <div className="no-survey" role="main">
        <h1 className="no-survey-title">No hay encuesta activa</h1>
        <p>
          Para ver el formulario, la encuesta debe estar en estado <code>live</code>,
          o pasá el UUID por parámetro: <code>?s=UUID</code>.
        </p>
        <pre className="no-survey-hint">
          {`-- Activar en Supabase Cloud:\nUPDATE surveys SET status = 'live'\nWHERE id = '30000000-0000-0000-0000-000000000001';`}
        </pre>
      </div>
    )
  }

  // 2. Fetch questions ordered by position
  const { data: questionRows, error: questionsError } = await supabase
    .from('questions')
    .select(
      'id, survey_id, code, type, prompt, position, is_sensitive, required, max_select, options, conditional_rules'
    )
    .eq('survey_id', surveyRow.id)
    .order('position', { ascending: true })

  if (questionsError || !questionRows) {
    return (
      <div className="no-survey" role="main">
        <h1 className="no-survey-title">Error al cargar las preguntas</h1>
        <p>{questionsError?.message ?? 'Respuesta vacía del servidor.'}</p>
      </div>
    )
  }

  const questions = questionRows as Question[]

  console.log(`[2B] Survey loaded: id=${surveyRow.id} | questions=${questions.length}`)

  const survey: Survey = {
    id: surveyRow.id,
    org_id: surveyRow.org_id,
    title: surveyRow.title,
    status: surveyRow.status,
    is_anonymous: surveyRow.is_anonymous,
    k_threshold: surveyRow.k_threshold,
    consent_version_id: surveyRow.consent_version_id,
    brand_config: (surveyRow.brand_config as BrandConfig) ?? null,
    questions,
  }

  return <SurveyForm survey={survey} questions={questions} />
}
