'use client'

import type { ReactNode } from 'react'
import Link from 'next/link'
import { useAuth } from '@/contexts/AuthContext'
import { hasAnyPermission, hasPermission } from '@/lib/permissions'

export function RequirePermission({
  permission,
  anyOf,
  children,
}: {
  permission?: string
  anyOf?: string[]
  children: ReactNode
}) {
  const { user, loading } = useAuth()

  if (loading) {
    return (
      <div className="flex min-h-[40vh] items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-2 border-brand-500 border-t-transparent" />
      </div>
    )
  }

  const ok = permission
    ? hasPermission(user, permission)
    : anyOf
      ? hasAnyPermission(user, anyOf)
      : true

  if (!ok) {
    return (
      <div className="premium-card mx-auto max-w-lg rounded-2xl p-8 text-center">
        <h1 className="text-lg font-semibold text-[var(--premium-text)]">Access denied</h1>
        <p className="mt-2 text-sm text-[var(--premium-muted-text)]">
          You do not have permission to view this page.
        </p>
        <Link
          href="/"
          className="mt-4 inline-flex rounded-xl bg-brand-600 px-4 py-2 text-sm font-semibold text-white"
        >
          Back to dashboard
        </Link>
      </div>
    )
  }

  return <>{children}</>
}
