import React, { useState } from 'react';
import { Link, router, 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';

const QUAL_LABELS = ['خیلی خوب', 'خوب', 'قابل قبول', 'نیاز به تلاش بیشتر'] as const;

type QualThreshold = { label: string; min: number; max: number };

function scoreToLabel(score: string, thresholds: QualThreshold[]): string {
  const n = parseFloat(score);
  if (isNaN(n)) return '';
  const match = thresholds.find((t) => n >= t.min && n <= t.max);
  return match?.label ?? '';
}

function labelToScore(label: string, thresholds: QualThreshold[]): string {
  const match = thresholds.find((t) => t.label === label);
  return match ? String(match.max) : '';
}

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

type Props = {
  students: Array<{ value: string | number; label: string }>;
  classes: Array<{ value: string | number; label: string }>;
  subjects: Array<{ value: string | number; label: string; defaultMaxScore?: number | string }>;
  grades: Grade[];
  activeSchoolYear: { id: number; title: string } | null;
  schoolType: string | null;
  qualThresholds: QualThreshold[];
  gradeTypes: Array<{ value: string; label: string; weight: number }>;
};

function EbtedaeeInputs({
  score,
  qualLabel,
  thresholds,
  scoreError,
  qualError,
  onScoreChange,
  onLabelChange,
}: {
  score: string;
  qualLabel: string;
  thresholds: QualThreshold[];
  scoreError?: string;
  qualError?: string;
  onScoreChange: (v: string) => void;
  onLabelChange: (v: string) => void;
}) {
  function handleScore(v: string) {
    onScoreChange(v);
    const derived = scoreToLabel(v, thresholds);
    if (derived) onLabelChange(derived);
  }

  function handleLabel(v: string) {
    onLabelChange(v);
    if (v) {
      const derived = labelToScore(v, thresholds);
      if (derived) onScoreChange(derived);
    }
  }

  return (
    <>
      <div className="field-wrap">
        <label className="field-label">ارزیابی کیفی</label>
        <select className="field-input" value={qualLabel} onChange={(e) => handleLabel(e.target.value)}>
          <option value="">— انتخاب کنید —</option>
          {QUAL_LABELS.map((l) => <option key={l} value={l}>{l}</option>)}
        </select>
        {qualError && <span className="field-error">{qualError}</span>}
        {thresholds.length > 0 && qualLabel && (
          <p className="field-hint" style={{ margin: '0.2rem 0 0', fontSize: '0.75rem', color: 'var(--color-text-muted)' }}>
            {(() => { const t = thresholds.find((x) => x.label === qualLabel); return t ? `بازه: ${t.min} – ${t.max}` : null; })()}
          </p>
        )}
      </div>
      <TextInput
        label="نمره عددی (اختیاری)"
        type="number"
        min="0"
        max="20"
        step="0.25"
        value={score}
        onChange={(e) => handleScore(e.target.value)}
        error={scoreError}
      />
    </>
  );
}

function EditGradeForm({ grade, schoolType, qualThresholds, onClose }: {
  grade: Grade;
  schoolType: string | null;
  qualThresholds: QualThreshold[];
  onClose: () => void;
}) {
  const isEbtedaee = schoolType === 'ebtedaee';

  const form = useForm({
    score: String(grade.score),
    max_score: String(grade.maxScore),
    qualitative_label: grade.qualitativeLabel ?? '',
    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: isEbtedaee ? '1.5fr 1fr 2fr auto auto' : '1fr 1fr 2fr auto auto' }}>
        {isEbtedaee ? (
          <EbtedaeeInputs
            score={form.data.score}
            qualLabel={form.data.qualitative_label}
            thresholds={qualThresholds}
            scoreError={form.errors.score}
            qualError={form.errors.qualitative_label}
            onScoreChange={(v) => form.setData('score', v)}
            onLabelChange={(v) => form.setData('qualitative_label', v)}
          />
        ) : (
          <>
            <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, activeSchoolYear, schoolType, qualThresholds, gradeTypes }: Props) {
  const [editingId, setEditingId] = useState<number | null>(null);
  const isEbtedaee = schoolType === 'ebtedaee';

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

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

  function requestReconsideration(grade: Grade) {
    const note = window.prompt(`یادداشت بازبینی برای نمره ${grade.student} در درس ${grade.subject}`);
    if (!note) return;
    router.post(`/teacher/grades/${grade.id}/reconsideration`, { note }, { preserveScroll: true });
  }

  return (
    <AppLayout title="نمره‌دهی">
      <div className="page-stack">
        <form className="panel-card" onSubmit={(e) => { e.preventDefault(); form.post('/teacher/grades', { preserveScroll: true, onSuccess: () => form.reset() }); }}>
          <h2>ثبت نمره جدید</h2>
          {activeSchoolYear && (
            <div style={{ marginBottom: '0.75rem', padding: '0.5rem 0.75rem', background: 'var(--color-bg-soft)', borderRadius: 6, border: '1px solid var(--color-border)', color: 'var(--color-text-muted)', fontSize: '0.85rem' }}>
              <i className="bi bi-calendar2-range" style={{ marginLeft: '0.3rem' }} />
              سال تحصیلی فعال: <strong style={{ color: 'var(--color-text)' }}>{activeSchoolYear.title}</strong>
            </div>
          )}
          {isEbtedaee && (
            <div style={{ marginBottom: '0.75rem', padding: '0.5rem 0.75rem', background: '#eff6ff', borderRadius: 6, border: '1px solid #bfdbfe', color: '#1e40af', fontSize: '0.875rem' }}>
              <i className="bi bi-info-circle" /> مدرسه ابتدایی — می‌توانید ارزیابی کیفی، نمره عددی، یا هر دو را وارد کنید. انتخاب هر کدام دیگری را پیشنهاد می‌دهد.
            </div>
          )}
          <div className="form-grid">
            <SelectInput label="دانش‌آموز" value={form.data.student_id} onChange={(e) => form.setData('student_id', e.target.value)} options={[{ value: '', label: 'انتخاب دانش‌آموز' }, ...students]} />
            <SelectInput label="کلاس" value={form.data.classroom_id} onChange={(e) => form.setData('classroom_id', e.target.value)} options={[{ value: '', label: 'انتخاب کلاس' }, ...classes]} />
            <SelectInput
              label="درس"
              value={form.data.subject_id}
              onChange={(e) => {
                const value = e.target.value;
                form.setData('subject_id', value);
                const subject = subjects.find((s) => String(s.value) === value);
                if (subject?.defaultMaxScore) form.setData('max_score', String(subject.defaultMaxScore));
              }}
              options={[{ value: '', label: 'انتخاب درس' }, ...subjects]}
            />
            <SelectInput
              label="نوع نمره"
              value={form.data.grade_type}
              onChange={(e) => form.setData('grade_type', e.target.value)}
              options={gradeTypes.map((t) => ({ value: t.value, label: `${t.label} (${t.weight}٪)` }))}
            />
            {isEbtedaee ? (
              <EbtedaeeInputs
                score={form.data.score}
                qualLabel={form.data.qualitative_label}
                thresholds={qualThresholds}
                scoreError={form.errors.score}
                qualError={form.errors.qualitative_label}
                onScoreChange={(v) => form.setData('score', v)}
                onLabelChange={(v) => form.setData('qualitative_label', v)}
              />
            ) : (
              <>
                <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.description} onChange={(e) => form.setData('description', e.target.value)} />
          </div>
          <button className="btn btn-primary" disabled={form.processing} type="submit">ثبت نمره</button>

          {isEbtedaee && qualThresholds.length > 0 && (
            <details style={{ marginTop: '0.75rem' }}>
              <summary style={{ cursor: 'pointer', fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>
                <i className="bi bi-info-circle" /> بازه‌های کیفی این مدرسه
              </summary>
              <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', marginTop: '0.5rem' }}>
                {qualThresholds.map((t) => (
                  <span key={t.label} style={{ padding: '0.25rem 0.6rem', borderRadius: 6, background: 'var(--color-bg-soft)', border: '1px solid var(--color-border)', fontSize: '0.78rem' }}>
                    <strong>{t.label}</strong>: {t.min}–{t.max}
                  </span>
                ))}
              </div>
            </details>
          )}
        </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) => (
                  <React.Fragment key={grade.id}>
                    <tr>
                      <td>{grade.student}</td>
                      <td>{grade.subject}</td>
                      <td>
                        {grade.gradeType && (
                          <div style={{ fontSize: '0.75rem', color: 'var(--color-text-muted)', marginBottom: '0.15rem' }}>
                            {gradeTypes.find((t) => t.value === grade.gradeType)?.label ?? grade.gradeType}
                          </div>
                        )}
                        {grade.qualitativeLabel ? (
                          <span style={{ fontWeight: 600 }}>
                            {grade.qualitativeLabel}
                            {grade.score ? <span style={{ color: 'var(--color-text-muted)', fontWeight: 400, fontSize: '0.8rem', marginRight: 4 }}>({formatCount(grade.score)})</span> : null}
                          </span>
                        ) : (
                          <>{formatCount(grade.score)} از {formatCount(grade.maxScore)}</>
                        )}
                        {grade.description && (
                          <div style={{ fontSize: '0.78rem', color: 'var(--color-info, #0ea5e9)', marginTop: '0.15rem' }}>
                            <i className="bi bi-chat-quote" style={{ marginLeft: '0.2rem' }} />{grade.description}
                          </div>
                        )}
                      </td>
                      <td>
                        <span className={`badge ${statusBadge[grade.statusKey] || 'badge-muted'}`}>{grade.status}</span>
                        {grade.statusKey === 'rejected' && grade.rejectReason && (
                          <div style={{ fontSize: '0.75rem', color: '#dc2626', marginTop: '0.2rem' }}>
                            <i className="bi bi-x-circle" style={{ marginLeft: '0.2rem' }} />{grade.rejectReason}
                          </div>
                        )}
                      </td>
                      <td>{grade.changedAt}</td>
                      <td>{grade.changedBy}</td>
                      <td>
                        <div className="action-row--compact">
                          {(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>
                          )}
                          <Link href={`/teacher/students/${grade.studentId}/scores`} className="btn btn-soft btn-sm">
                            <i className="bi bi-mortarboard" /> کارنامه
                          </Link>
                          {grade.statusKey === 'rejected' && (
                            <button className="btn btn-soft btn-sm" type="button" onClick={() => requestReconsideration(grade)}>
                              <i className="bi bi-arrow-repeat" /> بازبینی
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                    {editingId === grade.id && (
                      <tr>
                        <td colSpan={7}>
                          <EditGradeForm grade={grade} schoolType={schoolType} qualThresholds={qualThresholds} onClose={() => setEditingId(null)} />
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <section className="panel-card">
            <h2>نمره‌ای ثبت نشده</h2>
            <p>بعد از ثبت نمره، جدول و audit log واقعی از دیتابیس نمایش داده می‌شود.</p>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
