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

type ActionTarget = { id: number; name: string } | null;

type School = {
  id: number;
  name: string;
  code: string;
  city: string;
  status: string;
  schoolType: string | null;
  owner: string;
  smsBalance: number;
  expiresAt: string;
  licenseStatus: string;
};

const schoolTypeLabel: Record<string, string> = {
  ebtedaee: 'ابتدایی',
  motevasete_aval: 'متوسطه اول',
  motevasete_dovom: 'متوسطه دوم',
};

type Props = {
  metrics: {
    activeSchools: number;
    totalStudents: number;
    totalTeachers: number;
  };
  schools: School[];
};

const statusBadge: Record<string, string> = {
  active: 'badge-success',
  inactive: 'badge-muted',
  suspended: 'badge-danger',
  archived: 'badge-muted',
};

const statusLabel: Record<string, string> = {
  active: 'فعال',
  inactive: 'غیرفعال',
  suspended: 'معلق',
  archived: 'آرشیو',
};

export default function Schools({ metrics, schools }: Props) {
  const { props } = usePage<{ flash?: { temp_password?: string } }>();
  const tempPassword = (props as { flash?: { temp_password?: string } }).flash?.temp_password;

  const [showForm, setShowForm] = useState(false);
  const [chargeTarget, setChargeTarget] = useState<ActionTarget>(null);
  const [renewTarget, setRenewTarget] = useState<ActionTarget>(null);
  const [alertTarget, setAlertTarget] = useState<ActionTarget>(null);
  const chargeForm = useForm({ amount: '', description: '' });
  const renewForm = useForm({ expires_at: '', status: 'active', max_students: '', max_teachers: '' });
  const alertForm = useForm({ title: '', body: '' });
  const form = useForm({
    school_name: '',
    school_code: '',
    school_type: '',
    city: '',
    province: '',
    phone: '',
    owner_username: '',
    owner_first_name: '',
    owner_last_name: '',
    owner_mobile: '',
    license_expires: '',
  });

  function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    form.post('/super-admin/schools', {
      onSuccess: () => {
        form.reset();
        setShowForm(false);
      },
    });
  }

  function handleChargeSubmit(event: React.FormEvent) {
    event.preventDefault();
    if (!chargeTarget) return;
    chargeForm.post(`/super-admin/schools/${chargeTarget.id}/charge-sms`, {
      onSuccess: () => { chargeForm.reset(); setChargeTarget(null); },
    });
  }

  function handleRenewSubmit(event: React.FormEvent) {
    event.preventDefault();
    if (!renewTarget) return;
    renewForm.patch(`/super-admin/schools/${renewTarget.id}/renew-license`, {
      onSuccess: () => { renewForm.reset(); setRenewTarget(null); },
    });
  }

  function handleAlertSubmit(event: React.FormEvent) {
    event.preventDefault();
    if (!alertTarget) return;
    alertForm.post(`/super-admin/schools/${alertTarget.id}/alert-owner`, {
      preserveScroll: true,
      onSuccess: () => { alertForm.reset(); setAlertTarget(null); },
    });
  }

  function handleToggle(school: School) {
    const action = school.status === 'active' ? 'غیرفعال کردن' : 'فعال کردن';
    if (!confirm(`${action} مدرسه «${school.name}»؟`)) return;
    router.patch(`/super-admin/schools/${school.id}/toggle`, {}, { preserveScroll: true });
  }

  function handleArchive(school: School) {
    const action = school.status === 'archived' ? 'خروج از آرشیو' : 'آرشیو کردن';
    if (!confirm(`${action} مدرسه «${school.name}»؟`)) return;
    router.patch(`/super-admin/schools/${school.id}/archive`, {}, { preserveScroll: true });
  }

  return (
    <AppLayout title="مدیریت مدارس">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>مدارس و مجوزها</h2>
            <p>ساخت مدرسه، تعریف مدیر ارشد، تنظیم مجوز و مدیریت وضعیت.</p>
          </div>
          <button className="btn btn-primary" type="button" onClick={() => setShowForm(!showForm)}>
            <i className="bi bi-building-add" /> مدرسه جدید
          </button>
        </section>

        {tempPassword && (
          <section className="panel-card" style={{ background: '#fef9c3', border: '1px solid #fde68a' }}>
            <h2><i className="bi bi-key" /> رمز موقت تولید شد</h2>
            <p style={{ fontFamily: 'monospace', fontSize: '1.1rem', fontWeight: 700 }}>{tempPassword}</p>
            <p>این رمز فقط یک بار نمایش داده می‌شود.</p>
          </section>
        )}

        <section className="dashboard-grid">
          <article className="metric-card"><span>مدارس فعال</span><strong>{formatCount(metrics.activeSchools)}</strong></article>
          <article className="metric-card"><span>دانش‌آموزان کل</span><strong>{formatCount(metrics.totalStudents)}</strong></article>
          <article className="metric-card"><span>معلمان کل</span><strong>{formatCount(metrics.totalTeachers)}</strong></article>
        </section>

        {showForm && (
          <form className="panel-card" onSubmit={handleSubmit}>
            <h2>ساخت مدرسه جدید</h2>
            <div className="form-grid">
              <TextInput label="نام مدرسه" value={form.data.school_name} onChange={(e) => form.setData('school_name', e.target.value)} error={form.errors.school_name} />
              <TextInput label="کد مدرسه (منحصربه‌فرد)" value={form.data.school_code} onChange={(e) => form.setData('school_code', e.target.value)} error={form.errors.school_code} />
              <div className="field-wrap">
                <label className="field-label">مقطع مدرسه <span className="text-danger">*</span></label>
                <select
                  className="field-input"
                  value={form.data.school_type}
                  onChange={(e) => form.setData('school_type', e.target.value)}
                >
                  <option value="">انتخاب مقطع</option>
                  <option value="ebtedaee">ابتدایی (پایه ۱ تا ۶)</option>
                  <option value="motevasete_aval">متوسطه اول (پایه ۷ تا ۹)</option>
                  <option value="motevasete_dovom">متوسطه دوم (پایه ۱۰ تا ۱۲)</option>
                </select>
                {form.errors.school_type && <span className="field-error">{form.errors.school_type}</span>}
                <p className="field-hint">پایه‌های مجاز بر اساس مقطع به‌صورت خودکار تنظیم می‌شود.</p>
              </div>
              <TextInput label="شهر" value={form.data.city} onChange={(e) => form.setData('city', e.target.value)} />
              <TextInput label="استان" value={form.data.province} onChange={(e) => form.setData('province', e.target.value)} />
              <TextInput label="تلفن مدرسه" value={form.data.phone} onChange={(e) => form.setData('phone', e.target.value)} />
              <JalaliDatePicker label="تاریخ پایان مجوز" value={form.data.license_expires} onChange={(value) => form.setData('license_expires', value)} error={form.errors.license_expires} />
            </div>
            <h3>اطلاعات مدیر ارشد مدرسه</h3>
            <div className="form-grid">
              <TextInput label="نام کاربری مدیر ارشد" value={form.data.owner_username} onChange={(e) => form.setData('owner_username', e.target.value)} error={form.errors.owner_username} />
              <TextInput label="نام" value={form.data.owner_first_name} onChange={(e) => form.setData('owner_first_name', e.target.value)} error={form.errors.owner_first_name} />
              <TextInput label="نام خانوادگی" value={form.data.owner_last_name} onChange={(e) => form.setData('owner_last_name', e.target.value)} error={form.errors.owner_last_name} />
              <TextInput label="موبایل مدیر ارشد" value={form.data.owner_mobile} onChange={(e) => form.setData('owner_mobile', e.target.value)} />
            </div>
            <div className="action-row">
              <button className="btn btn-primary" disabled={form.processing} type="submit">ساخت مدرسه</button>
              <button className="btn btn-ghost" type="button" onClick={() => setShowForm(false)}>لغو</button>
            </div>
          </form>
        )}

        {renewTarget && (
          <form className="panel-card" onSubmit={handleRenewSubmit} style={{ border: '2px solid var(--color-primary)' }}>
            <h2><i className="bi bi-calendar-check" /> تمدید مجوز — مدرسه «{renewTarget.name}»</h2>
            <div className="form-grid">
              <JalaliDatePicker
                label="تاریخ انقضا جدید"
                value={renewForm.data.expires_at}
                onChange={(value) => renewForm.setData('expires_at', value)}
                error={renewForm.errors.expires_at}
              />
              <div className="field-wrap">
                <label className="field-label">وضعیت مجوز</label>
                <select className="field-input" value={renewForm.data.status} onChange={(e) => renewForm.setData('status', e.target.value)}>
                  <option value="active">فعال</option>
                  <option value="suspended">معلق</option>
                  <option value="cancelled">لغو شده</option>
                  <option value="expired">منقضی</option>
                </select>
              </div>
              <TextInput label="حداکثر دانش‌آموز" type="number" value={renewForm.data.max_students} onChange={(e) => renewForm.setData('max_students', e.target.value)} />
              <TextInput label="حداکثر معلم" type="number" value={renewForm.data.max_teachers} onChange={(e) => renewForm.setData('max_teachers', e.target.value)} />
            </div>
            <div className="action-row">
              <button className="btn btn-primary" disabled={renewForm.processing} type="submit">تمدید</button>
              <button className="btn btn-ghost" type="button" onClick={() => { renewForm.reset(); setRenewTarget(null); }}>لغو</button>
            </div>
          </form>
        )}

        {chargeTarget && (
          <form className="panel-card" onSubmit={handleChargeSubmit} style={{ border: '2px solid var(--color-primary)' }}>
            <h2><i className="bi bi-wallet2" /> شارژ پیامک — مدرسه «{chargeTarget.name}»</h2>
            <div className="form-grid">
              <TextInput
                label="تعداد پیامک (واحد)"
                type="number"
                value={chargeForm.data.amount}
                onChange={(e) => chargeForm.setData('amount', e.target.value)}
                error={chargeForm.errors.amount}
              />
              <TextInput
                label="توضیح (اختیاری)"
                value={chargeForm.data.description}
                onChange={(e) => chargeForm.setData('description', e.target.value)}
              />
            </div>
            <div className="action-row">
              <button className="btn btn-primary" disabled={chargeForm.processing} type="submit">شارژ</button>
              <button className="btn btn-ghost" type="button" onClick={() => { chargeForm.reset(); setChargeTarget(null); }}>لغو</button>
            </div>
          </form>
        )}

        {alertTarget && (
          <form className="panel-card" onSubmit={handleAlertSubmit} style={{ border: '2px solid var(--color-warning)' }}>
            <h2><i className="bi bi-megaphone" /> اعلان به مدیر مدرسه «{alertTarget.name}»</h2>
            <div className="form-grid">
              <TextInput label="عنوان" value={alertForm.data.title} onChange={(e) => alertForm.setData('title', e.target.value)} error={alertForm.errors.title} />
              <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                <label className="form-label">متن</label>
                <textarea className="form-input" rows={3} value={alertForm.data.body} onChange={(e) => alertForm.setData('body', e.target.value)} />
                {alertForm.errors.body && <p className="form-error">{alertForm.errors.body}</p>}
              </div>
            </div>
            <div className="action-row">
              <button className="btn btn-primary" disabled={alertForm.processing} type="submit">ارسال اعلان</button>
              <button className="btn btn-ghost" type="button" onClick={() => { alertForm.reset(); setAlertTarget(null); }}>لغو</button>
            </div>
          </form>
        )}

        {schools.length > 0 ? (
          <div className="table-wrap super-schools-table-wrap">
            <table className="data-table super-schools-table">
              <thead>
                <tr>
                  <th>نام مدرسه</th>
                  <th>مقطع</th>
                  <th>کد</th>
                  <th>شهر</th>
                  <th>مالک</th>
                  <th>پایان مجوز</th>
                  <th>پیامک</th>
                  <th>وضعیت</th>
                  <th>عملیات</th>
                </tr>
              </thead>
              <tbody>
                {schools.map((school) => (
                  <tr key={school.id}>
                    <td className="school-name-cell">{school.name}</td>
                    <td>{school.schoolType ? schoolTypeLabel[school.schoolType] : '—'}</td>
                    <td className="school-code-cell">{school.code}</td>
                    <td>{school.city}</td>
                    <td className="school-owner-cell">{school.owner}</td>
                    <td className="school-license-cell">
                      {school.expiresAt}
                      <div style={{ fontSize: '0.75rem', color: 'var(--color-text-muted)' }}>{school.licenseStatus}</div>
                    </td>
                    <td className="school-sms-cell">{formatCount(school.smsBalance)}</td>
                    <td>
                      <span className={`badge ${statusBadge[school.status] || 'badge-muted'}`}>
                        {statusLabel[school.status] || school.status}
                      </span>
                    </td>
                    <td>
                      <div className="school-actions">
                        <a
                          className="school-action-btn school-action-btn--modules"
                          href={`/super-admin/schools/${school.id}/modules`}
                          title="مدیریت ماژول‌های مدرسه"
                        >
                          <i className="bi bi-grid-3x3-gap" />
                          <span>ماژول‌ها</span>
                        </a>
                        <button
                          className="school-action-btn school-action-btn--sms"
                          type="button"
                          onClick={() => setChargeTarget({ id: school.id, name: school.name })}
                          title="شارژ کیف پیامک"
                        >
                          <i className="bi bi-wallet2" />
                          <span>پیامک</span>
                        </button>
                        <button
                          className="school-action-btn school-action-btn--renew"
                          type="button"
                          onClick={() => setRenewTarget({ id: school.id, name: school.name })}
                          title="تمدید مجوز"
                        >
                          <i className="bi bi-calendar-check" />
                          <span>تمدید</span>
                        </button>
                        <button
                          className="school-action-btn school-action-btn--alert"
                          type="button"
                          onClick={() => setAlertTarget({ id: school.id, name: school.name })}
                          title="ارسال اعلان مستقیم به مالک مدرسه"
                        >
                          <i className="bi bi-megaphone" />
                          <span>اعلان</span>
                        </button>
                        <a
                          className="school-action-icon"
                          href={`/super-admin/schools/${school.id}/export`}
                          title="خروجی ZIP داده‌های مدرسه"
                        >
                          <i className="bi bi-file-earmark-zip" />
                        </a>
                        <button
                          className="school-action-btn school-action-btn--status"
                          type="button"
                          onClick={() => handleToggle(school)}
                          title={school.status === 'active' ? 'غیرفعال کردن مدرسه' : 'فعال کردن مدرسه'}
                        >
                          <i className={`bi ${school.status === 'active' ? 'bi-pause-circle' : 'bi-play-circle'}`} />
                          <span>{school.status === 'active' ? 'غیرفعال' : 'فعال‌سازی'}</span>
                        </button>
                        <button
                          className="school-action-btn school-action-btn--archive"
                          type="button"
                          onClick={() => handleArchive(school)}
                          title={school.status === 'archived' ? 'خروج از آرشیو' : 'آرشیو مدرسه'}
                        >
                          <i className="bi bi-archive" />
                          <span>{school.status === 'archived' ? 'خروج آرشیو' : 'آرشیو'}</span>
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <section className="panel-card">
            <h2>هنوز مدرسه‌ای ساخته نشده</h2>
            <p>از دکمه «مدرسه جدید» اولین مدرسه را بساز.</p>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
