import { useState } from 'react'
import { createFileRoute, Link } from '@tanstack/react-router'
import { useServerFn } from '@tanstack/react-start'
import { LogIn, Lock, ShieldCheck, UserPlus, Wallet } from 'lucide-react'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { PricingGrid } from '@/components/PricingGrid'
import { GoogleSignInButton, useGoogleAvailable } from '@/components/GoogleButton'
import { getServerUser } from '@/lib/identity.functions'
import { startCheckout } from '@/lib/account.functions'
import { formatCedis, getPackage } from '@/lib/pricing'
import { cn } from '@/lib/utils'

export const Route = createFileRoute('/buy')({
  validateSearch: z.object({ package: z.string().optional() }),
  // Signed-out visitors see the bundles with a sign-in panel instead of being
  // sent away, so they come straight back here to pay.
  beforeLoad: async () => ({ user: await getServerUser() }),
  head: () => ({ meta: [{ title: 'Buy SMS credit — AkotoCreative SMS' }] }),
  component: BuyPage,
})

function BuyPage() {
  const { user } = Route.useRouteContext()
  const { package: highlighted } = Route.useSearch()
  if (!user) return <SignInToBuy highlighted={highlighted} />
  return <Checkout highlighted={highlighted} />
}

function BuyHeading({ intro }: { intro: string }) {
  return (
    <div className="mb-10 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
      <div>
        <p className="font-display text-sm font-bold tracking-[0.2em] text-primary uppercase">Top up</p>
        <h1 className="mt-2 text-4xl font-extrabold sm:text-5xl">Buy SMS credit</h1>
        <p className="mt-3 max-w-xl text-muted-foreground">{intro}</p>
      </div>
      <p className="flex items-center gap-2 text-sm text-muted-foreground">
        <Lock className="size-4" aria-hidden /> Secured by Moolre
      </p>
    </div>
  )
}

function SignInToBuy({ highlighted }: { highlighted?: string }) {
  const selected = highlighted ? getPackage(highlighted) : undefined
  const next = selected ? `/buy?package=${selected.id}` : '/buy'
  const googleAvailable = useGoogleAvailable()

  return (
    <div className="mx-auto max-w-content px-4 py-16 sm:px-6">
      <BuyHeading intro="Sign in to buy credit. Your credits are added to your own account, so you can send messages as soon as the payment is confirmed." />

      <section
        aria-labelledby="sign-in-to-buy"
        className="mb-12 grid gap-8 rounded-3xl border bg-card p-7 shadow-deep sm:p-9 lg:grid-cols-[1fr_24rem] lg:items-center"
      >
        <div>
          <h2 id="sign-in-to-buy" className="text-2xl font-extrabold sm:text-3xl">
            {selected ? `Sign in to buy the ${selected.name} bundle` : 'Sign in to buy credit'}
          </h2>
          {selected ? (
            <p className="mt-3 text-muted-foreground">
              <span className="font-semibold text-foreground">
                {selected.credits.toLocaleString('en-GH')} SMS credits for {formatCedis(selected.price)}
              </span>
              . After you sign in you come straight back here to pay.
            </p>
          ) : (
            <p className="mt-3 text-muted-foreground">
              Pick a bundle below, or sign in first. After you sign in you come straight back here to pay.
            </p>
          )}
          <p className="mt-5 flex items-start gap-2 text-sm text-muted-foreground">
            <ShieldCheck className="mt-0.5 size-4 shrink-0 text-primary" aria-hidden />
            New here? Signing in with Google creates your free account automatically. No password needed.
          </p>
        </div>
        <div className="grid gap-3">
          <GoogleSignInButton label="Sign in with Google" next={next} divider={false} />
          {googleAvailable && (
            <div className="flex items-center gap-3 text-xs text-muted-foreground" aria-hidden>
              <span className="h-px flex-1 bg-border" /> or use your email <span className="h-px flex-1 bg-border" />
            </div>
          )}
          <div className="grid gap-3 sm:grid-cols-2">
            <Button asChild variant={googleAvailable ? 'secondary' : 'default'}>
              <Link to="/login" search={{ redirect: next }}>
                <LogIn /> Sign in
              </Link>
            </Button>
            <Button asChild variant="secondary">
              <Link to="/signup" search={{ redirect: next }}>
                <UserPlus /> Create account
              </Link>
            </Button>
          </div>
        </div>
      </section>

      <PricingGrid
        renderAction={(pkg) => (
          <Button
            asChild
            className={cn('w-full', highlighted === pkg.id && 'ring-4 ring-accent')}
            variant={pkg.popular ? 'secondary' : 'default'}
          >
            <Link to="/buy" search={{ package: pkg.id }} aria-current={highlighted === pkg.id ? 'true' : undefined}>
              {highlighted === pkg.id ? 'Selected' : `Choose ${pkg.name}`}
            </Link>
          </Button>
        )}
      />
    </div>
  )
}

function Checkout({ highlighted }: { highlighted?: string }) {
  const selected = highlighted ? getPackage(highlighted) : undefined
  const checkout = useServerFn(startCheckout)
  const [pending, setPending] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  async function buy(packageId: string) {
    setPending(packageId)
    setError(null)
    try {
      const { url } = await checkout({ data: { packageId } })
      window.location.assign(url)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'We could not start the payment. Please try again.')
      setPending(null)
    }
  }

  return (
    <div className="mx-auto max-w-content px-4 py-16 sm:px-6">
      <BuyHeading intro="Choose a bundle. You’ll be taken to Moolre’s secure checkout to pay with MTN MoMo, Telecel Cash, AirtelTigo Money or card. Credits land in your balance as soon as the payment is confirmed." />

      {selected && (
        <div className="mb-8 flex flex-col gap-4 rounded-2xl border border-primary/30 bg-primary/5 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
          <p className="text-sm">
            <span className="font-semibold">{selected.name} bundle:</span>{' '}
            {selected.credits.toLocaleString('en-GH')} SMS credits for {formatCedis(selected.price)}
          </p>
          <Button disabled={pending !== null} onClick={() => buy(selected.id)}>
            <Wallet />
            {pending === selected.id ? 'Opening checkout…' : `Pay ${formatCedis(selected.price)}`}
          </Button>
        </div>
      )}

      {error && (
        <p role="alert" className="mb-6 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">
          {error}
        </p>
      )}

      <PricingGrid
        renderAction={(pkg) => (
          <Button
            className={cn('w-full', highlighted === pkg.id && 'ring-4 ring-accent')}
            variant={pkg.popular ? 'secondary' : 'default'}
            disabled={pending !== null}
            onClick={() => buy(pkg.id)}
          >
            <Wallet />
            {pending === pkg.id ? 'Opening checkout…' : `Pay for ${pkg.name}`}
          </Button>
        )}
      />
    </div>
  )
}
