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

type LicenseWarning = {
  schoolName: string;
  expiresAt: string;
  daysLeft: number;
};

type RecentLogin = {
  username: string;
  schoolName: string | null;
  status: 'success' | 'failed';
  ip: string | null;
  createdAt: string;
};

type ChartPoint = {
  label: string;
  value: number;
};

type Props = {
  metrics: {
    activeSchools: number;
    inactiveSchools: number;
    totalStudents: number;
    totalTeachers: number;
    totalUsers: number;
    smsUsedThisMonth: number;
    expiringLicenses: number;
  };
  smsChart: ChartPoint[];
  schoolChart: ChartPoint[];
  licenseWarnings: LicenseWarning[];
  recentLogins: RecentLogin[];
};

function BarChart({ data, color }: { data: ChartPoint[]; color?: string }) {
  const max = Math.max(...data.map((d) => d.value), 1);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
      <div className="usage-chart" style={{ height: 120 }}>
        {data.map((point) => (
          <div
            key={point.label}
            style={{
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'flex-end',
              alignItems: 'center',
              flex: 1,
              gap: '0.25rem',
            }}
            title={`${point.label}: ${formatCount(point.value)}`}
          >
            <span
              style={{
                background: color ?? 'linear-gradient(180deg, var(--color-accent), var(--color-primary))',
                borderRadius: '4px 4px 0 0',
                width: '100%',
                height: `${Math.max(4, Math.round((point.value / max) * 100))}%`,
                minHeight: point.value > 0 ? 4 : 2,
              }}
            />
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        {data.map((point) => (
          <span key={point.label} style={{ fontSize: '0.7rem', color: 'var(--color-text-muted)', textAlign: 'center', flex: 1 }}>
            {point.label.slice(5)}
          </span>
        ))}
      </div>
    </div>
  );
}

export default function Dashboard({ metrics, smsChart, schoolChart, licenseWarnings, recentLogins }: Props) {
  return (
    <AppLayout title="داشبورد Super Admin">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>داشبورد Super Admin</h2>
            <p>آمار کلی سیستم، وضعیت مدارس و فعالیت‌های اخیر.</p>
          </div>
        </section>

        <section className="dashboard-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))' }}>
          <article className="metric-card">
            <span><i className="bi bi-building-check" /> مدارس فعال</span>
            <strong>{formatCount(metrics.activeSchools)}</strong>
          </article>
          <article className="metric-card">
            <span><i className="bi bi-building-x" /> مدارس غیرفعال</span>
            <strong>{formatCount(metrics.inactiveSchools)}</strong>
          </article>
          <article className="metric-card">
            <span><i className="bi bi-person-badge" /> کل دانش‌آموزان</span>
            <strong>{formatCount(metrics.totalStudents)}</strong>
          </article>
          <article className="metric-card">
            <span><i className="bi bi-person-workspace" /> کل معلمان</span>
            <strong>{formatCount(metrics.totalTeachers)}</strong>
          </article>
          <article className="metric-card">
            <span><i className="bi bi-people" /> کل کاربران</span>
            <strong>{formatCount(metrics.totalUsers)}</strong>
          </article>
          <article className="metric-card">
            <span><i className="bi bi-chat-dots" /> SMS ارسالی این ماه</span>
            <strong>{formatCount(metrics.smsUsedThisMonth)}</strong>
          </article>
          <article className="metric-card" style={{ borderColor: metrics.expiringLicenses > 0 ? 'var(--color-warning)' : undefined }}>
            <span><i className="bi bi-calendar-x" /> مجوز رو به اتمام</span>
            <strong style={{ color: metrics.expiringLicenses > 0 ? 'var(--color-warning)' : undefined }}>
              {formatCount(metrics.expiringLicenses)}
            </strong>
          </article>
        </section>

        {licenseWarnings.length > 0 && (
          <section className="panel-card" style={{ borderColor: 'var(--color-warning)' }}>
            <h2 style={{ marginBottom: '1rem' }}>
              <i className="bi bi-exclamation-triangle" /> مجوزهای رو به انقضا (۳۰ روز آینده)
            </h2>
            <div className="table-wrap">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>مدرسه</th>
                    <th>تاریخ انقضا</th>
                    <th>روزهای باقی‌مانده</th>
                  </tr>
                </thead>
                <tbody>
                  {licenseWarnings.map((w, i) => (
                    <tr key={i}>
                      <td>{w.schoolName}</td>
                      <td>{w.expiresAt}</td>
                      <td>
                        <span className={`badge ${w.daysLeft <= 7 ? 'badge-danger' : 'badge-warning'}`}>
                          {w.daysLeft} روز
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className="action-row" style={{ marginTop: '1rem' }}>
              <a className="btn btn-soft" href="/super-admin/schools">مدیریت مجوزها</a>
            </div>
          </section>
        )}

        <section className="panel-card">
          <h2 style={{ marginBottom: '1rem' }}>
            <i className="bi bi-clock-history" /> ورودهای اخیر
          </h2>
          {recentLogins.length === 0 ? (
            <p style={{ color: 'var(--color-text-muted)' }}>لاگ ورودی وجود ندارد.</p>
          ) : (
            <div className="table-wrap">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>کاربر</th>
                    <th>مدرسه</th>
                    <th>وضعیت</th>
                    <th>IP</th>
                    <th>زمان</th>
                  </tr>
                </thead>
                <tbody>
                  {recentLogins.map((log, i) => (
                    <tr key={i}>
                      <td>{log.username}</td>
                      <td>{log.schoolName ?? '—'}</td>
                      <td>
                        <span className={`badge ${log.status === 'success' ? 'badge-success' : 'badge-danger'}`}>
                          {log.status === 'success' ? 'موفق' : 'ناموفق'}
                        </span>
                      </td>
                      <td style={{ fontFamily: 'monospace', fontSize: '0.85rem' }}>{log.ip ?? '—'}</td>
                      <td style={{ color: 'var(--color-text-muted)', fontSize: '0.85rem' }}>{log.createdAt}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
          <div className="action-row" style={{ marginTop: '1rem' }}>
            <a className="btn btn-soft" href="/super-admin/audit-logs">مشاهده کامل لاگ‌ها</a>
          </div>
        </section>

        <div className="card-grid" style={{ gridTemplateColumns: '1fr 1fr' }}>
          <article className="panel-card">
            <h3 style={{ marginBottom: '1rem', fontSize: '0.95rem' }}>
              <i className="bi bi-chat-dots" style={{ marginLeft: '0.4rem', color: 'var(--color-primary)' }} />
              مصرف SMS — ۶ ماه اخیر
            </h3>
            <BarChart data={smsChart} />
          </article>
          <article className="panel-card">
            <h3 style={{ marginBottom: '1rem', fontSize: '0.95rem' }}>
              <i className="bi bi-building-add" style={{ marginLeft: '0.4rem', color: 'var(--color-accent)' }} />
              مدارس جدید — ۶ ماه اخیر
            </h3>
            <BarChart
              data={schoolChart}
              color="linear-gradient(180deg, var(--color-accent-hover), var(--color-accent))"
            />
          </article>
        </div>

        <section className="dashboard-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))' }}>
          <a className="metric-card" href="/super-admin/schools" style={{ textDecoration: 'none', cursor: 'pointer' }}>
            <span><i className="bi bi-building" /> مدیریت مدارس</span>
            <strong style={{ fontSize: '0.95rem' }}>ساخت، تمدید مجوز، SMS</strong>
          </a>
          <a className="metric-card" href="/super-admin/modules" style={{ textDecoration: 'none', cursor: 'pointer' }}>
            <span><i className="bi bi-grid-3x3-gap" /> ماژول‌ها</span>
            <strong style={{ fontSize: '0.95rem' }}>مدیریت ماژول‌های قابل فروش</strong>
          </a>
          <a className="metric-card" href="/super-admin/sms-usage" style={{ textDecoration: 'none', cursor: 'pointer' }}>
            <span><i className="bi bi-chat-square-dots" /> مصرف SMS</span>
            <strong style={{ fontSize: '0.95rem' }}>آمار SMS همه مدارس</strong>
          </a>
          <a className="metric-card" href="/super-admin/audit-logs" style={{ textDecoration: 'none', cursor: 'pointer' }}>
            <span><i className="bi bi-journal-check" /> لاگ‌های سیستم</span>
            <strong style={{ fontSize: '0.95rem' }}>audit و login logs</strong>
          </a>
        </section>
      </div>
    </AppLayout>
  );
}
