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

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

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

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',
};

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

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 chargeForm = useForm({ amount: '', description: '' });
  const renewForm = useForm({ expires_at: '' });
  const form = useForm({
    school_name: '',
    school_code: '',
    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 handleToggle(school: School) {
    const action = school.status === 'active' ? 'غیرفعال کردن' : 'فعال کردن';
    if (!confirm(`${action} مدرسه «${school.name}»؟`)) return;
    router.patch(`/super-admin/schools/${school.id}/toggle`, {}, { preserveScroll: true });
  }

  return (
    <AppLayout title="مدیریت مدارس">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>مدارس و License</h2>
            <p>ساخت مدرسه، تعریف owner، تنظیم license و مدیریت وضعیت.</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} />
              <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)} />
              <TextInput label="تاریخ پایان license" type="date" value={form.data.license_expires} onChange={(e) => form.setData('license_expires', e.target.value)} error={form.errors.license_expires} />
            </div>
            <h3>اطلاعات owner اصلی</h3>
            <div className="form-grid">
              <TextInput label="نام کاربری owner" 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="موبایل owner" 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">
              <TextInput
                label="تاریخ انقضا جدید"
                type="date"
                value={renewForm.data.expires_at}
                onChange={(e) => renewForm.setData('expires_at', e.target.value)}
                error={renewForm.errors.expires_at}
              />
            </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" /> شارژ SMS — مدرسه «{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>
        )}

        {schools.length > 0 ? (
          <div className="table-wrap">
            <table className="data-table">
              <thead>
                <tr>
                  <th>نام مدرسه</th>
                  <th>کد</th>
                  <th>شهر</th>
                  <th>Owner</th>
                  <th>پایان License</th>
                  <th>SMS</th>
                  <th>وضعیت</th>
                  <th>عملیات</th>
                </tr>
              </thead>
              <tbody>
                {schools.map((school) => (
                  <tr key={school.id}>
                    <td>{school.name}</td>
                    <td>{school.code}</td>
                    <td>{school.city}</td>
                    <td>{school.owner}</td>
                    <td>{school.expiresAt}</td>
                    <td>{formatCount(school.smsBalance)}</td>
                    <td>
                      <span className={`badge ${statusBadge[school.status] || 'badge-muted'}`}>
                        {statusLabel[school.status] || school.status}
                      </span>
                    </td>
                    <td>
                      <div className="action-row--compact">
                        <a
                          className="btn btn-soft btn-sm"
                          href={`/super-admin/schools/${school.id}/modules`}
                        >
                          <i className="bi bi-grid-3x3-gap" /> ماژول‌ها
                        </a>
                        <button
                          className="btn btn-soft btn-sm"
                          type="button"
                          onClick={() => setChargeTarget({ id: school.id, name: school.name })}
                        >
                          <i className="bi bi-wallet2" /> SMS
                        </button>
                        <button
                          className="btn btn-soft btn-sm"
                          type="button"
                          onClick={() => setRenewTarget({ id: school.id, name: school.name })}
                        >
                          <i className="bi bi-calendar-check" /> تمدید
                        </button>
                        <a
                          className="btn btn-ghost btn-sm"
                          href={`/super-admin/schools/${school.id}/export`}
                          title="خروجی ZIP داده‌های مدرسه"
                        >
                          <i className="bi bi-file-earmark-zip" />
                        </a>
                        <button
                          className="btn btn-ghost btn-sm"
                          type="button"
                          onClick={() => handleToggle(school)}
                        >
                          {school.status === 'active' ? 'غیرفعال' : 'فعال‌سازی'}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <section className="panel-card">
            <h2>هنوز مدرسه‌ای ساخته نشده</h2>
            <p>از دکمه «مدرسه جدید» اولین مدرسه را بساز.</p>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
