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

type Grade = {
  id: number;
  student: string;
  subject: string;
  classroom: string;
  teacher: string;
  score: number;
  maxScore: number;
  status: string;
  description: string;
  updatedAt: string;
};

type Props = {
  grades: Grade[];
};

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

const statusClass: Record<string, string> = {
  submitted: 'badge-warning',
  approved: 'badge-success',
  rejected: 'badge-danger',
};

export default function SchoolGrades({ grades }: Props) {
  const [selected, setSelected] = useState<number[]>([]);

  const submitted = grades.filter((g) => g.status === 'submitted');
  const rest = grades.filter((g) => g.status !== 'submitted');

  const allChecked = submitted.length > 0 && selected.length === submitted.length;
  const someChecked = selected.length > 0 && selected.length < submitted.length;

  function toggle(id: number) {
    setSelected((s) => s.includes(id) ? s.filter((x) => x !== id) : [...s, id]);
  }

  function toggleAll() {
    setSelected(allChecked ? [] : submitted.map((g) => g.id));
  }

  function handleApprove(id: number, student: string) {
    if (!confirm(`تایید نمره «${student}»؟`)) return;
    router.patch(`/school/grades/${id}/approve`, {}, { preserveScroll: true });
  }

  function handleReject(id: number, student: string) {
    if (!confirm(`رد نمره «${student}»؟`)) return;
    router.patch(`/school/grades/${id}/reject`, {}, { preserveScroll: true });
  }

  function bulkApprove() {
    if (selected.length === 0) return;
    if (!confirm(`تایید ${selected.length} نمره انتخاب‌شده؟`)) return;
    router.post('/school/grades/bulk-approve', { ids: selected }, { preserveScroll: true, onSuccess: () => setSelected([]) });
  }

  function bulkReject() {
    if (selected.length === 0) return;
    if (!confirm(`رد ${selected.length} نمره انتخاب‌شده؟`)) return;
    router.post('/school/grades/bulk-reject', { ids: selected }, { preserveScroll: true, onSuccess: () => setSelected([]) });
  }

  return (
    <AppLayout title="تایید نمرات">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>تایید و مدیریت نمرات</h2>
            <p>نمرات ارسال‌شده توسط معلمان نیاز به تایید دارند.</p>
          </div>
          <div style={{ display: 'flex', gap: '.5rem', flexWrap: 'wrap' }}>
            <a className="btn btn-soft" href="/school/grade-logs">گزارش تغییرات نمره</a>
            <a className="btn btn-soft" href="/school/report-card">کارنامه دانش‌آموز</a>
          </div>
        </section>

        {submitted.length > 0 && (
          <div className="panel-card">
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '.75rem', marginBottom: '1rem' }}>
              <h2>نیاز به تایید ({submitted.length})</h2>
              {selected.length > 0 && (
                <div style={{ display: 'flex', gap: '.5rem' }}>
                  <span style={{ alignSelf: 'center', fontSize: '.9rem', opacity: .7 }}>{selected.length} انتخاب‌شده</span>
                  <button type="button" className="btn btn-primary btn-sm" onClick={bulkApprove}>
                    <i className="bi bi-check-all" /> تایید همه
                  </button>
                  <button type="button" className="btn btn-danger-ghost btn-sm" onClick={bulkReject}>
                    <i className="bi bi-x-circle" /> رد همه
                  </button>
                </div>
              )}
            </div>
            <div className="table-wrap">
              <table className="data-table">
                <thead>
                  <tr>
                    <th style={{ width: 36 }}>
                      <input
                        type="checkbox"
                        checked={allChecked}
                        ref={(el) => { if (el) el.indeterminate = someChecked; }}
                        onChange={toggleAll}
                        aria-label="انتخاب همه"
                      />
                    </th>
                    <th>دانش‌آموز</th>
                    <th>درس</th>
                    <th>کلاس</th>
                    <th>معلم</th>
                    <th>نمره</th>
                    <th>توضیح</th>
                    <th>عملیات</th>
                  </tr>
                </thead>
                <tbody>
                  {submitted.map((grade) => (
                    <tr key={grade.id} className={selected.includes(grade.id) ? 'row--selected' : ''}>
                      <td>
                        <input
                          type="checkbox"
                          checked={selected.includes(grade.id)}
                          onChange={() => toggle(grade.id)}
                          aria-label={`انتخاب نمره ${grade.student}`}
                        />
                      </td>
                      <td>{grade.student}</td>
                      <td>{grade.subject}</td>
                      <td>{grade.classroom}</td>
                      <td>{grade.teacher}</td>
                      <td>{grade.score} از {grade.maxScore}</td>
                      <td>{grade.description || '—'}</td>
                      <td>
                        <div className="action-row--compact">
                          <button
                            className="btn btn-primary btn-sm"
                            type="button"
                            onClick={() => handleApprove(grade.id, grade.student)}
                          >
                            <i className="bi bi-check-circle" /> تایید
                          </button>
                          <button
                            className="btn btn-danger-ghost btn-sm"
                            type="button"
                            onClick={() => handleReject(grade.id, grade.student)}
                          >
                            <i className="bi bi-x-circle" /> رد
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {submitted.length === 0 && (
          <section className="panel-card">
            <h2>نمره‌ای منتظر تایید نیست</h2>
            <p>همه نمرات بررسی شده‌اند یا هنوز نمره‌ای ثبت نشده است.</p>
          </section>
        )}

        {rest.length > 0 && (
          <div className="table-wrap">
            <table className="data-table">
              <thead>
                <tr>
                  <th>دانش‌آموز</th>
                  <th>درس</th>
                  <th>کلاس</th>
                  <th>نمره</th>
                  <th>وضعیت</th>
                  <th>آخرین تغییر</th>
                </tr>
              </thead>
              <tbody>
                {rest.map((grade) => (
                  <tr key={grade.id}>
                    <td>{grade.student}</td>
                    <td>{grade.subject}</td>
                    <td>{grade.classroom}</td>
                    <td>{grade.score} از {grade.maxScore}</td>
                    <td>
                      <span className={`badge ${statusClass[grade.status] || ''}`}>
                        {statusLabel[grade.status] || grade.status}
                      </span>
                    </td>
                    <td>{grade.updatedAt}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </AppLayout>
  );
}
