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

type TableInfo = {
  name: string;
  rowCount: number;
  sizeMb: number;
  freeMb: number;
};

type Suggestion = {
  table: string;
  label: string;
  oldCount: number;
};

type Props = {
  tables: TableInfo[];
  totalSizeMb: number;
  totalFreeMb: number;
  suggestions: Suggestion[];
};

export default function DbOptimizer({ tables, totalSizeMb, totalFreeMb, suggestions }: Props) {
  const [optimizing, setOptimizing] = useState<string | null>(null);
  const [deleteDays, setDeleteDays] = useState<Record<string, string>>({});

  async function optimizeTable(name: string) {
    setOptimizing(name);
    const csrf = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
    await fetch('/super-admin/db-optimizer/optimize', {
      method: 'POST',
      headers: { 'X-CSRF-TOKEN': csrf, 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify({ table: name }),
    });
    setOptimizing(null);
    router.reload();
  }

  function deleteOldRecords(table: string) {
    const days = deleteDays[table] ?? '90';
    if (!confirm(`رکوردهای قدیمی‌تر از ${days} روز از جدول ${table} حذف شوند؟`)) return;
    router.delete('/super-admin/db-optimizer/delete-old', { data: { table, days }, preserveScroll: true });
  }

  return (
    <AppLayout title="بهینه‌سازی پایگاه داده">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2><i className="bi bi-database-gear" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />بهینه‌ساز پایگاه داده</h2>
            <p>مشاهده حجم جداول، پیشنهادات پاک‌سازی و بهینه‌سازی جداول</p>
          </div>
        </section>

        <div className="dashboard-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))' }}>
          <div className="panel-card" style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '1.6rem', fontWeight: 700, color: 'var(--color-primary)' }}>{totalSizeMb} MB</div>
            <div style={{ fontSize: '0.875rem', color: 'var(--color-text-muted)' }}>حجم کل پایگاه داده</div>
          </div>
          <div className="panel-card" style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '1.6rem', fontWeight: 700, color: 'var(--color-warning)' }}>{totalFreeMb} MB</div>
            <div style={{ fontSize: '0.875rem', color: 'var(--color-text-muted)' }}>فضای آزادسازی‌پذیر</div>
          </div>
          <div className="panel-card" style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '1.6rem', fontWeight: 700 }}>{tables.length}</div>
            <div style={{ fontSize: '0.875rem', color: 'var(--color-text-muted)' }}>تعداد جداول</div>
          </div>
        </div>

        {suggestions.length > 0 && (
          <section className="panel-card" style={{ borderColor: 'var(--color-warning)' }}>
            <h3 style={{ marginBottom: '1rem', color: 'var(--color-warning)' }}>
              <i className="bi bi-lightbulb" style={{ marginLeft: '0.4rem' }} />
              پیشنهادات پاک‌سازی
            </h3>
            <div className="page-stack" style={{ gap: '0.75rem' }}>
              {suggestions.map((s) => (
                <div key={s.table} style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', flexWrap: 'wrap', padding: '0.75rem', background: 'var(--color-bg-soft)', borderRadius: 'var(--radius-sm)' }}>
                  <div style={{ flex: 1 }}>
                    <strong>{s.label}</strong>
                    <span style={{ color: 'var(--color-text-muted)', fontSize: '0.875rem', marginRight: '0.5rem' }}>
                      ({s.oldCount} رکورد قدیمی‌تر از ۹۰ روز)
                    </span>
                  </div>
                  <input
                    type="number"
                    className="form-control"
                    style={{ width: 80 }}
                    value={deleteDays[s.table] ?? '90'}
                    min={1}
                    max={365}
                    onChange={(e) => setDeleteDays({ ...deleteDays, [s.table]: e.target.value })}
                  />
                  <span style={{ fontSize: '0.85rem' }}>روز</span>
                  <button className="btn btn-danger btn-sm" onClick={() => deleteOldRecords(s.table)}>
                    <i className="bi bi-trash" /> حذف قدیمی‌ها
                  </button>
                </div>
              ))}
            </div>
          </section>
        )}

        <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '0.75rem 1rem', borderBottom: '1px solid var(--color-border)' }}>
            <strong>جداول پایگاه داده</strong>
            <span style={{ color: 'var(--color-text-muted)', fontSize: '0.85rem', marginRight: '0.5rem' }}>مرتب‌سازی بر اساس حجم (بزرگ‌ترین اول)</span>
          </div>
          <div style={{ overflowX: 'auto' }}>
            <table className="data-table" style={{ width: '100%' }}>
              <thead>
                <tr>
                  <th>نام جدول</th>
                  <th>تعداد ردیف</th>
                  <th>حجم (MB)</th>
                  <th>فضای آزاد (MB)</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {tables.map((t) => (
                  <tr key={t.name}>
                    <td style={{ fontFamily: 'monospace', fontSize: '0.875rem' }}>{t.name}</td>
                    <td style={{ fontVariantNumeric: 'tabular-nums' }}>{t.rowCount.toLocaleString('fa-IR')}</td>
                    <td>
                      <span style={{
                        fontWeight: t.sizeMb > 10 ? 700 : 400,
                        color: t.sizeMb > 50 ? 'var(--color-danger)' : t.sizeMb > 10 ? 'var(--color-warning)' : undefined,
                      }}>
                        {t.sizeMb}
                      </span>
                    </td>
                    <td style={{ color: t.freeMb > 1 ? 'var(--color-warning)' : 'var(--color-text-muted)' }}>
                      {t.freeMb}
                    </td>
                    <td>
                      <button
                        className="btn btn-ghost btn-sm"
                        onClick={() => optimizeTable(t.name)}
                        disabled={optimizing === t.name}
                        title={`OPTIMIZE TABLE ${t.name}`}
                      >
                        {optimizing === t.name ? (
                          <i className="bi bi-arrow-repeat" style={{ animation: 'spin 1s linear infinite' }} />
                        ) : (
                          <i className="bi bi-gear" />
                        )}
                        {' '}بهینه‌سازی
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </section>
      </div>
    </AppLayout>
  );
}
