import { Head, Link, router, usePage } from '@inertiajs/react';
import { IosInstallPrompt } from '@/Components/IosInstallPrompt';
import { useEffect, useRef, useState } from 'react';
import type { PropsWithChildren } from 'react';
import { BrandMark } from '@/Components/Brand/BrandMark';
import { FlashToast } from '@/Components/UI/FlashToast';
import { avatarColor, initials, roleLabel } from '@/lib/roles';
import { DashboardSidebar } from './DashboardSidebar';
import { Topbar } from './Topbar';

type Props = PropsWithChildren<{
  title: string;
}>;

type AuthUser = {
  firstName: string;
  lastName: string;
  username: string;
  roleKey: string;
  schoolName: string | null;
  avatarUrl: string | null;
  profileCompletion?: {
    needsAttention: boolean;
    mustChangePassword: boolean;
    missingFields: Array<{ key: string; label: string }>;
    severity: 'warning' | 'danger';
  } | null;
};

function sendHeartbeat() {
  const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
  fetch('/heartbeat', {
    method: 'POST',
    headers: { 'X-CSRF-TOKEN': token, 'Content-Type': 'application/json', Accept: 'application/json' },
    body: JSON.stringify({ page: window.location.pathname }),
    credentials: 'same-origin',
  }).catch(() => {});
}

function SidebarUserCard() {
  const { props } = usePage<{ auth?: { user?: AuthUser } }>();
  const user = props.auth?.user;
  if (!user) return null;

  const name = `${user.firstName} ${user.lastName}`.trim() || user.username;
  const profileAttention = user.profileCompletion?.needsAttention ? user.profileCompletion : null;
  const profileTitle = profileAttention
    ? [
        profileAttention.mustChangePassword ? 'تغییر رمز عبور لازم است' : null,
        profileAttention.missingFields.length > 0 ? `اطلاعات ناقص: ${profileAttention.missingFields.map((field) => field.label).join('، ')}` : null,
      ].filter(Boolean).join(' — ')
    : 'پروفایل من';

  return (
    <div className="sidebar-user">
      <Link href="/profile" className="sidebar-user-link" title={profileTitle}>
        {user.avatarUrl ? (
          <span className="sidebar-avatar avatar--photo">
            <img src={user.avatarUrl} alt={name} />
          </span>
        ) : (
          <span className="sidebar-avatar" style={{ background: avatarColor(name) }}>{initials(name)}</span>
        )}
        <span className="sidebar-user-meta">
          <strong>{name}</strong>
          <small>{roleLabel(user.roleKey)}{user.schoolName ? ` · ${user.schoolName}` : ''}</small>
        </span>
        {profileAttention && (
          <span
            className={`profile-attention-dot profile-attention-dot--${profileAttention.severity}`}
            aria-label="پروفایل نیاز به تکمیل دارد"
          />
        )}
      </Link>
      <form method="POST" action="/logout">
        <input type="hidden" name="_token" value={document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? ''} />
        <button type="submit" className="sidebar-logout" aria-label="خروج از حساب" title="خروج از حساب">
          <i className="bi bi-box-arrow-left" />
        </button>
      </form>
    </div>
  );
}

export function AppLayout({ title, children }: Props) {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  useEffect(() => {
    sendHeartbeat();
    intervalRef.current = setInterval(sendHeartbeat, 120_000);
    return () => { if (intervalRef.current) clearInterval(intervalRef.current); };
  }, []);

  // Force full reload when browser restores this page from bfcache (back/forward button).
  // Without this, hitting Back after logout shows a stale authenticated page.
  useEffect(() => {
    const handlePageShow = (e: PageTransitionEvent) => {
      if (e.persisted) window.location.reload();
    };
    window.addEventListener('pageshow', handlePageShow);
    return () => window.removeEventListener('pageshow', handlePageShow);
  }, []);

  useEffect(() => {
    const stop = router.on('navigate', () => setSidebarOpen(false));
    return stop;
  }, []);

  useEffect(() => {
    document.body.style.overflow = sidebarOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [sidebarOpen]);

  return (
    <div className="dashboard-shell">
      <Head title={title}>
        <meta name="description" content={`دانشیار من | ${title}؛ پنل فارسی اتوماسیون هوشمند مدارس`} />
      </Head>

      {sidebarOpen && (
        <div className="sidebar-overlay active" role="button" tabIndex={-1} aria-label="بستن منو" onClick={() => setSidebarOpen(false)} onKeyDown={() => setSidebarOpen(false)} />
      )}

      <aside className={`dashboard-sidebar${sidebarOpen ? ' sidebar-open' : ''}`}>
        <div className="sidebar-header">
          <BrandMark href="/dashboard" />
          <button className="sidebar-close-btn" type="button" aria-label="بستن منو" onClick={() => setSidebarOpen(false)}>
            <i className="bi bi-x-lg" />
          </button>
        </div>
        <DashboardSidebar />
        <SidebarUserCard />
      </aside>

      <main className="dashboard-main">
        <Topbar title={title} onMenuToggle={() => setSidebarOpen(true)} />
        <div className="dashboard-content">
          {children}
        </div>
      </main>

      <FlashToast />
      <IosInstallPrompt />
    </div>
  );
}
