import { usePage } from '@inertiajs/react';

type AuthUser = {
  firstName: string;
  lastName: string;
  username: string;
  roleKey: string;
};

type Props = {
  title: string;
  onMenuToggle?: () => void;
};

const roleLabel: Record<string, string> = {
  super_admin: 'Super Admin',
  owner: 'مدیر ارشد',
  principal: 'مدیر مدرسه',
  moaven: 'معاون',
  teacher: 'معلم',
  student: 'دانش‌آموز',
  support: 'پشتیبانی',
  finance: 'مالی',
};

export function Topbar({ title, onMenuToggle }: Props) {
  const { props } = usePage<{ auth?: { user?: AuthUser } }>();
  const user = props.auth?.user;

  const displayName = user
    ? (trimStr(`${user.firstName} ${user.lastName}`) || user.username)
    : null;

  const role = user?.roleKey ? (roleLabel[user.roleKey] ?? user.roleKey) : null;

  return (
    <header className="dashboard-topbar">
      <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
        {onMenuToggle && (
          <button className="hamburger-btn" type="button" aria-label="منو" onClick={onMenuToggle}>
            <span />
            <span />
            <span />
          </button>
        )}
        <h1 style={{ margin: 0 }}>{title}</h1>
      </div>
      {displayName && (
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '0.875rem', flexWrap: 'wrap', justifyContent: 'flex-end' }}>
          <span style={{ color: 'var(--color-text-muted)' }}>{role}</span>
          <span style={{ fontWeight: 600 }}>{displayName}</span>
          <form method="POST" action="/logout" style={{ display: 'inline' }}>
            <input type="hidden" name="_token" value={document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? ''} />
            <button type="submit" style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--color-danger)', fontSize: '0.8rem', padding: '0.25rem 0.5rem' }}>
              خروج
            </button>
          </form>
        </div>
      )}
    </header>
  );
}

function trimStr(str: string): string {
  return str.trim();
}
