import { notFound, permanentRedirect } from 'next/navigation'
import { createAdminClient } from '@/lib/supabase/admin'
import { IntakeForm } from './intake-form'
import type { Company } from '@/types/db'

export default async function IntakePage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const admin = createAdminClient()
  const { data: page } = await admin
    .from('broker_pages')
    .select('*')
    .eq('slug', slug)
    .eq('enabled', true)
    .maybeSingle()
  if (!page) {
    // Task 94 (article §16): a renamed intake page keeps its old links alive.
    const { data: history } = await admin
      .from('broker_page_slug_history')
      .select('broker_page_id')
      .eq('old_slug', slug)
      .order('created_at', { ascending: false })
      .limit(1)
    const pageId = history?.[0]?.broker_page_id
    if (pageId) {
      const { data: current } = await admin
        .from('broker_pages')
        .select('slug')
        .eq('id', pageId)
        .eq('enabled', true)
        .maybeSingle()
      if (current?.slug) permanentRedirect(`/intake/${current.slug}`)
    }
    notFound()
  }

  // Verified-company badge + logo (Task 94): shown from level 2 up; below
  // that nothing is shown — verification is optional, never a negative mark.
  let company: Company | null = null
  if (page.company_id) {
    const { data } = await admin.from('companies').select('*').eq('id', page.company_id).maybeSingle()
    company = (data ?? null) as Company | null
  }
  const verified = !!company && company.verification_level >= 2

  // The broker's defaults control the intake page (order-intake doc §23):
  // a hard default hides the other path; 'ask' shows both.
  const policyDefault: string = page.default_permit_policy ?? 'ask'
  const forcedPath =
    policyDefault === 'synchron_required'
      ? ('synchron' as const)
      : policyDefault === 'upload_allowed'
        ? ('upload' as const)
        : null
  const paymentDefault: 'broker' | 'carrier' | null =
    page.default_payment_party === 'broker' || page.default_payment_party === 'carrier'
      ? page.default_payment_party
      : null

  return (
    <main className="min-h-screen bg-neutral-50">
      <header className="border-b bg-white">
        <div className="mx-auto flex h-16 max-w-2xl items-center justify-between px-4">
          <div className="flex items-center gap-3">
            {company?.logo_url && (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={company.logo_url} alt="" className="h-10 w-10 rounded-lg border bg-white object-contain p-0.5" />
            )}
            <div>
              <p className="font-semibold leading-tight">
                {page.display_name}
                {verified && (
                  <span
                    className="ml-2 rounded-full bg-green-50 px-2 py-0.5 text-[11px] font-semibold text-green-700"
                    title="Company verified by HeavyHaul Agent · Managed by company admin"
                  >
                    ✓ Verified company
                  </span>
                )}
              </p>
              <p className="text-xs text-neutral-500">Permit intake for {page.display_name}</p>
            </div>
          </div>
          <span className="text-xs text-neutral-500">
            Powered by <span className="font-semibold text-neutral-900">HeavyHaul Agent</span>
          </span>
        </div>
      </header>

      <div className="mx-auto max-w-2xl px-4 py-8">
        <h1 className="text-2xl font-bold tracking-tight">
          Submit your load for {page.display_name}
        </h1>
        <p className="mt-2 text-sm leading-relaxed text-neutral-600">
          {page.intro_message ??
            'Upload your rate confirmation and contact details. A shared trip workspace will be created and the broker will be notified. No account is needed to submit.'}
        </p>

        <IntakeForm
          slug={page.slug}
          brokerName={page.display_name}
          forcedPath={forcedPath}
          paymentDefault={paymentDefault}
        />

        <p className="mt-8 text-center text-[11px] leading-relaxed text-neutral-400">
          Submitting a request does not guarantee permit approval, route approval, or legal
          movement. The carrier and driver remain responsible for legal operation. Permit
          processing may be supported by our trusted partner Synchron Permits.
        </p>
      </div>
    </main>
  )
}
