import { Link } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { PageHeader } from '@/Components/UI/PageHeader';
import { StatCard } from '@/Components/UI/StatCard';
import { BarsChart, DonutChart, TrendAreaChart } from '@/Components/Charts/PanelCharts';
import { formatCount } from '@/lib/formatters';
import { jalaliMonthNames, toJalali } from '@/lib/persianDate';

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

/** «2026-07» → «تیر» */
function jalaliMonthLabel(label: string): string {
  const match = label.match(/^(\d{4})-(\d{2})/);
  if (!match) return label;
  const j = toJalali(Number(match[1]), Number(match[2]), 15);
  return jalaliMonthNames[j.jm - 1];
}

export default function Dashboard({ metrics, smsChart, schoolChart, licenseWarnings, recentLogins }: Props) {
  const smsData = smsChart.map((point) => ({ ...point, label: jalaliMonthLabel(point.label) }));
  const schoolData = schoolChart.map((point) => ({ ...point, label: jalaliMonthLabel(point.label) }));
  const schoolsDonut = [
    { label: 'مدارس فعال', value: metrics.activeSchools },
    { label: 'مدارس غیرفعال', value: metrics.inactiveSchools },
  ];

  return (
    <AppLayout title="داشبورد مدیر کل">
      <div className="page-stack">
        <PageHeader
          title="داشبورد مدیر کل"
          icon="bi-speedometer2"
          description="نمای زنده کل سامانه: وضعیت مدارس، کاربران، مصرف پیامک و رویدادهای اخیر. برای جزئیات هر بخش روی کارت مربوطه کلیک کنید."
        />

        <section className="dashboard-grid dashboard-grid--animated" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(210px, 1fr))' }}>
          <StatCard icon="bi-building-check" label="مدارس فعال" value={metrics.activeSchools} tone="primary" href="/super-admin/schools" />
          <StatCard icon="bi-building-x" label="مدارس غیرفعال" value={metrics.inactiveSchools} tone="danger" href="/super-admin/schools" />
          <StatCard icon="bi-person-badge" label="کل دانش‌آموزان" value={metrics.totalStudents} tone="info" />
          <StatCard icon="bi-person-workspace" label="کل معلمان" value={metrics.totalTeachers} tone="violet" />
          <StatCard icon="bi-people" label="کل کاربران" value={metrics.totalUsers} tone="info" />
          <StatCard icon="bi-chat-dots" label="پیامک ارسالی این ماه" value={metrics.smsUsedThisMonth} tone="primary" href="/super-admin/sms-usage" />
          <StatCard
            icon="bi-calendar-x"
            label="مجوز رو به اتمام"
            value={metrics.expiringLicenses}
            tone={metrics.expiringLicenses > 0 ? 'warning' : 'primary'}
            hint="۳۰ روز آینده"
            href="/super-admin/schools"
          />
        </section>

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

        <div className="card-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 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)' }} />
              مصرف پیامک — ۶ ماه اخیر
            </h3>
            <BarsChart data={smsData} />
          </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-hover)' }} />
              مدارس جدید — ۶ ماه اخیر
            </h3>
            <TrendAreaChart data={schoolData} color="#0EA5E9" />
          </article>
          <article className="panel-card">
            <h3 style={{ marginBottom: '1rem', fontSize: '0.95rem' }}>
              <i className="bi bi-pie-chart" style={{ marginLeft: '0.4rem', color: '#8B5CF6' }} />
              وضعیت مدارس
            </h3>
            <DonutChart data={schoolsDonut} />
          </article>
        </div>

        <section className="panel-card">
          <h2 style={{ marginBottom: '1rem' }}>
            <i className="bi bi-clock-history" style={{ marginLeft: '0.4rem' }} /> ورودهای اخیر
          </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, index) => (
                    <tr key={index}>
                      <td>{log.username}</td>
                      <td>{log.schoolName ?? '—'}</td>
                      <td>
                        <span className={`badge ${log.status === 'success' ? 'badge-success' : 'badge-danger'}`}>
                          {log.status === 'success' ? <><i className="bi bi-check-lg" /> موفق</> : <><i className="bi bi-x-lg" /> ناموفق</>}
                        </span>
                      </td>
                      <td style={{ fontFamily: 'monospace', fontSize: '0.85rem', direction: 'ltr', textAlign: 'right' }}>{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' }}>
            <Link className="btn btn-soft" href="/super-admin/audit-logs">مشاهده کامل رویدادها</Link>
          </div>
        </section>

        <section className="dashboard-grid dashboard-grid--animated" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))' }}>
          <StatCard icon="bi-building" label="مدیریت مدارس" value="ساخت و تمدید مجوز" tone="primary" href="/super-admin/schools" />
          <StatCard icon="bi-grid-3x3-gap" label="ماژول‌ها" value="قابلیت‌های قابل فروش" tone="violet" href="/super-admin/modules" />
          <StatCard icon="bi-database" label="پایگاه داده" value="مرور همه جدول‌ها" tone="info" href="/super-admin/database" />
          <StatCard icon="bi-journal-check" label="رویدادهای سیستم" value="لاگ ورود و تغییرات" tone="warning" href="/super-admin/audit-logs" />
        </section>
      </div>
    </AppLayout>
  );
}
