import Link from 'next/link'
import { getSessionUser } from '@/lib/auth'
import { loadRuleByToken, toViews } from '@/lib/data/auto-participant-rules'
import { FEATURE_EXPLANATION, FEATURE_NAME } from '@/lib/domain/auto-participants'
import { AcceptExplainer } from '@/components/app/auto-participants-explainer'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { RespondButtons } from './respond-buttons'

/**
 * Public accept / decline landing for an Auto-Participant request (Task 6.4,
 * D4, 2026-09-30). Mirrors src/app/invite/[token]. Token lookup only — the
 * page never shows any other rule, and never prints the token itself.
 */
export default async function AutoParticipantTokenPage({ params }: { params: Promise<{ token: string }> }) {
  const { token } = await params
  const rule = await loadRuleByToken(token)

  if (!rule) {
    return (
      <Shell>
        <CardHeader className="text-center">
          <CardTitle>{FEATURE_NAME}</CardTitle>
          <CardDescription>This request is no longer valid.</CardDescription>
        </CardHeader>
      </Shell>
    )
  }

  const [view] = await toViews([rule])
  const isCompany = view.rule_type === 'company'
  const owner = isCompany ? view.owner.company_name ?? 'A company' : view.owner.name ?? 'Someone'

  if (isExpired(rule.token_expires_at)) {
    return (
      <Shell>
        <CardHeader className="text-center">
          <CardTitle>{FEATURE_NAME}</CardTitle>
          <CardDescription>This request has expired. Ask {owner} to send a new one.</CardDescription>
        </CardHeader>
      </Shell>
    )
  }

  const user = await getSessionUser()
  const settled = rule.status !== 'pending'

  return (
    <Shell>
      <CardHeader className="text-center">
        <CardTitle className="text-xl">{FEATURE_NAME}</CardTitle>
        <CardDescription>
          <strong>{owner}</strong> wants to automatically include you in{' '}
          {isCompany ? <>Trips involving {owner} ({view.scope_label}).</> : <>Trips where {owner} participates.</>}
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-5">
        <p className="rounded-xl border bg-neutral-50 p-4 text-sm text-neutral-700">{FEATURE_EXPLANATION}</p>
        {!settled && <AcceptExplainer owner={owner} company={isCompany ? owner : null} />}

        {settled ? (
          <div className="text-center text-sm">
            <p className="text-neutral-600">
              {rule.status === 'active' ? 'You already accepted this request.' : rule.status === 'declined' ? 'Declined.' : 'This request is no longer open.'}
            </p>
            <Link href="/settings/auto-participants" className="mt-2 inline-block font-semibold underline">
              Open your Auto-Participants settings
            </Link>
          </div>
        ) : user ? (
          <RespondButtons token={token} owner={owner} />
        ) : (
          <div className="space-y-3 text-center">
            <Link
              href={`/login?next=${encodeURIComponent(`/auto-participants/${token}`)}`}
              className="inline-block rounded-lg bg-neutral-900 px-4 py-2.5 text-sm font-semibold text-white"
            >
              Sign in or create an account to respond
            </Link>
            <p className="text-xs text-neutral-500">If you do not have an account yet, create one and choose your role first.</p>
          </div>
        )}
      </CardContent>
    </Shell>
  )
}

/** Same check as src/app/invite/[token]: a missing expiry never expires. */
function isExpired(expiresAt: string | null): boolean {
  return Boolean(expiresAt) && new Date(expiresAt as string).getTime() < Date.now()
}

function Shell({ children }: { children: React.ReactNode }) {
  return (
    <main className="flex min-h-screen items-center justify-center bg-neutral-50 p-4">
      <Card className="w-full max-w-md">{children}</Card>
    </main>
  )
}
