import { useState } from 'react';
import { useForm } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { SelectInput } from '@/Components/Forms/SelectInput';
import { TextInput } from '@/Components/Forms/TextInput';
import { formatCount } from '@/lib/formatters';

type Grade = {
  id: number;
  student: string;
  subject: string;
  score: number;
  maxScore: number;
  statusKey: string;
  status: string;
  oldScore: number | null;
  newScore: number | null;
  changedBy: string;
  changedAt: string;
};

type Props = {
  students: Array<{ value: string | number; label: string }>;
  classes: Array<{ value: string | number; label: string }>;
  subjects: Array<{ value: string | number; label: string }>;
  grades: Grade[];
};

function EditGradeForm({ grade, onClose }: { grade: Grade; onClose: () => void }) {
  const form = useForm({
    score: String(grade.score),
    max_score: String(grade.maxScore),
    reason: '',
  });

  function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    form.put(`/teacher/grades/${grade.id}`, {
      onSuccess: () => onClose(),
    });
  }

  return (
    <form onSubmit={handleSubmit} style={{ marginTop: '0.75rem', background: 'var(--color-bg-soft)', padding: '0.75rem', borderRadius: 'var(--radius-sm)' }}>
      <div className="form-grid" style={{ gridTemplateColumns: '1fr 1fr 2fr auto auto' }}>
        <TextInput
          label="نمره جدید"
          type="number"
          min="0"
          step="0.25"
          value={form.data.score}
          onChange={(e) => form.setData('score', e.target.value)}
          error={form.errors.score}
        />
        <TextInput
          label="از"
          type="number"
          min="1"
          step="0.25"
          value={form.data.max_score}
          onChange={(e) => form.setData('max_score', e.target.value)}
        />
        <TextInput
          label="دلیل تغییر"
          value={form.data.reason}
          onChange={(e) => form.setData('reason', e.target.value)}
        />
        <button className="btn btn-primary btn-sm" style={{ alignSelf: 'flex-end', marginBottom: '0.1rem' }} disabled={form.processing} type="submit">ذخیره</button>
        <button className="btn btn-ghost btn-sm" style={{ alignSelf: 'flex-end', marginBottom: '0.1rem' }} type="button" onClick={onClose}>لغو</button>
      </div>
    </form>
  );
}

export default function GradeTable({ students, classes, subjects, grades }: Props) {
  const [editingId, setEditingId] = useState<number | null>(null);

  const form = useForm({
    student_id: '',
    classroom_id: '',
    subject_id: '',
    exam_id: '',
    score: '',
    max_score: '20',
    description: '',
  });

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

  return (
    <AppLayout title="نمره‌دهی">
      <div className="page-stack">
        <form className="panel-card" onSubmit={(event) => { event.preventDefault(); form.post('/teacher/grades', { preserveScroll: true, onSuccess: () => form.reset() }); }}>
          <h2>ثبت نمره جدید</h2>
          <div className="form-grid">
            <SelectInput label="دانش‌آموز" value={form.data.student_id} onChange={(event) => form.setData('student_id', event.target.value)} options={[{ value: '', label: 'انتخاب دانش‌آموز' }, ...students]} />
            <SelectInput label="کلاس" value={form.data.classroom_id} onChange={(event) => form.setData('classroom_id', event.target.value)} options={[{ value: '', label: 'انتخاب کلاس' }, ...classes]} />
            <SelectInput label="درس" value={form.data.subject_id} onChange={(event) => form.setData('subject_id', event.target.value)} options={[{ value: '', label: 'انتخاب درس' }, ...subjects]} />
            <TextInput label="نمره" type="number" min="0" step="0.25" value={form.data.score} onChange={(event) => form.setData('score', event.target.value)} error={form.errors.score} />
            <TextInput label="از نمره" type="number" min="1" step="0.25" value={form.data.max_score} onChange={(event) => form.setData('max_score', event.target.value)} />
            <TextInput label="توضیح" value={form.data.description} onChange={(event) => form.setData('description', event.target.value)} />
          </div>
          <button className="btn btn-primary" disabled={form.processing} type="submit">ثبت نمره</button>
        </form>

        {grades.length > 0 ? (
          <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>
                {grades.map((grade) => (
                  <>
                    <tr key={grade.id}>
                      <td>{grade.student}</td>
                      <td>{grade.subject}</td>
                      <td>{formatCount(grade.score)} از {formatCount(grade.maxScore)}</td>
                      <td>
                        <span className={`badge ${statusBadge[grade.statusKey] || 'badge-muted'}`}>
                          {grade.status}
                        </span>
                      </td>
                      <td>{grade.changedAt}</td>
                      <td>{grade.changedBy}</td>
                      <td>
                        {(grade.statusKey === 'draft' || grade.statusKey === 'submitted') && (
                          <button
                            className="btn btn-ghost btn-sm"
                            type="button"
                            onClick={() => setEditingId(editingId === grade.id ? null : grade.id)}
                          >
                            <i className="bi bi-pencil" /> ویرایش
                          </button>
                        )}
                      </td>
                    </tr>
                    {editingId === grade.id && (
                      <tr key={`edit-${grade.id}`}>
                        <td colSpan={7}>
                          <EditGradeForm grade={grade} onClose={() => setEditingId(null)} />
                        </td>
                      </tr>
                    )}
                  </>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <section className="panel-card">
            <h2>نمره‌ای ثبت نشده</h2>
            <p>بعد از ثبت نمره، جدول و audit log واقعی از دیتابیس نمایش داده می‌شود.</p>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
