import { router } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';

type SubjectStat = {
  subjectId: number;
  subject: string;
  count: number;
  avg: number;
  min: number;
  max: number;
  passRate: number;
  avgRaw: number;
  maxScore: number;
};

type Overall = {
  count: number;
  avg: number;
  min: number;
  max: number;
  passRate: number;
};

type Classroom = { id: number; name: string };

type Props = {
  classrooms: Classroom[];
  classroomId: number | null;
  totalStudents: number;
  subjectStats: SubjectStat[];
  overall: Overall | null;
};

function pctBar(pct: number) {
  const color = pct >= 70 ? '#16a34a' : pct >= 50 ? '#d97706' : '#dc2626';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
      <div style={{ flex: 1, height: 8, background: 'var(--color-border)', borderRadius: 4, overflow: 'hidden' }}>
        <div style={{ width: `${Math.min(pct, 100)}%`, height: '100%', background: color, borderRadius: 4, transition: 'width 0.3s' }} />
      </div>
      <span style={{ fontWeight: 600, color, minWidth: 40, fontSize: '0.875rem' }}>{pct}%</span>
    </div>
  );
}

export default function ClassStats({ classrooms, classroomId, totalStudents, subjectStats, overall }: Props) {
  function changeClass(id: string) {
    router.get('/teacher/class-stats', { classroom_id: id }, { preserveScroll: false });
  }

  return (
    <AppLayout title="آمار نمرات کلاس">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2><i className="bi bi-bar-chart-line" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />آمار نمرات کلاس</h2>
            <p>میانگین، کمترین، بیشترین و نرخ قبولی به تفکیک درس</p>
          </div>
          <select
            className="form-control"
            style={{ minWidth: 160 }}
            value={classroomId ?? ''}
            onChange={(e) => changeClass(e.target.value)}
          >
            <option value="">انتخاب کلاس</option>
            {classrooms.map((c) => (
              <option key={c.id} value={c.id}>{c.name}</option>
            ))}
          </select>
        </section>

        {overall && (
          <section className="dashboard-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))' }}>
            {[
              { label: 'تعداد نمرات', value: overall.count, icon: 'bi-hash', color: 'var(--color-primary)' },
              { label: 'میانگین کل', value: `${overall.avg}%`, icon: 'bi-graph-up', color: overall.avg >= 50 ? '#16a34a' : '#dc2626' },
              { label: 'نرخ قبولی', value: `${overall.passRate}%`, icon: 'bi-check2-circle', color: overall.passRate >= 70 ? '#16a34a' : '#d97706' },
              { label: 'کمترین', value: `${overall.min}%`, icon: 'bi-arrow-down', color: '#dc2626' },
              { label: 'بیشترین', value: `${overall.max}%`, icon: 'bi-arrow-up', color: '#16a34a' },
            ].map((stat) => (
              <div key={stat.label} className="panel-card" style={{ textAlign: 'center' }}>
                <i className={`bi ${stat.icon}`} style={{ fontSize: '1.5rem', color: stat.color, display: 'block', marginBottom: '0.25rem' }} />
                <div style={{ fontSize: '1.4rem', fontWeight: 700, color: stat.color }}>{stat.value}</div>
                <div style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)', marginTop: '0.2rem' }}>{stat.label}</div>
              </div>
            ))}
          </section>
        )}

        {subjectStats.length === 0 ? (
          <div className="panel-card" style={{ textAlign: 'center', padding: '2.5rem', color: 'var(--color-text-muted)' }}>
            <i className="bi bi-bar-chart" style={{ fontSize: '2.5rem', display: 'block', marginBottom: '0.75rem' }} />
            {classroomId ? 'نمره تایید‌شده‌ای برای آمارگیری وجود ندارد' : 'یک کلاس انتخاب کنید'}
          </div>
        ) : (
          <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ padding: '0.75rem 1rem', borderBottom: '1px solid var(--color-border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <strong>آمار به تفکیک درس</strong>
              <span style={{ fontSize: '0.85rem', color: 'var(--color-text-muted)' }}>{totalStudents} دانش‌آموز</span>
            </div>
            <div style={{ overflowX: 'auto' }}>
              <table className="data-table" style={{ width: '100%' }}>
                <thead>
                  <tr>
                    <th>درس</th>
                    <th>تعداد نمره</th>
                    <th>میانگین</th>
                    <th>کمترین</th>
                    <th>بیشترین</th>
                    <th>نرخ قبولی</th>
                  </tr>
                </thead>
                <tbody>
                  {subjectStats.map((s) => (
                    <tr key={s.subjectId}>
                      <td style={{ fontWeight: 600 }}>{s.subject}</td>
                      <td style={{ fontVariantNumeric: 'tabular-nums' }}>{s.count}</td>
                      <td>
                        <div style={{ minWidth: 140 }}>
                          <div style={{ marginBottom: '0.2rem', fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>
                            {s.avgRaw}/{s.maxScore}
                          </div>
                          {pctBar(s.avg)}
                        </div>
                      </td>
                      <td style={{ color: '#dc2626', fontWeight: 600 }}>{s.min}%</td>
                      <td style={{ color: '#16a34a', fontWeight: 600 }}>{s.max}%</td>
                      <td>
                        <div style={{ minWidth: 120 }}>
                          {pctBar(s.passRate)}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
