import { useState } from 'react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { formatCount } from '@/lib/formatters';

type ImportantAnnouncement = {
  id: number;
  title: string;
  body: string;
  createdAt: string;
};

type Props = {
  metrics: {
    students: number;
    teachers: number;
    classes: number;
    smsBalance: number;
    activeExams: number;
    absencesToday: number;
  };
  tasks: Array<{ title: string; count: number; tone: string }>;
  activeModules: string[];
  importantAnnouncements: ImportantAnnouncement[];
  licenseWarning: string | null;
};

type MetricCard = {
  label: string;
  value: number;
  icon: string;
  accent?: boolean;
  href?: string;
};

export default function Dashboard({ metrics, tasks, activeModules, importantAnnouncements, licenseWarning }: Props) {
  const [dismissed, setDismissed] = useState<number[]>([]);
  const visibleAlerts = importantAnnouncements.filter((a) => !dismissed.includes(a.id));

  const cards: MetricCard[] = [
    { label: 'دانش‌آموزان', value: metrics.students, icon: 'bi-person-badge', href: '/school/students' },
    { label: 'معلمان', value: metrics.teachers, icon: 'bi-person-workspace', href: '/school/teachers' },
    { label: 'کلاس‌ها', value: metrics.classes, icon: 'bi-door-open', href: '/school/classes' },
    { label: 'SMS باقی‌مانده', value: metrics.smsBalance, icon: 'bi-wallet2', href: '/school/sms-wallet', accent: metrics.smsBalance < 100 },
    { label: 'امتحانات فعال', value: metrics.activeExams, icon: 'bi-pencil-square', href: '/school/grades' },
    { label: 'غیبت‌های امروز', value: metrics.absencesToday, icon: 'bi-clipboard-x', href: '/school/attendance', accent: metrics.absencesToday > 0 },
  ];

  return (
    <AppLayout title="داشبورد مدرسه">
      <div className="page-stack">
        {licenseWarning && (
          <div style={{ background: '#fee2e2', border: '1px solid #f87171', borderRadius: 'var(--radius-md)', padding: '0.875rem 1.25rem', display: 'flex', gap: '0.75rem', alignItems: 'flex-start' }}>
            <i className="bi bi-shield-exclamation" style={{ color: 'var(--color-danger)', fontSize: '1.1rem', flexShrink: 0, marginTop: '0.1rem' }} />
            <span><strong>هشدار مجوز: </strong>{licenseWarning}</span>
          </div>
        )}

        {visibleAlerts.map((alert) => (
          <div
            key={alert.id}
            style={{
              background: '#fef3c7',
              border: '1px solid #f59e0b',
              borderRadius: 'var(--radius-md)',
              padding: '1rem 1.25rem',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'flex-start',
              gap: '1rem',
            }}
          >
            <div>
              <strong style={{ display: 'block', marginBottom: '0.25rem' }}>
                <i className="bi bi-megaphone-fill" style={{ marginLeft: '0.4rem' }} />
                {alert.title}
              </strong>
              <span style={{ fontSize: '0.9rem' }}>{alert.body}</span>
              <span style={{ display: 'block', fontSize: '0.78rem', color: 'var(--color-text-muted)', marginTop: '0.25rem' }}>{alert.createdAt}</span>
            </div>
            <button
              style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: '1.2rem', flexShrink: 0 }}
              type="button"
              onClick={() => setDismissed((d) => [...d, alert.id])}
              aria-label="بستن"
            >
              <i className="bi bi-x" />
            </button>
          </div>
        ))}

        <section className="dashboard-grid">
          {cards.map((card) => {
            const Tag = card.href ? 'a' : 'article';
            return (
              <Tag
                key={card.label}
                className="metric-card"
                href={card.href}
                style={{
                  textDecoration: 'none',
                  cursor: card.href ? 'pointer' : 'default',
                  borderColor: card.accent ? 'var(--color-danger)' : undefined,
                  display: 'flex',
                  flexDirection: 'column',
                  gap: '0.75rem',
                }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <span style={{ fontSize: '0.875rem' }}>{card.label}</span>
                  <span style={{
                    background: card.accent ? '#fee2e2' : 'var(--color-primary-soft)',
                    borderRadius: 'var(--radius-sm)',
                    color: card.accent ? 'var(--color-danger)' : 'var(--color-primary)',
                    display: 'inline-flex',
                    fontSize: '1rem',
                    padding: '0.4rem',
                  }}>
                    <i className={`bi ${card.icon}`} />
                  </span>
                </div>
                <strong style={{ fontSize: '2rem', color: card.accent ? 'var(--color-danger)' : undefined }}>
                  {formatCount(card.value)}
                </strong>
              </Tag>
            );
          })}
        </section>

        <section className="split-panel">
          <article className="panel-card">
            <h2 style={{ marginBottom: '1rem', fontSize: '1.05rem' }}>
              <i className="bi bi-list-check" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />
              کارهای فوری
            </h2>
            {tasks.length === 0 ? (
              <p style={{ color: 'var(--color-text-muted)' }}>موردی برای پیگیری وجود ندارد.</p>
            ) : (
              <ul className="timeline-list">
                {tasks.map((task) => (
                  <li key={task.title}>
                    <span>{task.title}</span>
                    <span className={`status-pill ${task.tone === 'default' ? '' : task.tone}`}>{formatCount(task.count)}</span>
                  </li>
                ))}
              </ul>
            )}
          </article>

          <article className="panel-card">
            <h2 style={{ marginBottom: '1rem', fontSize: '1.05rem' }}>
              <i className="bi bi-puzzle" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />
              ماژول‌های فعال
            </h2>
            {activeModules.length === 0 ? (
              <p style={{ color: 'var(--color-text-muted)' }}>هنوز ماژول فعالی برای این مدرسه ثبت نشده است.</p>
            ) : (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem' }}>
                {activeModules.map((mod) => (
                  <span key={mod} className="badge badge-success" style={{ fontSize: '0.8rem' }}>
                    <i className="bi bi-check-circle" style={{ marginLeft: '0.3rem' }} />
                    {mod}
                  </span>
                ))}
              </div>
            )}
          </article>
        </section>
      </div>
    </AppLayout>
  );
}
