import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { createAdminClient } from '@/lib/supabase/admin'
import { STATE_NAMES } from '@/lib/domain/states'
import { loadCapabilityTypes, loadProfileByClaimToken, pilotNetworkAvailable, recordClaimLinkOpened } from '@/lib/data/pilot-network'
import { ClaimForm } from './claim-form'

/**
 * Claim My Pilot Profile (§20–§22) — public, reached from the invitation
 * email. Shows what we already have, asks what describes the person, lets
 * them correct every imported field and confirm / remove / add capabilities
 * (imported = source data, never HeavyHaul Agent verified), and choose
 * whether to receive future pilot car requests. The token is the only
 * credential; it is erased once claimed (answer 6). The source of the data
 * is never shown here (answer 7).
 */
export default async function ClaimPilotProfilePage({ params }: { params: Promise<{ token: string }> }) {
  const { token } = await params
  const admin = createAdminClient()
  const available = await pilotNetworkAvailable(admin)
  const profile = available ? await loadProfileByClaimToken(token, admin) : null
  if (!profile) {
    return (
      <Shell>
        <CardHeader className="text-center">
          <CardTitle>This link is no longer available</CardTitle>
          <CardDescription>The profile may already be claimed, or the link is not valid. If you claimed your profile, sign in; otherwise write to support and we will help.</CardDescription>
        </CardHeader>
      </Shell>
    )
  }
  await recordClaimLinkOpened(profile.id, admin)
  const capabilityTypes = (await loadCapabilityTypes(admin)).filter((t) => t.active || profile.capabilities.some((c) => c.key === t.key))
  return (
    <Shell>
      <CardHeader className="text-center">
        <div className="mx-auto mb-2 grid h-11 w-11 place-items-center rounded-xl bg-[#0f1b2d] text-lg font-extrabold text-[#f5a623]">H</div>
        <CardTitle className="text-xl">Claim your HeavyHaul Agent pilot profile</CardTitle>
        <CardDescription>Your contact information is associated with pilot car services in {profile.related_states.map((s) => STATE_NAMES[s] ?? s).join(', ') || STATE_NAMES[profile.primary_state]}. Check what we have, correct anything that is wrong, and tell us what describes you.</CardDescription>
      </CardHeader>
      <CardContent>
        <ClaimForm
          token={token}
          initial={{
            name: profile.name,
            company_name: profile.company_name,
            email: profile.email,
            phone: profile.phone,
            states: profile.related_states.length ? profile.related_states : [profile.primary_state],
            capabilities: profile.capabilities.map((c) => ({ key: c.key, label: c.label, group: c.group })),
          }}
          capabilityTypes={capabilityTypes.map((t) => ({ key: t.key, label: t.label, group: t.group }))}
          states={Object.keys(STATE_NAMES)}
        />
      </CardContent>
    </Shell>
  )
}

function Shell({ children }: { children: React.ReactNode }) {
  return (
    <main className="min-h-screen bg-neutral-50 p-4">
      <div className="mx-auto max-w-2xl py-6">
        <Card>{children}</Card>
      </div>
    </main>
  )
}
