'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { X, Sparkles, ChevronRight } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { usePermissions } from '@/hooks/use-permissions';
import { useOnboardingStatus } from '@/hooks/use-onboarding-status';
import { cn } from '@/lib/utils';

const DISMISS_STORAGE_KEY = 'pn-crm.onboarding-banner-dismissed';

function getInitialDismissed(): boolean {
  if (typeof window === 'undefined') return false;
  return sessionStorage.getItem(DISMISS_STORAGE_KEY) === '1';
}

/**
 * Topbar banner nudging super_admins to finish onboarding while the
 * checklist is incomplete. Renders nothing for non-super-admin roles and
 * disappears for everyone once the checklist hits 100%.
 *
 * Dismissible per browser session — flag stored in sessionStorage so it
 * comes back on next sign-in (we want it visible until they actually
 * finish, not just clicked-away forever).
 */
export function OnboardingBanner() {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';
  const { isSuperAdmin } = usePermissions();
  const { data, isLoading } = useOnboardingStatus({ enabled: isSuperAdmin });
  const [dismissed, setDismissed] = useState(getInitialDismissed);

  if (!isSuperAdmin || isLoading || !data) return null;
  if (data.isComplete) return null;
  if (dismissed) return null;
  if (!portSlug) return null;

  const next = data.nextStep;
  return (
    <div
      className={cn(
        'flex items-center justify-between gap-3 border-b border-amber-200 bg-amber-50 px-4 py-2 text-sm text-amber-900',
        'dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-100',
      )}
      role="status"
    >
      <div className="flex min-w-0 items-center gap-2">
        <Sparkles className="size-4 shrink-0" aria-hidden />
        <span className="truncate">
          <strong>Setup is {data.percent}% complete</strong>
          {/* Verbose progress + the "Next:" deep-link are hidden on mobile,
              where they get clipped (R1) and duplicate the always-visible
              "View checklist" button. Shown from sm: up. */}
          <span className="hidden sm:inline">
            . {data.completed} of {data.total} steps done.{' '}
            {next ? (
              <>
                Next:{' '}
                <Link
                  // eslint-disable-next-line @typescript-eslint/no-explicit-any
                  href={`/${portSlug}/admin/${next.href}` as any}
                  className="font-medium underline-offset-2 hover:underline"
                >
                  {next.label}
                </Link>
              </>
            ) : null}
          </span>
        </span>
      </div>
      <div className="flex shrink-0 items-center gap-1">
        <Button asChild size="sm" variant="ghost" className="h-7 px-2 text-xs">
          <Link
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            href={`/${portSlug}/admin/onboarding` as any}
          >
            View checklist
            <ChevronRight className="ml-0.5 size-3" aria-hidden />
          </Link>
        </Button>
        <Button
          type="button"
          size="icon"
          variant="ghost"
          className="h-7 w-7"
          aria-label="Dismiss onboarding banner"
          onClick={() => {
            sessionStorage.setItem(DISMISS_STORAGE_KEY, '1');
            setDismissed(true);
          }}
        >
          <X className="size-3.5" aria-hidden />
        </Button>
      </div>
    </div>
  );
}
