'use client'

import { useActionState } from 'react'
import Link from 'next/link'
import { useSearchParams } from 'next/navigation'
import { Suspense } from 'react'
import { signIn } from '../actions'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Alert, AlertDescription } from '@/components/ui/alert'

export default function LoginPage() {
  return (
    <Suspense>
      <LoginForm />
    </Suspense>
  )
}

/** Portal labels for the role-specific entrances on the landing page. */
const PORTALS: Record<string, { title: string; tagline: string }> = {
  broker: { title: 'Broker Portal', tagline: 'Stop chasing permits. Start seeing the trip.' },
  carrier: {
    title: 'Carrier Control Tower',
    tagline: 'Every permit, every trip, every warning — in one place.',
  },
  driver: { title: 'Driver Portal', tagline: 'Ask questions about your permit before you move.' },
}

/**
 * Username + password only. Role switching for pilot testing happens AFTER
 * sign-in, in the header bar (AUTH_ROLE_SWITCH) — not here.
 */
function LoginForm() {
  const [state, action, pending] = useActionState(signIn, undefined)
  const params = useSearchParams()
  const next = params.get('next') ?? ''
  const portal = PORTALS[params.get('role') ?? '']

  return (
    <main className="flex min-h-screen items-center justify-center bg-neutral-50 p-4">
      <Card className="w-full max-w-md">
        <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>
          {portal && (
            <span className="mx-auto mb-1 rounded-full bg-[#0f1b2d] px-3 py-1 text-xs font-bold text-[#f5a623]">
              {portal.title}
            </span>
          )}
          <CardTitle className="text-xl">Sign in to HeavyHaul Agent</CardTitle>
          <CardDescription>
            {portal?.tagline ?? 'The shared workspace for oversize trips'}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form action={action} className="space-y-4">
            <input type="hidden" name="next" value={next} />
            {state?.error && (
              <Alert variant="destructive">
                <AlertDescription>{state.error}</AlertDescription>
              </Alert>
            )}
            <div className="space-y-2">
              <Label htmlFor="username">Username</Label>
              <Input id="username" name="username" type="text" required autoComplete="username" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">Password</Label>
              <Input id="password" name="password" type="password" required autoComplete="current-password" />
            </div>
            <Button type="submit" className="w-full" disabled={pending}>
              {pending ? 'Signing in…' : 'Sign in'}
            </Button>
            <p className="text-center text-sm text-neutral-500">
              New here?{' '}
              <Link href="/signup" className="font-medium text-neutral-900 underline">
                Create an account
              </Link>
            </p>
          </form>
        </CardContent>
      </Card>
    </main>
  )
}
