import { router, useForm } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { DataTable } from '@/Components/Tables/DataTable';
import { UsageChart } from '@/Components/Charts/UsageChart';
import { JalaliDatePicker } from '@/Components/Forms/JalaliDatePicker';
import { formatCount } from '@/lib/formatters';

type SchoolSms = {
  id: number;
  name: string;
  totalCharged: number;
  totalUsed: number;
  balance: number;
};
type SmsMessage = { id: number; schoolName: string; targetType: string; recipientCount: number; cost: number; status: string; sender: string; createdAt: string };
type WalletTx = { id: number; schoolName: string; type: string; amount: number; before: number; after: number; description: string | null; createdAt: string };
type Payment = { id: number; schoolName: string; invoiceNumber: string | null; invoiceType: string | null; amount: number; status: string; providerName: string | null; paidAt: string | null; createdAt: string };

type ChargeRequest = {
  id: number;
  schoolName: string;
  schoolId: number;
  smsCount: number;
  price: number;
  requestedBy: string;
  createdAt: string;
};

type Props = {
  metrics: {
    totalCharged: number;
    sentThisMonth: number;
    schoolsWithSms: number;
  };
  chart: number[];
  schools: SchoolSms[];
  chargeRequests: ChargeRequest[];
  messages: SmsMessage[];
  transactions: WalletTx[];
  payments: Payment[];
  filters: { school_id: number | null; from: string; to: string };
};

export default function SmsUsage({ metrics, chart, schools, chargeRequests, messages, transactions, payments, filters }: Props) {
  const approveForm = useForm({});
  const rejectForm = useForm({});
  const filterForm = useForm({
    school_id: filters.school_id ? String(filters.school_id) : '',
    from: filters.from,
    to: filters.to,
  });

  const rows = schools.map((school) => [
    school.name,
    formatCount(school.totalCharged),
    formatCount(school.totalUsed),
    formatCount(school.balance),
  ]);
  const max = Math.max(...chart, 1);
  const chartValues = chart.map((value) => Math.max(8, Math.round((value / max) * 100)));

  function approve(id: number) {
    approveForm.post(`/super-admin/sms-charge-requests/${id}/approve`);
  }

  function reject(id: number) {
    if (!confirm('رد درخواست شارژ؟')) return;
    rejectForm.post(`/super-admin/sms-charge-requests/${id}/reject`);
  }

  function applyFilters(e: React.FormEvent) {
    e.preventDefault();
    router.get('/super-admin/sms-usage', {
      school_id: filterForm.data.school_id || undefined,
      from: filterForm.data.from,
      to: filterForm.data.to,
    }, { preserveState: true });
  }

  return (
    <AppLayout title="گزارش پیامک مدارس">
      <div className="page-stack">
        <section className="dashboard-grid">
          <article className="metric-card"><span>کل پیامک‌های فروخته‌شده</span><strong>{formatCount(metrics.totalCharged)}</strong></article>
          <article className="metric-card"><span>ارسال موفق ماه</span><strong>{formatCount(metrics.sentThisMonth)}</strong></article>
          <article className="metric-card"><span>مدارس دارای پیامک</span><strong>{formatCount(metrics.schoolsWithSms)}</strong></article>
        </section>

        <section className="panel-card">
          <form onSubmit={applyFilters} className="form-grid">
            <div className="form-group">
              <label className="form-label">مدرسه</label>
              <select className="form-input" value={filterForm.data.school_id} onChange={(e) => filterForm.setData('school_id', e.target.value)}>
                <option value="">همه مدارس</option>
                {schools.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
            <JalaliDatePicker label="از" value={filterForm.data.from} onChange={(value) => filterForm.setData('from', value)} />
            <JalaliDatePicker label="تا" value={filterForm.data.to} onChange={(value) => filterForm.setData('to', value)} />
            <div style={{ alignSelf: 'end' }}>
              <button className="btn btn-primary" type="submit"><i className="bi bi-funnel" /> اعمال</button>
            </div>
          </form>
        </section>

        {chargeRequests.length > 0 && (
          <section className="panel-card" style={{ border: '2px solid var(--color-warning)' }}>
            <h2><i className="bi bi-clock-fill" style={{ marginLeft: '0.4rem', color: 'var(--color-warning)' }} />درخواست‌های شارژ کیف پول ({chargeRequests.length})</h2>
            <div className="table-wrap" style={{ padding: 0, overflow: 'hidden', marginTop: '1rem' }}>
              <table className="data-table">
                <thead>
                  <tr>
                    <th>مدرسه</th>
                    <th>بسته</th>
                    <th>مبلغ (تومان)</th>
                    <th>درخواست‌کننده</th>
                    <th>تاریخ</th>
                    <th>عملیات</th>
                  </tr>
                </thead>
                <tbody>
                  {chargeRequests.map((req) => (
                    <tr key={req.id}>
                      <td>{req.schoolName}</td>
                      <td><span className="badge badge-success">{formatCount(req.smsCount)} پیامک</span></td>
                      <td>{formatCount(req.price)}</td>
                      <td>{req.requestedBy}</td>
                      <td style={{ fontSize: '0.85rem', color: 'var(--color-text-muted)' }}>{req.createdAt}</td>
                      <td>
                        <div className="action-row--compact">
                          <button
                            className="btn btn-primary btn-sm"
                            type="button"
                            disabled={approveForm.processing}
                            onClick={() => approve(req.id)}
                          >
                            <i className="bi bi-check" /> تایید
                          </button>
                          <button
                            className="btn btn-ghost btn-sm"
                            type="button"
                            disabled={rejectForm.processing}
                            onClick={() => reject(req.id)}
                          >
                            <i className="bi bi-x" /> رد
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        )}

        <section className="split-panel">
          <article className="panel-card">
            <h2>مصرف مدارس در ۷ روز اخیر</h2>
            {chart.length > 0 ? <UsageChart values={chartValues} /> : <p>هنوز مصرفی ثبت نشده است.</p>}
          </article>
          <article className="panel-card">
            <h2>قانون wallet</h2>
            <p>برای هر recipient که provider با موفقیت تایید کند، یک اعتبار از کیف پول همان مدرسه کم می‌شود.</p>
            <span className="status-pill warning">provider بعدا انتخاب می‌شود</span>
          </article>
        </section>

        {rows.length > 0
          ? <DataTable columns={['مدرسه', 'شارژ شده', 'مصرف شده', 'مانده']} rows={rows} />
          : <section className="panel-card"><h2>کیف پولی ثبت نشده</h2><p>بعد از ساخت wallet مدرسه‌ها، گزارش واقعی اینجا نمایش داده می‌شود.</p></section>}

        <DetailTable
          title="جزئیات ارسال پیامک"
          columns={['مدرسه', 'هدف', 'گیرنده', 'هزینه', 'وضعیت', 'فرستنده', 'تاریخ']}
          rows={messages.map((m) => [m.schoolName, m.targetType, formatCount(m.recipientCount), formatCount(m.cost), m.status, m.sender, m.createdAt])}
        />

        <DetailTable
          title="تراکنش‌های کیف پول"
          columns={['مدرسه', 'نوع', 'مقدار', 'قبل', 'بعد', 'شرح', 'تاریخ']}
          rows={transactions.map((tx) => [tx.schoolName, tx.type, formatCount(tx.amount), formatCount(tx.before), formatCount(tx.after), tx.description ?? '—', tx.createdAt])}
        />

        <DetailTable
          title="پرداخت‌ها و فاکتورها"
          columns={['مدرسه', 'فاکتور', 'نوع', 'مبلغ', 'وضعیت', 'درگاه', 'تاریخ']}
          rows={payments.map((p) => [p.schoolName, p.invoiceNumber ?? '—', p.invoiceType ?? '—', formatCount(p.amount), p.status, p.providerName ?? '—', p.paidAt ?? p.createdAt])}
        />
      </div>
    </AppLayout>
  );
}

function DetailTable({ title, columns, rows }: { title: string; columns: string[]; rows: (string | number)[][] }) {
  return (
    <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{ padding: '1rem 1rem 0' }}><h2 style={{ margin: 0 }}>{title}</h2></div>
      {rows.length === 0 ? (
        <p style={{ textAlign: 'center', padding: '2rem', color: 'var(--color-text-muted)' }}>داده‌ای در این بازه نیست.</p>
      ) : (
        <div style={{ overflowX: 'auto' }}>
          <table className="data-table" style={{ width: '100%' }}>
            <thead><tr>{columns.map((c) => <th key={c}>{c}</th>)}</tr></thead>
            <tbody>{rows.map((row, i) => <tr key={i}>{row.map((cell, j) => <td key={j}>{cell}</td>)}</tr>)}</tbody>
          </table>
        </div>
      )}
    </section>
  );
}
