import { Link, usePage } from '@inertiajs/react';
import { useEffect, useState } from 'react';
import { tehranTimeHM, todayJalaliLong } from '@/lib/persianDate';
import { avatarColor, initials, roleLabel } from '@/lib/roles';
import { getStoredTheme, setTheme, type Theme } from '@/lib/theme';
import { NotificationBell } from './NotificationBell';

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;
};

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

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

  const displayName = user
    ? (`${user.firstName} ${user.lastName}`.trim() || user.username)
    : null;
  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(' — ')
    : 'پروفایل من';

  const [now, setNow] = useState(() => ({ date: todayJalaliLong(), time: tehranTimeHM() }));
  useEffect(() => {
    const timer = setInterval(() => {
      setNow({ date: todayJalaliLong(), time: tehranTimeHM() });
    }, 30_000);
    return () => clearInterval(timer);
  }, []);

  const [theme, setThemeState] = useState<Theme>(() => getStoredTheme());
  const toggleTheme = () => {
    const next: Theme = theme === 'dark' ? 'light' : 'dark';
    setTheme(next);
    setThemeState(next);
  };

  return (
    <header className="dashboard-topbar">
      <div className="topbar-right">
        {onMenuToggle && (
          <button className="hamburger-btn" type="button" aria-label="باز کردن منو" onClick={onMenuToggle}>
            <span />
            <span />
            <span />
          </button>
        )}
        <h1>{title}</h1>
      </div>

      <div className="topbar-left">
        <span className="topbar-date" title="تاریخ و ساعت تهران">
          <i className="bi bi-calendar3" aria-hidden="true" />
          {now.date}
          <span className="topbar-clock">{now.time}</span>
        </span>

        <NotificationBell />

        <button
          type="button"
          className="topbar-theme-btn"
          onClick={toggleTheme}
          aria-label={theme === 'dark' ? 'حالت روشن' : 'حالت تاریک'}
          title={theme === 'dark' ? 'حالت روشن' : 'حالت تاریک'}
        >
          <i className={`bi ${theme === 'dark' ? 'bi-sun' : 'bi-moon-stars'}`} />
        </button>

        {displayName && (
          <div className="topbar-user">
            <Link href="/profile" className="topbar-user-link" title={profileTitle}>
              {user?.avatarUrl ? (
                <span className="topbar-avatar avatar--photo">
                  <img src={user.avatarUrl} alt={displayName} />
                </span>
              ) : (
                <span className="topbar-avatar" style={{ background: avatarColor(displayName) }}>
                  {initials(displayName)}
                </span>
              )}
              {profileAttention && (
                <span
                  className={`profile-attention-dot profile-attention-dot--${profileAttention.severity}`}
                  aria-label="پروفایل نیاز به تکمیل دارد"
                />
              )}
              <span className="topbar-user-meta">
                <strong>{displayName}</strong>
                <small>{roleLabel(user?.roleKey)}{user?.schoolName ? ` · ${user.schoolName}` : ''}</small>
              </span>
            </Link>
          </div>
        )}
      </div>
    </header>
  );
}
