import { ReactNode, useState } from 'react';
import { Head } from '@inertiajs/react';
import AdminLayout from '@/layouts/AdminLayout';
import { Button } from '@/components/ui/button';
import { Eye } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import { useRolePreview } from '@/contexts/RolePreviewContext';
import SopManual, { VIEW_AS_OPTIONS, type RoleKey } from '@/components/SopManual';

const SOPPage = () => {
  const { roles, isReallySysLevel } = useAuth();
  const { getEffectiveRoles } = useRolePreview();
  // null = use my own (or globally-previewed) role; otherwise preview a role.
  const [viewAs, setViewAs] = useState<'all' | RoleKey | null>(null);

  const realSysLevel = isReallySysLevel();

  // Effective roles used for filtering: an in-page "Viewing as" override wins,
  // then any global role preview, then the user's real roles.
  const effectiveRoles: string[] =
    viewAs === null
      ? getEffectiveRoles(roles)
      : viewAs === 'all'
        ? ['sys_admin']
        : [viewAs];

  // Role preview — staff can see what each role's manual looks like.
  const viewAsControls = realSysLevel ? (
    <div className="mb-6 flex flex-wrap items-center gap-2 rounded-lg border border-border bg-muted/40 p-3">
      <span className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground">
        <Eye className="h-4 w-4" /> Viewing as:
      </span>
      <Button
        variant={viewAs === null ? 'default' : 'outline'}
        size="sm"
        onClick={() => setViewAs(null)}
      >
        My role
      </Button>
      {VIEW_AS_OPTIONS.map((opt) => (
        <Button
          key={opt.value}
          variant={viewAs === opt.value ? 'default' : 'outline'}
          size="sm"
          onClick={() => setViewAs(opt.value)}
        >
          {opt.label}
        </Button>
      ))}
    </div>
  ) : null;

  return (
    <>
      <Head title="System Manual (SOPs)" />
      <SopManual effectiveRoles={effectiveRoles} viewAsControls={viewAsControls} />
    </>
  );
};

SOPPage.layout = (page: ReactNode) => <AdminLayout>{page}</AdminLayout>;

export default SOPPage;
