import { redirect } from 'next/navigation';
import { FIRM_ROLE_LABEL, isPortalRole, isStaff, me } from '@/lib/api';
import { logout } from '../actions';
import { PUBLIC_SITE } from '@/lib/format';
import { BellIcon, ExternalLinkIcon, LogOutIcon } from '@/components/Icons';
import { BrandMark, BrandName } from '@/components/BrandMark';
import { PortalNav, type PortalTab } from '@/components/PortalNav';

export const dynamic = 'force-dynamic';

export default async function PortalLayout({ children }: { children: React.ReactNode }) {
  const user = await me();
  if (user.mustChangePassword) redirect('/change-password');
  if (isStaff(user.role)) redirect('/');
  if (!isPortalRole(user.role)) redirect('/login');
  const org = user.organization;
  const firmRole = org?.role;
  const firm = !!org?.hasFirm;
  const manage = firmRole === 'owner' || firmRole === 'admin';
  const tabs: PortalTab[] = [
    { href: '/portal', label: 'Overview' },
    ...(user.lawyer
      ? [
          { href: '/portal/profile', label: 'My profile' },
          { href: '/portal/credentials', label: 'Credentials' },
          { href: '/portal/rankings', label: 'Rankings' },
          { href: '/portal/leads', label: 'My enquiries' },
          { href: '/portal/reviews', label: 'Reviews' },
          { href: '/portal/analytics', label: 'Analytics' },
        ]
      : []),
    ...(firm
      ? [
          { href: '/portal/firm', label: 'Firm' },
          { href: '/portal/firm/lawyers', label: 'Lawyers' },
          ...(firmRole !== 'billing' ? [{ href: '/portal/firm/leads', label: 'Firm enquiries' }] : []),
          { href: '/portal/firm/team', label: 'Team' },
          ...(manage ? [{ href: '/portal/firm/integrations', label: 'Integrations' }] : []),
        ]
      : []),
    ...(org && firmRole !== 'member' ? [{ href: '/portal/billing', label: 'Billing' }] : []),
    { href: '/portal/notifications', label: 'Notifications', badge: user.unreadNotifications },
    { href: '/portal/security', label: 'Security' },
  ];
  return (
    <div className="min-h-screen">
      <header className="sticky top-0 z-30 border-b border-rule bg-surface/90 backdrop-blur">
        <div className="mx-auto flex max-w-6xl items-center justify-between gap-4 px-4 pt-3 sm:px-6">
          <p className="flex min-w-0 items-center gap-2.5">
            <BrandMark />
            <BrandName sub={firm && !user.lawyer ? 'Firm dashboard' : 'Professional dashboard'} />
          </p>
          <div className="flex items-center gap-2">
            {org && (
              <span className="hidden text-right text-xs leading-tight text-muted md:block">
                <span className="block font-semibold text-ink">{org.name}</span>
                {FIRM_ROLE_LABEL[org.role] ?? org.role}
              </span>
            )}
            <a href="/portal/notifications" className="btn btn-ghost btn-icon relative" aria-label={`Notifications${user.unreadNotifications ? `, ${user.unreadNotifications} unread` : ''}`}>
              <BellIcon className="h-5 w-5" />
              {user.unreadNotifications > 0 && <span className="absolute right-1 top-1 h-2 w-2 rounded-full bg-brass" />}
            </a>
            {user.lawyer && (
              <a href={`${PUBLIC_SITE}/lawyers/${user.lawyer.slug}/`} target="_blank" rel="noopener" className="btn btn-quiet btn-sm">
                <ExternalLinkIcon className="h-4 w-4" /> <span className="hidden sm:inline">Public profile</span>
              </a>
            )}
            <form action={logout}>
              <button className="btn btn-ghost btn-sm" aria-label="Sign out">
                <LogOutIcon className="h-4 w-4" /> <span className="hidden sm:inline">Sign out</span>
              </button>
            </form>
          </div>
        </div>
        <div className="mx-auto max-w-6xl px-2 sm:px-4">
          <PortalNav tabs={tabs} />
        </div>
      </header>
      <main className="mx-auto max-w-6xl px-4 py-8 sm:px-6">{children}</main>
    </div>
  );
}
