import { Head, Link, usePage } from '@inertiajs/react';
import type { CSSProperties } from 'react';
import { BrandMark } from '@/Components/Brand/BrandMark';
import { persianDigits } from '@/lib/persianDate';

type Props = {
  status: number;
  detail?: string | null;
};

type ErrorSpec = {
  title: string;
  desc: string;
  icon: string;
  /** Accent hue for this status — drives the numeral, glow, and icon chip. */
  accent: string;
};

const SPECS: Record<number, ErrorSpec> = {
  403: {
    title: 'دسترسی ندارید',
    desc: 'این بخش برای حساب شما فعال نیست. اگر فکر می‌کنید اشتباهی رخ داده، با مدیر مدرسه هماهنگ کنید.',
    icon: 'bi-shield-lock',
    accent: '#d97706',
  },
  404: {
    title: 'صفحه پیدا نشد',
    desc: 'نشانی‌ای که دنبال آن بودید وجود ندارد یا جابه‌جا شده است.',
    icon: 'bi-compass',
    accent: '#0EA678',
  },
  429: {
    title: 'درخواست بیش از حد',
    desc: 'در زمان کوتاهی درخواست زیادی فرستاده شد. کمی صبر کنید و دوباره تلاش کنید.',
    icon: 'bi-hourglass-split',
    accent: '#7c3aed',
  },
  500: {
    title: 'خطای داخلی سرور',
    desc: 'مشکلی در سرور رخ داد و تیم فنی در جریان است. چند دقیقه دیگر دوباره امتحان کنید.',
    icon: 'bi-cone-striped',
    accent: '#ef4444',
  },
  503: {
    title: 'سرویس موقتاً در دسترس نیست',
    desc: 'سامانه در حال به‌روزرسانی است. به‌زودی برمی‌گردیم.',
    icon: 'bi-tools',
    accent: '#64748b',
  },
};

const FALLBACK: ErrorSpec = {
  title: 'خطایی رخ داد',
  desc: 'مشکلی پیش آمد. دوباره تلاش کنید.',
  icon: 'bi-exclamation-triangle',
  accent: '#ef4444',
};

export default function ErrorPage({ status, detail }: Props) {
  const { props } = usePage<{ auth?: { user?: { roleKey: string } | null } }>();
  const roleKey = props.auth?.user?.roleKey;
  const spec = SPECS[status] ?? FALLBACK;

  // Send people to the dashboard their role actually owns.
  const home =
    roleKey === 'super_admin' ? '/super-admin'
    : roleKey === 'teacher' ? '/teacher'
    : roleKey === 'student' ? '/student'
    : roleKey ? '/school'
    : '/login';

  return (
    <>
      <Head title={`${status} — ${spec.title}`} />

      <div className="errpage" style={{ '--err-accent': spec.accent } as CSSProperties}>
        <div className="errpage-glow" aria-hidden="true" />

        <div className="errpage-card">
          <div className="errpage-brand">
            <BrandMark href={home} />
          </div>

          <div className="errpage-badge" aria-hidden="true">
            <i className={`bi ${spec.icon}`} />
          </div>

          <div className="errpage-code" aria-hidden="true">{persianDigits(status)}</div>
          <div className="errpage-rule" aria-hidden="true" />

          <h1 className="errpage-title">{spec.title}</h1>
          <p className="errpage-desc">{detail || spec.desc}</p>

          <Link href={home} className="errpage-btn">
            <i className="bi bi-arrow-right" aria-hidden="true" />
            بازگشت به داشبورد
          </Link>
        </div>
      </div>
    </>
  );
}
