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

type Objection = {
  id: number;
  gradeId: number;
  student: string;
  subject: string;
  score: number;
  maxScore: number;
  reason: string;
  status: 'pending' | 'approved' | 'rejected';
  adminNote: string | null;
  resolvedAt: string | null;
  createdAt: string;
  resolvedBy: string | null;
};

type Props = {
  objections: Objection[];
  enabledGrades: number[];
};

const ALL_GRADE_LEVELS = Array.from({ length: 12 }, (_, i) => i + 1);

export default function SchoolEteraz({ objections, enabledGrades }: Props) {
  const [resolveForm, setResolveForm] = useState<{ id: number; action: 'approved' | 'rejected'; note: string } | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [policyGrades, setPolicyGrades] = useState<number[]>(enabledGrades);
  const [savingPolicy, setSavingPolicy] = useState(false);
  const [tab, setTab] = useState<'pending' | 'resolved'>('pending');

  const pending = objections.filter((o) => o.status === 'pending');
  const resolved = objections.filter((o) => o.status !== 'pending');

  function openResolve(id: number, action: 'approved' | 'rejected') {
    setResolveForm({ id, action, note: '' });
  }

  function submitResolve() {
    if (! resolveForm) return;
    setSubmitting(true);
    router.patch(
      `/school/eteraz/${resolveForm.id}/resolve`,
      { action: resolveForm.action, admin_note: resolveForm.note },
      { onFinish: () => { setSubmitting(false); setResolveForm(null); } }
    );
  }

  function toggleGrade(n: number) {
    setPolicyGrades((prev) =>
      prev.includes(n) ? prev.filter((g) => g !== n) : [...prev, n].sort((a, b) => a - b)
    );
  }

  function savePolicy() {
    setSavingPolicy(true);
    router.put(
      '/school/eteraz/policy',
      { enabled_grades: policyGrades },
      { onFinish: () => setSavingPolicy(false) }
    );
  }

  const displayed = tab === 'pending' ? pending : resolved;

  return (
    <AppLayout title="صندوق اعتراضات نمره">
      <div className="page-stack">

        <section className="section-header">
          <div>
            <h2>
              <i className="bi bi-megaphone" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />
              صندوق اعتراضات نمره
            </h2>
            <p>بررسی اعتراض‌های دانش‌آموزان نسبت به نمرات تایید‌شده</p>
          </div>
          {pending.length > 0 && (
            <span style={{ background: '#dc262620', color: '#dc2626', border: '1px solid #dc262630', borderRadius: 'var(--radius-sm)', padding: '0.3rem 0.75rem', fontWeight: 700, fontSize: '0.95rem' }}>
              {pending.length} اعتراض جدید
            </span>
          )}
        </section>

        {/* Tabs */}
        <div style={{ display: 'flex', gap: '0.25rem', borderBottom: '2px solid var(--color-border)', marginBottom: '-0.75rem' }}>
          {[
            { key: 'pending' as const, label: `در انتظار (${pending.length})` },
            { key: 'resolved' as const, label: `بررسی‌شده (${resolved.length})` },
          ].map((t) => (
            <button
              key={t.key}
              type="button"
              onClick={() => setTab(t.key)}
              style={{
                padding: '0.5rem 1.1rem',
                fontSize: '0.9rem',
                fontWeight: tab === t.key ? 700 : 400,
                color: tab === t.key ? 'var(--color-primary-active)' : 'var(--color-text-muted)',
                border: 'none',
                borderBottom: tab === t.key ? '2px solid var(--color-primary-active)' : '2px solid transparent',
                marginBottom: -2,
                background: 'transparent',
                cursor: 'pointer',
              }}
            >
              {t.label}
            </button>
          ))}
        </div>

        {/* Objections list */}
        {displayed.length === 0 ? (
          <section className="panel-card">
            <div style={{ textAlign: 'center', padding: '2rem 1rem' }}>
              <i className="bi bi-inbox" style={{ fontSize: '2.5rem', color: 'var(--color-text-muted)' }} />
              <p style={{ marginTop: '0.75rem', color: 'var(--color-text-muted)' }}>
                {tab === 'pending' ? 'اعتراض جدیدی وجود ندارد.' : 'هنوز اعتراضی بررسی نشده.'}
              </p>
            </div>
          </section>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
            {displayed.map((o) => (
              <section key={o.id} className="panel-card" style={{ padding: '1rem 1.25rem' }}>
                <div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap', alignItems: 'flex-start' }}>
                  <div style={{ flex: 1, minWidth: 220 }}>
                    <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', marginBottom: '0.3rem' }}>
                      <strong style={{ fontSize: '0.95rem' }}>{o.student}</strong>
                      <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>—</span>
                      <span style={{ fontSize: '0.9rem', fontWeight: 600 }}>{o.subject}</span>
                    </div>
                    <div style={{ fontSize: '0.85rem', color: 'var(--color-text-muted)', marginBottom: '0.5rem' }}>
                      نمره: <strong style={{ color: 'var(--color-text)' }}>{o.score} / {o.maxScore}</strong>
                      <span style={{ marginRight: '0.75rem' }}>تاریخ: {o.createdAt}</span>
                    </div>
                    <div style={{ background: 'var(--color-bg-subtle)', borderRadius: 'var(--radius-sm)', padding: '0.5rem 0.75rem', fontSize: '0.875rem', borderRight: '3px solid #d97706', marginBottom: '0.5rem' }}>
                      <span style={{ color: 'var(--color-text-muted)', fontSize: '0.78rem' }}>متن اعتراض:</span>
                      <div style={{ marginTop: '0.2rem' }}>{o.reason}</div>
                    </div>
                    {o.adminNote && (
                      <div style={{ fontSize: '0.82rem', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
                        یادداشت مدیر: {o.adminNote}
                        {o.resolvedBy && <span> — {o.resolvedBy}</span>}
                        {o.resolvedAt && <span> ({o.resolvedAt})</span>}
                      </div>
                    )}
                  </div>

                  <div style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem', alignItems: 'flex-end' }}>
                    {o.status === 'pending' ? (
                      <>
                        <button
                          type="button"
                          onClick={() => openResolve(o.id, 'approved')}
                          style={{ padding: '0.35rem 0.8rem', fontSize: '0.82rem', borderRadius: 'var(--radius-sm)', border: '1px solid #16a34a', color: '#16a34a', background: '#16a34a12', cursor: 'pointer', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '0.3rem' }}
                        >
                          <i className="bi bi-check-circle" /> پذیرش اعتراض
                        </button>
                        <button
                          type="button"
                          onClick={() => openResolve(o.id, 'rejected')}
                          style={{ padding: '0.35rem 0.8rem', fontSize: '0.82rem', borderRadius: 'var(--radius-sm)', border: '1px solid #dc2626', color: '#dc2626', background: '#dc262612', cursor: 'pointer', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '0.3rem' }}
                        >
                          <i className="bi bi-x-circle" /> رد اعتراض
                        </button>
                      </>
                    ) : (
                      <StatusBadge status={o.status} />
                    )}
                  </div>
                </div>

                {/* Resolve inline form */}
                {resolveForm?.id === o.id && (
                  <div style={{ marginTop: '0.75rem', borderTop: '1px solid var(--color-border)', paddingTop: '0.75rem' }}>
                    <p style={{ fontSize: '0.85rem', marginBottom: '0.4rem', fontWeight: 600, color: resolveForm.action === 'approved' ? '#16a34a' : '#dc2626' }}>
                      {resolveForm.action === 'approved' ? 'پذیرش اعتراض' : 'رد اعتراض'} — یادداشت (اختیاری):
                    </p>
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                      <textarea
                        rows={2}
                        placeholder="توضیح برای دانش‌آموز..."
                        value={resolveForm.note}
                        onChange={(e) => setResolveForm((p) => p ? { ...p, note: e.target.value } : p)}
                        style={{ flex: 1, border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', padding: '0.4rem', background: 'var(--color-surface)', color: 'var(--color-text)', fontSize: '0.85rem', resize: 'vertical' }}
                      />
                      <div style={{ display: 'flex', flexDirection: 'column', gap: '0.3rem' }}>
                        <button type="button" disabled={submitting} onClick={submitResolve} className="btn btn-primary" style={{ whiteSpace: 'nowrap' }}>
                          {submitting ? 'در حال ذخیره...' : 'تایید'}
                        </button>
                        <button type="button" onClick={() => setResolveForm(null)} style={{ padding: '0.3rem 0.6rem', fontSize: '0.8rem', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', cursor: 'pointer', background: 'transparent', color: 'var(--color-text-muted)' }}>
                          انصراف
                        </button>
                      </div>
                    </div>
                  </div>
                )}
              </section>
            ))}
          </div>
        )}

        {/* Eteraz policy */}
        <section className="panel-card">
          <h3 style={{ fontSize: '1rem', fontWeight: 700, marginBottom: '0.75rem' }}>
            <i className="bi bi-gear" style={{ marginLeft: '0.4rem', color: 'var(--color-primary)' }} />
            تنظیمات اعتراض به نمره
          </h3>
          <p style={{ fontSize: '0.875rem', color: 'var(--color-text-muted)', marginBottom: '0.75rem' }}>
            پایه‌هایی که دانش‌آموزان مجاز به ثبت اعتراض هستند را انتخاب کنید. (پیش‌فرض: پایه ۷ تا ۱۲)
          </p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', marginBottom: '1rem' }}>
            {ALL_GRADE_LEVELS.map((n) => (
              <label
                key={n}
                style={{
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: '0.35rem',
                  padding: '0.3rem 0.7rem',
                  borderRadius: 'var(--radius-sm)',
                  border: `1px solid ${policyGrades.includes(n) ? 'var(--color-primary)' : 'var(--color-border)'}`,
                  background: policyGrades.includes(n) ? 'var(--color-primary-soft)' : 'transparent',
                  cursor: 'pointer',
                  fontSize: '0.85rem',
                  fontWeight: 600,
                  userSelect: 'none',
                  color: policyGrades.includes(n) ? 'var(--color-primary-active)' : 'var(--color-text-muted)',
                }}
              >
                <input
                  type="checkbox"
                  checked={policyGrades.includes(n)}
                  onChange={() => toggleGrade(n)}
                  style={{ display: 'none' }}
                />
                پایه {n}
              </label>
            ))}
          </div>
          <button type="button" onClick={savePolicy} disabled={savingPolicy} className="btn btn-primary">
            {savingPolicy ? 'در حال ذخیره...' : 'ذخیره تنظیمات'}
          </button>
        </section>
      </div>
    </AppLayout>
  );
}

function StatusBadge({ status }: { status: string }) {
  const map: Record<string, { label: string; color: string; icon: string }> = {
    approved: { label: 'پذیرفته شد', color: '#16a34a', icon: 'bi-check-circle-fill' },
    rejected: { label: 'رد شد', color: '#dc2626', icon: 'bi-x-circle-fill' },
  };
  const m = map[status] ?? map.rejected;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.3rem', background: m.color + '18', color: m.color, border: `1px solid ${m.color}30`, borderRadius: 'var(--radius-sm)', padding: '0.25rem 0.6rem', fontSize: '0.8rem', fontWeight: 600 }}>
      <i className={m.icon} /> {m.label}
    </span>
  );
}
