import { useState } from 'react';
import { router } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { UsageChart } from '@/Components/Charts/UsageChart';
import { JalaliDatePicker } from '@/Components/Forms/JalaliDatePicker';
import { formatCount } from '@/lib/formatters';

type GradeSummaryRow = { classroom: string; subject: string; count: number; avgPct: number; minPct: number; maxPct: number; passRate: number };
type AttendanceSummaryRow = { classroom: string; present: number; absent: number; late: number; excused: number; total: number; absenceRate: number };
type ExamRow = { title: string; classroom: string; subject: string; participants: number; avgPct: number | null };
type SmsSummary = { total: number; cost: number; daily: { day: string; count: number; cost: number }[] };

type Props = {
  metrics: { loginsToday: number; absencesToday: number; smsThisMonth: number | null; exportsThisMonth: number };
  usage: number[];
  gradeSummary: GradeSummaryRow[];
  attendanceSummary: AttendanceSummaryRow[];
  examSummary: ExamRow[];
  smsSummary: SmsSummary | null;
  isPrincipal: boolean;
  dateRange: { from: string; to: string };
};

type SectionKey = 'grades' | 'attendance' | 'exams' | 'sms' | 'activity';

export default function Reports({ metrics, usage, gradeSummary, attendanceSummary, examSummary, smsSummary, isPrincipal, dateRange }: Props) {
  const [from, setFrom] = useState(dateRange.from);
  const [to, setTo] = useState(dateRange.to);
  const [activeSection, setActiveSection] = useState<SectionKey>('grades');

  const max = Math.max(...usage, 1);
  const chartValues = usage.map((v) => Math.max(8, Math.round((v / max) * 100)));

  function applyDateRange() {
    router.get('/school/reports', { from, to }, { preserveScroll: true });
  }

  function exportHref(kind: string) {
    const params = new URLSearchParams({ from, to, export: kind });
    return `/school/reports?${params.toString()}`;
  }

  const sections: { key: SectionKey; label: string; icon: string; count?: number; hidden?: boolean }[] = [
    { key: 'grades', label: 'نمرات', icon: 'bi-patch-check', count: gradeSummary.length },
    { key: 'attendance', label: 'حضور', icon: 'bi-clipboard-check', count: attendanceSummary.length },
    { key: 'exams', label: 'امتحانات', icon: 'bi-pencil-square', count: examSummary.length },
    { key: 'activity', label: 'فعالیت', icon: 'bi-activity' },
    ...(isPrincipal ? [{ key: 'sms' as SectionKey, label: 'پیامک', icon: 'bi-chat-dots', count: smsSummary?.total }] : []),
  ];

  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>
        </section>

        {/* Date range picker */}
        <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap', alignItems: 'flex-end' }} className="panel-card">
          <JalaliDatePicker label="از تاریخ" value={from} onChange={setFrom} />
          <JalaliDatePicker label="تا تاریخ" value={to} onChange={setTo} />
          <button type="button" className="btn btn-primary btn-sm" onClick={applyDateRange}>
            <i className="bi bi-search" /> اعمال
          </button>
          <button type="button" className="btn btn-ghost btn-sm" onClick={() => {
            const f = new Date(); f.setDate(f.getDate() - 30);
            setFrom(f.toISOString().split('T')[0]); setTo(new Date().toISOString().split('T')[0]);
          }}>۳۰ روز اخیر</button>
          <button type="button" className="btn btn-ghost btn-sm" onClick={() => {
            const now = new Date();
            setFrom(new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]);
            setTo(now.toISOString().split('T')[0]);
          }}>این ماه</button>
        </div>

        {/* Today stats */}
        <section className="dashboard-grid">
          <article className="metric-card"><span>ورود امروز</span><strong>{formatCount(metrics.loginsToday)}</strong></article>
          <article className="metric-card"><span>غیبت امروز</span><strong>{formatCount(metrics.absencesToday)}</strong></article>
          {metrics.smsThisMonth !== null && (
            <article className="metric-card"><span>پیامک این ماه</span><strong>{formatCount(metrics.smsThisMonth)}</strong></article>
          )}
          <article className="metric-card"><span>خروجی‌های ماه</span><strong>{formatCount(metrics.exportsThisMonth)}</strong></article>
        </section>

        {/* Section tabs */}
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: '0.75rem', alignItems: 'center', borderBottom: '2px solid var(--color-border)', flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: '0.25rem', overflowX: 'auto' }}>
            {sections.map((s) => (
              <button
                key={s.key}
                type="button"
                onClick={() => setActiveSection(s.key)}
                style={{
                  display: 'flex', alignItems: 'center', gap: '0.35rem',
                  padding: '0.5rem 0.9rem', background: 'none', border: 'none', cursor: 'pointer',
                  borderBottom: activeSection === s.key ? '2px solid var(--color-primary)' : '2px solid transparent',
                  marginBottom: -2,
                  color: activeSection === s.key ? 'var(--color-primary)' : 'var(--color-text-muted)',
                  fontWeight: activeSection === s.key ? 700 : 400,
                  fontSize: '0.875rem', whiteSpace: 'nowrap',
                }}
              >
                <i className={`bi ${s.icon}`} />{s.label}
                {s.count !== undefined && s.count > 0 && (
                  <span style={{ background: activeSection === s.key ? 'var(--color-primary)' : 'var(--color-border)', color: activeSection === s.key ? 'white' : 'var(--color-text-muted)', borderRadius: 99, fontSize: '0.7rem', padding: '0 0.35rem', fontWeight: 600 }}>
                    {s.count}
                  </span>
                )}
              </button>
            ))}
          </div>
          {activeSection !== 'activity' && (
            <a
              className="btn btn-soft btn-sm"
              href={exportHref(activeSection === 'grades' ? 'grades_csv' : activeSection === 'attendance' ? 'attendance_csv' : activeSection === 'exams' ? 'exams_csv' : 'sms_csv')}
            >
              <i className="bi bi-filetype-csv" /> خروجی CSV
            </a>
          )}
        </div>

        {/* Grade summary */}
        {activeSection === 'grades' && (
          gradeSummary.length === 0 ? (
            <EmptyState icon="bi-patch-check" msg="نمره تایید‌شده‌ای در این بازه یافت نشد" />
          ) : (
            <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
              <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><th>نرخ قبولی</th></tr>
                  </thead>
                  <tbody>
                    {gradeSummary.map((r, i) => (
                      <tr key={i}>
                        <td style={{ fontWeight: 600 }}>{r.classroom}</td>
                        <td>{r.subject}</td>
                        <td style={{ textAlign: 'center' }}>{r.count}</td>
                        <td><PctBadge v={r.avgPct} /></td>
                        <td><PctBadge v={r.minPct} /></td>
                        <td><PctBadge v={r.maxPct} /></td>
                        <td><PctBadge v={r.passRate} /></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>
          )
        )}

        {/* Attendance summary */}
        {activeSection === 'attendance' && (
          attendanceSummary.length === 0 ? (
            <EmptyState icon="bi-clipboard-check" msg="رکورد حضور و غیابی در این بازه یافت نشد" />
          ) : (
            <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
              <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>
                    {attendanceSummary.map((r, i) => (
                      <tr key={i}>
                        <td style={{ fontWeight: 600 }}>{r.classroom}</td>
                        <td style={{ color: '#16a34a', fontWeight: 600 }}>{r.present}</td>
                        <td style={{ color: '#dc2626', fontWeight: 600 }}>{r.absent}</td>
                        <td style={{ color: '#6366f1' }}>{r.excused}</td>
                        <td style={{ color: '#f59e0b' }}>{r.late}</td>
                        <td>
                          <span style={{ color: r.absenceRate > 20 ? '#dc2626' : r.absenceRate > 10 ? '#d97706' : '#16a34a', fontWeight: 600 }}>
                            {r.absenceRate}%
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>
          )
        )}

        {/* Exam summary */}
        {activeSection === 'exams' && (
          examSummary.length === 0 ? (
            <EmptyState icon="bi-pencil-square" msg="امتحانی در این بازه یافت نشد" />
          ) : (
            <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
              <div style={{ overflowX: 'auto' }}>
                <table className="data-table" style={{ width: '100%' }}>
                  <thead>
                    <tr><th>عنوان</th><th>کلاس</th><th>درس</th><th>شرکت‌کننده</th><th>میانگین</th></tr>
                  </thead>
                  <tbody>
                    {examSummary.map((r, i) => (
                      <tr key={i}>
                        <td style={{ fontWeight: 600 }}>{r.title}</td>
                        <td>{r.classroom}</td>
                        <td>{r.subject}</td>
                        <td style={{ textAlign: 'center' }}>{r.participants}</td>
                        <td>{r.avgPct !== null ? <PctBadge v={r.avgPct} /> : <span style={{ color: 'var(--color-text-muted)' }}>—</span>}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>
          )
        )}

        {/* Activity chart */}
        {activeSection === 'activity' && (
          <section className="panel-card">
            <h3 style={{ marginBottom: '1rem' }}><i className="bi bi-activity" style={{ marginLeft: '0.4rem', color: 'var(--color-primary)' }} />فعالیت ۷ روز اخیر</h3>
            {usage.length > 0 ? <UsageChart values={chartValues} /> : <EmptyState icon="bi-bar-chart" msg="داده فعالیت روزانه ثبت نشده" />}
          </section>
        )}

        {/* SMS — principal only */}
        {activeSection === 'sms' && isPrincipal && (
          smsSummary === null ? (
            <EmptyState icon="bi-chat-dots" msg="اطلاعات پیامک در این بازه موجود نیست" />
          ) : (
            <>
              <div className="dashboard-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))' }}>
                <div className="panel-card" style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: '1.6rem', fontWeight: 700 }}>{smsSummary.total.toLocaleString('fa-IR')}</div>
                  <div style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>تعداد پیامک ارسالی</div>
                </div>
                <div className="panel-card" style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: '1.6rem', fontWeight: 700, color: '#d97706' }}>{smsSummary.cost.toLocaleString('fa-IR')}</div>
                  <div style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>هزینه (ریال)</div>
                </div>
              </div>
              {smsSummary.daily.length > 0 && (
                <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
                  <div style={{ padding: '0.75rem 1rem', fontWeight: 600, borderBottom: '1px solid var(--color-border)' }}>مصرف روزانه</div>
                  <div style={{ overflowX: 'auto' }}>
                    <table className="data-table" style={{ width: '100%' }}>
                      <thead><tr><th>تاریخ</th><th>تعداد</th><th>هزینه (ریال)</th></tr></thead>
                      <tbody>
                        {smsSummary.daily.map((d, i) => (
                          <tr key={i}>
                            <td style={{ fontFamily: 'monospace' }}>{d.day}</td>
                            <td>{d.count}</td>
                            <td>{d.cost.toLocaleString('fa-IR')}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </section>
              )}
            </>
          )
        )}
      </div>
    </AppLayout>
  );
}

function PctBadge({ v }: { v: number }) {
  const color = v >= 70 ? '#16a34a' : v >= 50 ? '#d97706' : '#dc2626';
  return <span style={{ color, fontWeight: 600 }}>{v}%</span>;
}

function EmptyState({ icon, msg }: { icon: string; msg: string }) {
  return (
    <div className="panel-card" style={{ textAlign: 'center', padding: '2rem' }}>
      <i className={`bi ${icon}`} style={{ fontSize: '2rem', color: 'var(--color-text-muted)', display: 'block', marginBottom: '0.5rem' }} />
      <p style={{ color: 'var(--color-text-muted)' }}>{msg}</p>
    </div>
  );
}
