'use client'

import { Suspense, useEffect, useState } from 'react'
import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'
import { useAuth } from '@/lib/auth'
import { api, type ApiError } from '@/lib/api'
import { PageSkeleton } from '@/components/Skeletons'

interface Card {
  id: number
  brand?: string | null
  last4?: string | null
  label?: string | null
  exp_month?: number | null
  exp_year?: number | null
  is_default?: boolean
}

function CardsInner() {
  const router = useRouter()
  const params = useSearchParams()
  const { user, ready } = useAuth()
  const [cards, setCards] = useState<Card[]>([])
  const [loading, setLoading] = useState(true)
  const [busy, setBusy] = useState(false)
  const [msg, setMsg] = useState<string | null>(null)

  const setupRef = params.get('setup_ref')

  useEffect(() => { if (ready && !user) router.replace('/login?redirect=/account/cards') }, [ready, user, router])

  const load = () => {
    api.get<{ data?: Card[] } | Card[]>('/payment-methods', true)
      .then((r) => setCards((r as { data?: Card[] }).data ?? (r as Card[])))
      .catch(() => setCards([]))
      .finally(() => setLoading(false))
  }

  useEffect(() => { if (user) load() }, [user])

  // Returning from the gateway card-setup page: capture the instrument.
  useEffect(() => {
    if (!user || !setupRef) return
    setBusy(true)
    api.post<Card>('/payment-methods/capture', { reference: setupRef }, true)
      .then(() => { setMsg('Card saved.'); load() })
      .catch((e) => setMsg((e as ApiError).message || 'Could not save the card.'))
      .finally(() => { setBusy(false); router.replace('/account/cards') })
  }, [user, setupRef, router])

  const addCard = async () => {
    setBusy(true); setMsg(null)
    try {
      const res = await api.post<{ checkout_url?: string | null; reference?: string }>('/payment-methods/setup', { source: 'web' }, true)
      if (res.checkout_url) { window.location.href = res.checkout_url; return }
      setMsg('Saving cards is not available right now.')
    } catch (e) {
      setMsg((e as ApiError).message || 'Could not start card setup.')
    } finally { setBusy(false) }
  }

  const makeDefault = async (id: number) => {
    try { await api.post(`/payment-methods/${id}/default`, {}, true); load() } catch { /* ignore */ }
  }
  const remove = async (id: number) => {
    if (!confirm('Remove this card?')) return
    try { await api.del(`/payment-methods/${id}`, true); load() } catch { /* ignore */ }
  }

  if (!ready || !user) return <PageSkeleton />

  return (
    <div className="container-x py-8">
      <nav className="mb-2 text-xs text-muted"><Link href="/account">My account</Link> / <span className="text-ink">Payment methods</span></nav>
      <div className="flex items-center justify-between">
        <h1 className="h-section">Payment methods</h1>
        <button onClick={addCard} disabled={busy} className="btn btn-primary btn-sm disabled:opacity-60">{busy ? 'Please wait…' : '+ Add card'}</button>
      </div>

      {msg && <div className="mt-4 rounded-lg bg-brand-soft p-3 text-sm text-brand-dark">{msg}</div>}

      <div className="mt-6 space-y-3">
        {loading ? (
          Array.from({ length: 2 }).map((_, i) => <div key={i} className="h-16 animate-pulse rounded-xl bg-soft" />)
        ) : cards.length === 0 ? (
          <div className="card p-10 text-center text-muted">No saved cards yet. Add a card for faster checkout.</div>
        ) : (
          cards.map((c) => (
            <div key={c.id} className="card flex items-center justify-between p-4">
              <div className="flex items-center gap-3">
                <div className="grid h-10 w-14 place-items-center rounded-md bg-soft text-[11px] font-bold uppercase text-muted">{c.brand ?? 'Card'}</div>
                <div>
                  <div className="text-sm font-semibold">•••• {c.last4 ?? '----'}</div>
                  {(c.exp_month && c.exp_year) ? <div className="text-[12px] text-muted">Expires {String(c.exp_month).padStart(2, '0')}/{String(c.exp_year).slice(-2)}</div> : null}
                </div>
                {c.is_default && <span className="tag tag-otc">Default</span>}
              </div>
              <div className="flex items-center gap-2">
                {!c.is_default && <button onClick={() => makeDefault(c.id)} className="text-[13px] font-semibold text-brand-strong hover:underline">Make default</button>}
                <button onClick={() => remove(c.id)} className="text-[13px] text-rose-600 hover:underline">Remove</button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  )
}

export default function CardsPage() {
  return <Suspense fallback={<PageSkeleton />}><CardsInner /></Suspense>
}
