import { Navigate, Outlet, useLocation } from 'react-router-dom'
import { RouteLoader } from '@meshkee/dashboard-ui'
import { useAuth } from '../../context/AuthContext'
import { CheckoutStepper, type CheckoutStepId } from '../../components/checkout/CheckoutStepper'

/** Cart and checkout login are public. Delivery, payment, and success require auth. */
const PUBLIC_STEPS = new Set<CheckoutStepId>(['cart', 'login'])

function stepFromPath(pathname: string): CheckoutStepId {
  if (pathname.endsWith('/login')) return 'login'
  if (pathname.endsWith('/delivery')) return 'delivery'
  if (pathname.endsWith('/payment')) return 'payment'
  if (pathname.endsWith('/success') || pathname.endsWith('/failed')) return 'payment'
  return 'cart'
}

function loginRedirectPath(returnTo: string) {
  return `/checkout/login?redirect=${encodeURIComponent(returnTo)}`
}

export function CheckoutFlow() {
  const { user, isLoading } = useAuth()
  const location = useLocation()
  const step = stepFromPath(location.pathname)
  const isAuthenticated = Boolean(user)

  if (isLoading) {
    return <RouteLoader />
  }

  if (!isAuthenticated && !PUBLIC_STEPS.has(step)) {
    return (
      <Navigate
        to={loginRedirectPath(location.pathname)}
        replace
        state={{ from: location.pathname }}
      />
    )
  }

  if (isAuthenticated && step === 'login') {
    const params = new URLSearchParams(location.search)
    const fromQuery = params.get('redirect')
    const fromState = (location.state as { from?: string } | null)?.from
    const destination =
      fromQuery && fromQuery.startsWith('/') && !fromQuery.startsWith('//')
        ? fromQuery
        : fromState ?? '/checkout/delivery'
    return <Navigate to={destination} replace />
  }

  return (
    <>
      {step !== 'login' &&
        location.pathname !== '/checkout/success' &&
        location.pathname !== '/checkout/failed' && (
        <CheckoutStepper current={step} isAuthenticated={isAuthenticated} />
      )}
      <Outlet />
    </>
  )
}
