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

type CardRow = {
  subject: string;
  classroom: string;
  score: number;
  maxScore: number;
  status: string;
  description: string;
};

type Props = {
  students: Array<{ value: number; label: string }>;
  selectedStudentId: number | null;
  card: CardRow[];
};

const statusLabel: Record<string, string> = {
  draft: 'پیش‌نویس',
  submitted: 'ارسال‌شده',
  approved: 'تایید شده',
  rejected: 'رد شده',
};

export default function ReportCard({ students, selectedStudentId, card }: Props) {
  function handleSelect(event: React.ChangeEvent<HTMLSelectElement>) {
    const id = event.target.value;
    if (id) {
      router.get('/school/report-card', { student_id: id }, { preserveState: false });
    }
  }

  const total = card.reduce((sum, row) => sum + row.score, 0);
  const totalMax = card.reduce((sum, row) => sum + row.maxScore, 0);
  const avg = card.length > 0 ? (total / card.length).toFixed(2) : null;

  return (
    <AppLayout title="کارنامه">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>کارنامه دانش‌آموز</h2>
            <p>برای مشاهده کارنامه، ابتدا دانش‌آموز را انتخاب کنید.</p>
          </div>
          <div className="action-row report-card-actions">
            {selectedStudentId && (
              <a
                className="btn btn-primary"
                href={`/school/report-card/pdf?student_id=${selectedStudentId}`}
                target="_blank"
                rel="noreferrer"
              >
                <i className="bi bi-file-earmark-pdf" /> دانلود PDF
              </a>
            )}
            <a className="btn btn-ghost" href="/school/grades"><i className="bi bi-arrow-right" /> بازگشت به نمرات</a>
          </div>
        </section>

        <div className="panel-card">
          <SelectInput
            label="انتخاب دانش‌آموز"
            value={selectedStudentId ?? ''}
            onChange={handleSelect}
            options={[
              { value: '', label: 'انتخاب کنید...' },
              ...students.map((s) => ({ value: s.value, label: s.label })),
            ]}
          />
        </div>

        {selectedStudentId && card.length > 0 && (
          <>
            <section className="dashboard-grid">
              <article className="metric-card">
                <span>تعداد درس</span>
                <strong>{card.length}</strong>
              </article>
              <article className="metric-card">
                <span>مجموع نمرات</span>
                <strong>{total} از {totalMax}</strong>
              </article>
              {avg !== null && (
                <article className="metric-card">
                  <span>میانگین</span>
                  <strong>{avg}</strong>
                </article>
              )}
            </section>
            <div className="table-wrap">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>درس</th>
                    <th>کلاس</th>
                    <th>نمره</th>
                    <th>از</th>
                    <th>درصد</th>
                    <th>وضعیت</th>
                    <th>توضیح</th>
                  </tr>
                </thead>
                <tbody>
                  {card.map((row, index) => (
                    <tr key={index}>
                      <td>{row.subject}</td>
                      <td>{row.classroom}</td>
                      <td><strong>{row.score}</strong></td>
                      <td>{row.maxScore}</td>
                      <td>{row.maxScore > 0 ? Math.round((row.score / row.maxScore) * 100) : 0}٪</td>
                      <td>{statusLabel[row.status] || row.status}</td>
                      <td>{row.description || '—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}

        {selectedStudentId && card.length === 0 && (
          <section className="panel-card">
            <h2>نمره‌ای ثبت نشده</h2>
            <p>برای این دانش‌آموز هنوز نمره‌ای توسط معلم ثبت نشده است.</p>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
