import { AppLayout } from '@/Components/Layout/AppLayout';

type FailedJob = {
  id: number | string;
  queue: string;
  failedAt: string;
  error: string;
};

type LoginStat = {
  day: string;
  success: number;
  failed: number;
};

type Props = {
  version: string;
  deployAt: string | null;
  phpVersion: string;
  laravelVersion: string;
  nodeVersion: string | null;
  redisPing: boolean;
  redisLatencyMs: number | null;
  dbPing: boolean;
  dbLatencyMs: number | null;
  pendingJobs: number;
  failedJobs: number;
  diskTotal: number | null;
  diskFree: number | null;
  diskUsedPct: number | null;
  schoolCount: number;
  activeSchools: number;
  userCount: number;
  studentCount: number;
  recentFailed: FailedJob[];
  loginStats: LoginStat[];
  cacheDriver: string;
  sessionDriver: string;
};

function StatusDot({ ok, label, extra }: { ok: boolean; label: string; extra?: string }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', padding: '0.6rem 0', borderBottom: '1px solid var(--color-border)' }}>
      <span style={{
        width: 10, height: 10, borderRadius: '50%', flexShrink: 0,
        background: ok ? '#16a34a' : '#dc2626',
        boxShadow: ok ? '0 0 6px #16a34a88' : '0 0 6px #dc262688',
      }} />
      <span style={{ fontWeight: 600, fontSize: '0.9rem' }}>{label}</span>
      {extra && <span style={{ color: 'var(--color-text-muted)', fontSize: '0.82rem', marginRight: 'auto' }}>{extra}</span>}
    </div>
  );
}

export default function Status({
  version, deployAt, phpVersion, laravelVersion, nodeVersion,
  redisPing, redisLatencyMs, dbPing, dbLatencyMs,
  pendingJobs, failedJobs,
  diskTotal, diskFree, diskUsedPct,
  schoolCount, activeSchools, userCount, studentCount,
  recentFailed, loginStats,
  cacheDriver, sessionDriver,
}: Props) {
  const diskColor = diskUsedPct !== null
    ? (diskUsedPct > 85 ? '#dc2626' : diskUsedPct > 70 ? '#d97706' : '#16a34a')
    : 'var(--color-text-muted)';

  return (
    <AppLayout title="وضعیت سیستم">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2><i className="bi bi-activity" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />وضعیت سیستم</h2>
            <p>نسخه، سرویس‌ها، صف‌ها و آمار کلی سامانه</p>
          </div>
          <div className="panel-card" style={{ padding: '0.5rem 1rem', display: 'flex', gap: '1.5rem', alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: '0.72rem', color: 'var(--color-text-muted)' }}>نسخه</div>
              <div style={{ fontFamily: 'monospace', fontWeight: 700, color: 'var(--color-primary)' }}>{version}</div>
            </div>
            {deployAt && (
              <div>
                <div style={{ fontSize: '0.72rem', color: 'var(--color-text-muted)' }}>آخرین استقرار</div>
                <div style={{ fontFamily: 'monospace', fontSize: '0.85rem' }}>{deployAt}</div>
              </div>
            )}
          </div>
        </section>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '1rem' }}>
          {/* Services health */}
          <section className="panel-card">
            <h3 style={{ marginBottom: '0.5rem' }}><i className="bi bi-heart-pulse" style={{ marginLeft: '0.4rem', color: 'var(--color-primary)' }} />سرویس‌ها</h3>
            <StatusDot ok={dbPing} label="پایگاه داده" extra={dbLatencyMs !== null ? `${dbLatencyMs}ms` : undefined} />
            <StatusDot ok={redisPing} label="Redis" extra={redisLatencyMs !== null ? `${redisLatencyMs}ms` : undefined} />
            <StatusDot ok={pendingJobs === 0} label="صف وظایف" extra={pendingJobs > 0 ? `${pendingJobs} در انتظار` : 'خالی'} />
            <StatusDot ok={failedJobs === 0} label="وظایف ناموفق" extra={failedJobs > 0 ? `${failedJobs} خطا` : 'بدون خطا'} />
          </section>

          {/* Versions */}
          <section className="panel-card">
            <h3 style={{ marginBottom: '0.5rem' }}><i className="bi bi-code-slash" style={{ marginLeft: '0.4rem' }} />نسخه‌های محیط</h3>
            {[
              ['PHP', phpVersion],
              ['Laravel', laravelVersion],
              ['Node.js', nodeVersion ?? 'نامشخص'],
              ['Cache', cacheDriver],
              ['Session', sessionDriver],
            ].map(([k, v]) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '0.45rem 0', borderBottom: '1px solid var(--color-border)', fontSize: '0.875rem' }}>
                <span style={{ color: 'var(--color-text-muted)' }}>{k}</span>
                <code style={{ fontFamily: 'monospace', color: 'var(--color-text)' }}>{v}</code>
              </div>
            ))}
          </section>

          {/* Disk */}
          <section className="panel-card">
            <h3 style={{ marginBottom: '0.75rem' }}><i className="bi bi-hdd" style={{ marginLeft: '0.4rem' }} />فضای دیسک</h3>
            {diskTotal !== null && diskFree !== null ? (
              <>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.875rem', marginBottom: '0.5rem' }}>
                  <span>استفاده‌شده</span>
                  <span style={{ fontWeight: 700, color: diskColor }}>{diskUsedPct}%</span>
                </div>
                <div style={{ height: 10, background: 'var(--color-border)', borderRadius: 5, overflow: 'hidden', marginBottom: '0.75rem' }}>
                  <div style={{ width: `${diskUsedPct ?? 0}%`, height: '100%', background: diskColor, borderRadius: 5, transition: 'width 0.4s' }} />
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>
                  <span>آزاد: {diskFree} GB</span>
                  <span>کل: {diskTotal} GB</span>
                </div>
              </>
            ) : (
              <p style={{ color: 'var(--color-text-muted)' }}>اطلاعات دیسک در دسترس نیست</p>
            )}
          </section>

          {/* School stats */}
          <section className="panel-card">
            <h3 style={{ marginBottom: '0.75rem' }}><i className="bi bi-building" style={{ marginLeft: '0.4rem' }} />آمار سامانه</h3>
            {[
              ['کل مدارس', schoolCount],
              ['مدارس فعال', activeSchools],
              ['کاربران', userCount],
              ['دانش‌آموزان فعال', studentCount],
            ].map(([k, v]) => (
              <div key={String(k)} style={{ display: 'flex', justifyContent: 'space-between', padding: '0.45rem 0', borderBottom: '1px solid var(--color-border)', fontSize: '0.875rem' }}>
                <span style={{ color: 'var(--color-text-muted)' }}>{k}</span>
                <strong style={{ fontVariantNumeric: 'tabular-nums' }}>{Number(v).toLocaleString('fa-IR')}</strong>
              </div>
            ))}
          </section>
        </div>

        {/* Login stats */}
        {loginStats.length > 0 && (
          <section className="panel-card">
            <h3 style={{ marginBottom: '0.75rem' }}><i className="bi bi-shield-check" style={{ marginLeft: '0.4rem' }} />ورودها (۷ روز اخیر)</h3>
            <div style={{ overflowX: 'auto' }}>
              <table className="data-table" style={{ width: '100%' }}>
                <thead>
                  <tr>
                    <th>تاریخ</th>
                    <th>موفق</th>
                    <th>ناموفق</th>
                    <th>نرخ شکست</th>
                  </tr>
                </thead>
                <tbody>
                  {loginStats.map((s) => {
                    const total = s.success + s.failed;
                    const failRate = total > 0 ? Math.round((s.failed / total) * 100) : 0;
                    return (
                      <tr key={s.day}>
                        <td style={{ fontFamily: 'monospace', direction: 'ltr', textAlign: 'right' }}>{s.day}</td>
                        <td style={{ color: '#16a34a', fontWeight: 600 }}>{s.success}</td>
                        <td style={{ color: s.failed > 0 ? '#dc2626' : 'var(--color-text-muted)', fontWeight: s.failed > 0 ? 600 : 400 }}>{s.failed}</td>
                        <td>
                          <span style={{ color: failRate > 20 ? '#dc2626' : 'var(--color-text-muted)', fontSize: '0.85rem' }}>
                            {failRate}%
                          </span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </section>
        )}

        {/* Failed jobs */}
        {recentFailed.length > 0 && (
          <section className="panel-card" style={{ borderColor: 'var(--color-danger)' }}>
            <h3 style={{ marginBottom: '0.75rem', color: '#dc2626' }}>
              <i className="bi bi-exclamation-triangle" style={{ marginLeft: '0.4rem' }} />
              وظایف ناموفق اخیر
            </h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              {recentFailed.map((j) => (
                <div key={j.id} style={{ padding: '0.6rem', background: 'var(--color-bg-soft)', borderRadius: 'var(--radius-sm)', fontSize: '0.82rem' }}>
                  <div style={{ display: 'flex', gap: '0.75rem', marginBottom: '0.25rem' }}>
                    <span style={{ color: 'var(--color-text-muted)' }}>صف: <strong>{j.queue}</strong></span>
                    <span style={{ color: 'var(--color-text-muted)', marginRight: 'auto', fontFamily: 'monospace' }}>{j.failedAt}</span>
                  </div>
                  <code style={{ fontSize: '0.78rem', color: '#dc2626', wordBreak: 'break-all' }}>{j.error}</code>
                </div>
              ))}
            </div>
          </section>
        )}
      </div>
    </AppLayout>
  );
}
