import { useState } from 'react';
import { useForm, router } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { JalaliDatePicker } from '@/Components/Forms/JalaliDatePicker';

type SchoolYear = {
  id: number;
  title: string;
  startsOn: string | null;
  endsOn: string | null;
  status: 'active' | 'archived';
  promotedStudents: number;
  graduatedStudents: number;
  closedAt: string | null;
  createdAt: string;
};

type Props = {
  years: SchoolYear[];
  activeStudentCount: number;
};

export default function SchoolYears({ years, activeStudentCount }: Props) {
  const [confirmClose, setConfirmClose] = useState<number | null>(null);
  const { data, setData, post, processing, errors, reset } = useForm({ title: '', starts_on: '', ends_on: '' });
  const closeForm = useForm({ confirm: false as boolean });

  const submitNew = (e: React.FormEvent) => {
    e.preventDefault();
    post('/school/years', { onSuccess: () => reset() });
  };

  const doClose = (id: number) => {
    closeForm.post(`/school/years/${id}/close`, {
      onSuccess: () => setConfirmClose(null),
    });
  };

  return (
    <AppLayout title="سال‌های تحصیلی">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>سال تحصیلی</h2>
            <p>بستن سال تحصیلی، پایه همه دانش‌آموزان فعال را یک عدد ارتقا می‌دهد.</p>
          </div>
        </section>

        <section className="panel-card">
          <h3 style={{ fontWeight: 700, marginBottom: '1rem' }}>ایجاد سال تحصیلی جدید</h3>
          <form onSubmit={submitNew} style={{ display: 'flex', flexWrap: 'wrap', gap: '0.75rem', alignItems: 'flex-end' }}>
            <div className="form-group" style={{ flex: '1 1 200px' }}>
              <label className="form-label">عنوان *</label>
              <input className="form-input" placeholder="مثلاً: ۱۴۰۵–۱۴۰۶" value={data.title} onChange={e => setData('title', e.target.value)} required />
              {errors.title && <p className="form-error">{errors.title}</p>}
            </div>
            <div style={{ flex: '1 1 180px' }}><JalaliDatePicker label="تاریخ شروع" value={data.starts_on} onChange={(value) => setData('starts_on', value)} /></div>
            <div style={{ flex: '1 1 180px' }}><JalaliDatePicker label="تاریخ پایان" value={data.ends_on} onChange={(value) => setData('ends_on', value)} /></div>
            <button className="btn btn-primary" type="submit" disabled={processing} style={{ flexShrink: 0 }}>
              <i className="bi bi-plus-lg" /> ایجاد
            </button>
          </form>
        </section>

        <section className="panel-card">
          {years.length === 0 ? (
            <p style={{ color: 'var(--color-text-soft)', textAlign: 'center', padding: '2rem' }}>هیچ سال تحصیلی‌ای ثبت نشده است.</p>
          ) : (
            <div className="table-wrap">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>عنوان</th>
                    <th>شروع</th>
                    <th>پایان</th>
                    <th>وضعیت</th>
                    <th>ارتقا</th>
                    <th>فارغ‌التحصیل</th>
                    <th>بسته‌شده</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {years.map(y => (
                    <tr key={y.id}>
                      <td><strong>{y.title}</strong></td>
                      <td style={{ fontSize: '0.85rem' }}>{y.startsOn ?? '—'}</td>
                      <td style={{ fontSize: '0.85rem' }}>{y.endsOn ?? '—'}</td>
                      <td>
                        <span className={`badge ${y.status === 'active' ? 'badge-success' : 'badge-secondary'}`}>
                          {y.status === 'active' ? 'فعال' : 'بایگانی'}
                        </span>
                      </td>
                      <td style={{ textAlign: 'center' }}>{y.promotedStudents || '—'}</td>
                      <td style={{ textAlign: 'center' }}>{y.graduatedStudents || '—'}</td>
                      <td style={{ fontSize: '0.82rem', color: 'var(--color-text-soft)' }}>{y.closedAt ?? '—'}</td>
                      <td>
                        <a className="btn btn-soft btn-sm" href={`/school/years/${y.id}/archive`} style={{ marginLeft: 8 }}>
                          <i className="bi bi-archive" /> آرشیو
                        </a>
                        {y.status === 'active' && (
                          <button className="btn btn-danger btn-sm" type="button" onClick={() => setConfirmClose(y.id)}>
                            <i className="bi bi-calendar2-x" /> بستن سال
                          </button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </section>
      </div>

      {/* مدال تأیید بستن سال */}
      {confirmClose !== null && (
        <div className="modal-backdrop" onClick={() => setConfirmClose(null)}>
          <div className="modal-box" onClick={e => e.stopPropagation()} style={{ maxWidth: 460 }}>
            <h3 style={{ fontWeight: 700, marginBottom: '0.75rem', color: 'var(--color-danger, #DC2626)' }}>
              <i className="bi bi-exclamation-triangle-fill" /> بستن سال تحصیلی
            </h3>
            <p style={{ marginBottom: '0.5rem' }}>این عملیات <strong>غیرقابل برگشت</strong> است:</p>
            <ul style={{ paddingRight: '1.25rem', marginBottom: '1rem', fontSize: '0.9rem' }}>
              <li>پایه <strong>{activeStudentCount}</strong> دانش‌آموز فعال یک عدد افزایش می‌یابد</li>
              <li>دانش‌آموزان پایه ۱۲ فارغ‌التحصیل می‌شوند</li>
              <li>سال تحصیلی به آرشیو منتقل می‌شود</li>
            </ul>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '1rem' }}>
              <input
                type="checkbox"
                id="confirm_close"
                checked={closeForm.data.confirm}
                onChange={e => closeForm.setData('confirm', e.target.checked)}
                style={{ width: 18, height: 18 }}
              />
              <label htmlFor="confirm_close" style={{ fontSize: '0.9rem', cursor: 'pointer' }}>بله، مطمئنم و تأیید می‌کنم</label>
            </div>
            {closeForm.errors.confirm && <p className="form-error" style={{ marginBottom: '0.75rem' }}>{closeForm.errors.confirm}</p>}
            <div style={{ display: 'flex', gap: '0.75rem' }}>
              <button
                className="btn btn-danger"
                type="button"
                disabled={!closeForm.data.confirm || closeForm.processing}
                onClick={() => doClose(confirmClose)}
              >
                {closeForm.processing ? 'در حال پردازش...' : 'بستن سال تحصیلی'}
              </button>
              <button className="btn btn-ghost" type="button" onClick={() => setConfirmClose(null)}>انصراف</button>
            </div>
          </div>
        </div>
      )}
    </AppLayout>
  );
}
