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

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

type Props = {
  totals: {
    schools: number;
    activeSchools: number;
    activeLicenses: number;
    smsThisMonth: number;
    totalStudents: number;
    totalTeachers: number;
  };
  smsChart: ChartPoint[];
  chargeChart: ChartPoint[];
  licenseChart: ChartPoint[];
  schoolChart: ChartPoint[];
  topSmsBySchool: Array<{ school: string; sms: number }>;
  moduleCounts: Array<{ module: string; schools: number }>;
};

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 style={{ display: 'flex', alignItems: 'flex-end', gap: '0.4rem', height: 120 }}>
        {data.map((point) => (
          <div
            key={point.label}
            style={{ display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'center', flex: 1 }}
            title={`${point.label}: ${formatCount(point.value)}`}
          >
            <span
              style={{
                fontSize: '0.65rem',
                color: 'var(--color-text-muted)',
                marginBottom: '0.2rem',
                display: point.value > 0 ? 'block' : 'none',
              }}
            >
              {formatCount(point.value)}
            </span>
            <div
              style={{
                background: color ?? 'linear-gradient(180deg, var(--color-accent), var(--color-primary))',
                borderRadius: '4px 4px 0 0',
                width: '100%',
                height: `${Math.max(point.value > 0 ? 6 : 2, Math.round((point.value / max) * 100))}%`,
              }}
            />
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        {data.map((point) => (
          <span key={point.label} style={{ fontSize: '0.68rem', color: 'var(--color-text-muted)', textAlign: 'center', flex: 1 }}>
            {point.label.slice(5)}
          </span>
        ))}
      </div>
    </div>
  );
}

function ProgressBar({ value, max, color }: { value: number; max: number; color?: string }) {
  const pct = max > 0 ? Math.round((value / max) * 100) : 0;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
      <div style={{ flex: 1, background: 'var(--color-surface-muted)', borderRadius: 999, height: 8, overflow: 'hidden' }}>
        <div
          style={{
            height: '100%',
            width: `${pct}%`,
            background: color ?? 'var(--color-primary)',
            borderRadius: 999,
            transition: 'width 0.4s',
          }}
        />
      </div>
      <span style={{ fontSize: '0.82rem', fontWeight: 700, color: 'var(--color-text-muted)', minWidth: 36, textAlign: 'left' }}>
        {formatCount(value)}
      </span>
    </div>
  );
}

export default function Reports({ totals, smsChart, chargeChart, licenseChart, schoolChart, topSmsBySchool, moduleCounts }: Props) {
  const maxSms = Math.max(...topSmsBySchool.map((r) => r.sms), 1);
  const maxModule = Math.max(...moduleCounts.map((r) => r.schools), 1);

  return (
    <AppLayout title="گزارش‌های مدیر کل">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>
              <i className="bi bi-bar-chart" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />
              گزارش‌های سیستم
            </h2>
            <p>آمار کلی، مصرف پیامک، مجوزها و ماژول‌های فعال در ۶ ماه اخیر.</p>
          </div>
          <div className="action-row">
            <a className="btn btn-ghost" href="/super-admin">
              <i className="bi bi-arrow-right" /> داشبورد
            </a>
          </div>
        </section>

        {/* KPI row */}
        <section className="dashboard-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))' }}>
          {[
            { label: 'کل مدارس', value: totals.schools, icon: 'bi-building', color: undefined },
            { label: 'مدارس فعال', value: totals.activeSchools, icon: 'bi-building-check', color: 'var(--color-primary)' },
            { label: 'مجوزهای فعال', value: totals.activeLicenses, icon: 'bi-patch-check', color: 'var(--color-accent)' },
            { label: 'پیامک این ماه', value: totals.smsThisMonth, icon: 'bi-chat-dots', color: undefined },
            { label: 'کل دانش‌آموزان', value: totals.totalStudents, icon: 'bi-person-badge', color: undefined },
            { label: 'کل معلمان', value: totals.totalTeachers, icon: 'bi-person-workspace', color: undefined },
          ].map((kpi) => (
            <article key={kpi.label} className="metric-card">
              <span>
                <i className={`bi ${kpi.icon}`} style={{ marginLeft: '0.3rem', color: kpi.color }} />
                {kpi.label}
              </span>
              <strong style={{ color: kpi.color }}>{formatCount(kpi.value)}</strong>
            </article>
          ))}
        </section>

        {/* Charts row */}
        <div className="card-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))' }}>
          <article className="panel-card">
            <h3 style={{ marginBottom: '1rem', fontSize: '0.9rem' }}>
              <i className="bi bi-chat-dots" style={{ marginLeft: '0.4rem', color: 'var(--color-primary)' }} />
              مصرف پیامک — ۶ ماه اخیر
            </h3>
            <BarChart data={smsChart} />
          </article>
          <article className="panel-card">
            <h3 style={{ marginBottom: '1rem', fontSize: '0.9rem' }}>
              <i className="bi bi-wallet2" style={{ marginLeft: '0.4rem', color: 'var(--color-accent)' }} />
              شارژ پیامک (تومان) — ۶ ماه اخیر
            </h3>
            <BarChart
              data={chargeChart}
              color="linear-gradient(180deg, #f59e0b, #d97706)"
            />
          </article>
          <article className="panel-card">
            <h3 style={{ marginBottom: '1rem', fontSize: '0.9rem' }}>
              <i className="bi bi-patch-check" style={{ marginLeft: '0.4rem', color: '#6366f1' }} />
              مجوزهای جدید — ۶ ماه اخیر
            </h3>
            <BarChart
              data={licenseChart}
              color="linear-gradient(180deg, #818cf8, #6366f1)"
            />
          </article>
          <article className="panel-card">
            <h3 style={{ marginBottom: '1rem', fontSize: '0.9rem' }}>
              <i className="bi bi-building-add" style={{ marginLeft: '0.4rem', color: 'var(--color-accent-hover)' }} />
              مدارس جدید — ۶ ماه اخیر
            </h3>
            <BarChart
              data={schoolChart}
              color="linear-gradient(180deg, var(--color-accent-hover), var(--color-accent))"
            />
          </article>
        </div>

        {/* برترین مصرف پیامک + module usage */}
        <div className="split-panel">
          <article className="panel-card">
            <h3 style={{ marginBottom: '1.25rem', fontSize: '0.9rem' }}>
              <i className="bi bi-trophy" style={{ marginLeft: '0.4rem', color: '#f59e0b' }} />
              برترین مصرف‌کنندگان پیامک (۶ ماه)
            </h3>
            {topSmsBySchool.length === 0 ? (
              <p style={{ color: 'var(--color-text-muted)', fontSize: '0.875rem' }}>داده‌ای موجود نیست.</p>
            ) : (
              <div style={{ display: 'grid', gap: '0.75rem' }}>
                {topSmsBySchool.map((row) => (
                  <div key={row.school}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.25rem', fontSize: '0.85rem' }}>
                      <span style={{ fontWeight: 600 }}>{row.school}</span>
                    </div>
                    <ProgressBar value={row.sms} max={maxSms} />
                  </div>
                ))}
              </div>
            )}
          </article>

          <article className="panel-card">
            <h3 style={{ marginBottom: '1.25rem', fontSize: '0.9rem' }}>
              <i className="bi bi-grid-3x3-gap" style={{ marginLeft: '0.4rem', color: 'var(--color-primary)' }} />
              محبوب‌ترین ماژول‌ها
            </h3>
            {moduleCounts.length === 0 ? (
              <p style={{ color: 'var(--color-text-muted)', fontSize: '0.875rem' }}>ماژولی فعال نیست.</p>
            ) : (
              <div style={{ display: 'grid', gap: '0.75rem' }}>
                {moduleCounts.map((row) => (
                  <div key={row.module}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.25rem', fontSize: '0.85rem' }}>
                      <span style={{ fontWeight: 600 }}>{row.module}</span>
                      <span style={{ color: 'var(--color-text-muted)' }}>{row.schools} مدرسه</span>
                    </div>
                    <ProgressBar
                      value={row.schools}
                      max={maxModule}
                      color="linear-gradient(90deg, var(--color-accent), var(--color-primary))"
                    />
                  </div>
                ))}
              </div>
            )}
          </article>
        </div>

        {/* Quick links */}
        <div className="action-row">
          <a className="btn btn-soft" href="/super-admin/sms-usage">
            <i className="bi bi-chat-square-dots" /> جزئیات پیامک همه مدارس
          </a>
          <a className="btn btn-ghost" href="/super-admin/audit-logs">
            <i className="bi bi-shield-check" /> لاگ‌های سیستم
          </a>
          <a className="btn btn-ghost" href="/super-admin/schools">
            <i className="bi bi-building" /> مدیریت مدارس
          </a>
        </div>
      </div>
    </AppLayout>
  );
}
