'use client';

import Link from 'next/link';
import { useSession } from 'next-auth/react';
import { type ReactNode } from 'react';

import { PortalSignInCard } from '@/components/auth/PortalSignInCard';

interface RoleGateProps {
  allowedRoles: readonly string[];
  callbackUrl: string;
  badge: string;
  title: string;
  subtitle: string;
  children: ReactNode;
}

function hasAllowedRole(sessionRoles: string[] | undefined, allowedRoles: readonly string[]) {
  const normalizedAllowed = new Set(allowedRoles.map((role) => role.toLowerCase()));
  return (sessionRoles || []).some((role) => normalizedAllowed.has(role.toLowerCase()));
}

export function RoleGate({
  allowedRoles,
  callbackUrl,
  badge,
  title,
  subtitle,
  children,
}: RoleGateProps) {
  const { data: session, status } = useSession();

  if (status === 'loading') {
    return (
      <div className="flex min-h-screen items-center justify-center bg-gray-900 px-4">
        <div className="text-center">
          <div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-blue-600" />
          <p className="text-gray-400">Loading...</p>
        </div>
      </div>
    );
  }

  if (status === 'unauthenticated') {
    return (
      <div className="flex min-h-screen items-center justify-center bg-gray-900 px-4 py-12">
        <PortalSignInCard
          badge={badge}
          title={title}
          subtitle={subtitle}
          callbackUrl={callbackUrl}
        />
      </div>
    );
  }

  if (!hasAllowedRole(session?.roles, allowedRoles)) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-gray-900 px-4 py-12">
        <div className="w-full max-w-lg rounded-2xl border border-gray-800 bg-gray-900/80 p-8 text-center shadow-xl shadow-black/40">
          <p className="mb-1 text-sm font-medium uppercase tracking-wide text-orange-400">{badge}</p>
          <h1 className="mb-3 text-2xl font-bold text-white">Access Restricted</h1>
          <p className="mb-2 text-gray-400">
            Your account does not currently include one of the roles required for this workspace.
          </p>
          <p className="mb-6 text-sm text-gray-500">
            Required roles: {allowedRoles.join(', ')}
          </p>
          <div className="flex flex-col gap-3 pt-2 sm:flex-row sm:justify-center">
            <Link
              href="/"
              className="inline-flex h-10 items-center justify-center rounded-md bg-gray-700 px-4 text-base font-medium text-white transition-colors hover:bg-gray-600"
            >
              Return Home
            </Link>
            <Link
              href="/help/support"
              className="inline-flex h-10 items-center justify-center rounded-md border border-gray-600 bg-transparent px-4 text-base font-medium text-white transition-colors hover:bg-gray-800"
            >
              Contact Support
            </Link>
          </div>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}
