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

type AuditEntry = {
  id: number;
  action: string;
  entityType: string | null;
  entityId: number | null;
  oldValue: string | null;
  newValue: string | null;
  ip: string | null;
  createdAt: string;
  userName: string;
  userRole: string;
};

type LoginEntry = {
  username: string;
  status: string;
  ip: string | null;
  createdAt: string;
};

type Props = {
  auditLogs: AuditEntry[];
  loginLogs: LoginEntry[];
};

export default function AuditLogs({ auditLogs, loginLogs }: Props) {
  const [tab, setTab] = useState<'audit' | 'login'>('audit');
  const [expanded, setExpanded] = useState<number | null>(null);

  return (
    <AppLayout title="لاگ‌های مدرسه">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>لاگ‌های مدرسه</h2>
            <p>سابقه فعالیت‌ها و ورودهای کاربران این مدرسه.</p>
          </div>
        </section>

        <div className="tab-bar">
          <button className={`tab-btn${tab === 'audit' ? ' active' : ''}`} type="button" onClick={() => setTab('audit')}>
            <i className="bi bi-journal-check" /> فعالیت‌ها ({auditLogs.length})
          </button>
          <button className={`tab-btn${tab === 'login' ? ' active' : ''}`} type="button" onClick={() => setTab('login')}>
            <i className="bi bi-box-arrow-in-right" /> لاگ ورود ({loginLogs.length})
          </button>
        </div>

        {tab === 'audit' && (
          <section className="panel-card">
            {auditLogs.length === 0 ? (
              <p style={{ color: 'var(--color-text-muted)' }}>هیچ فعالیتی ثبت نشده است.</p>
            ) : (
              <div className="table-wrap">
                <table className="data-table">
                  <thead>
                    <tr>
                      <th>کاربر</th>
                      <th>نقش</th>
                      <th>عملیات</th>
                      <th>موجودیت</th>
                      <th>IP</th>
                      <th>زمان</th>
                      <th></th>
                    </tr>
                  </thead>
                  <tbody>
                    {auditLogs.map((log) => (
                      <>
                        <tr key={log.id}>
                          <td>{log.userName}</td>
                          <td style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>{log.userRole}</td>
                          <td>
                            <code style={{ fontSize: '0.8rem', background: 'var(--color-surface-muted)', padding: '0.1rem 0.4rem', borderRadius: '4px' }}>
                              {log.action}
                            </code>
                          </td>
                          <td style={{ fontSize: '0.85rem', color: 'var(--color-text-muted)' }}>
                            {log.entityType ?? '—'}{log.entityId ? ` #${log.entityId}` : ''}
                          </td>
                          <td style={{ fontFamily: 'monospace', fontSize: '0.8rem' }}>{log.ip ?? '—'}</td>
                          <td style={{ fontSize: '0.85rem', color: 'var(--color-text-muted)' }}>{log.createdAt}</td>
                          <td>
                            {(log.oldValue || log.newValue) && (
                              <button
                                className="btn btn-ghost btn-sm"
                                type="button"
                                onClick={() => setExpanded(expanded === log.id ? null : log.id)}
                              >
                                <i className={`bi bi-chevron-${expanded === log.id ? 'up' : 'down'}`} />
                              </button>
                            )}
                          </td>
                        </tr>
                        {expanded === log.id && (
                          <tr>
                            <td colSpan={7} style={{ background: 'var(--color-bg-soft)', padding: '0.75rem 1rem' }}>
                              {log.oldValue && (
                                <div style={{ marginBottom: '0.5rem' }}>
                                  <strong style={{ color: 'var(--color-danger)', marginLeft: '0.5rem' }}>قبل:</strong>
                                  <code style={{ fontSize: '0.8rem', wordBreak: 'break-all' }}>{log.oldValue}</code>
                                </div>
                              )}
                              {log.newValue && (
                                <div>
                                  <strong style={{ color: 'var(--color-success)', marginLeft: '0.5rem' }}>بعد:</strong>
                                  <code style={{ fontSize: '0.8rem', wordBreak: 'break-all' }}>{log.newValue}</code>
                                </div>
                              )}
                            </td>
                          </tr>
                        )}
                      </>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </section>
        )}

        {tab === 'login' && (
          <section className="panel-card">
            {loginLogs.length === 0 ? (
              <p style={{ color: 'var(--color-text-muted)' }}>هیچ لاگ ورودی ثبت نشده است.</p>
            ) : (
              <div className="table-wrap">
                <table className="data-table">
                  <thead>
                    <tr>
                      <th>نام کاربری</th>
                      <th>وضعیت</th>
                      <th>IP</th>
                      <th>زمان</th>
                    </tr>
                  </thead>
                  <tbody>
                    {loginLogs.map((log, i) => (
                      <tr key={i}>
                        <td>{log.username}</td>
                        <td>
                          <span className={`badge ${log.status === 'success' ? 'badge-success' : 'badge-danger'}`}>
                            {log.status === 'success' ? 'موفق' : 'ناموفق'}
                          </span>
                        </td>
                        <td style={{ fontFamily: 'monospace', fontSize: '0.85rem' }}>{log.ip ?? '—'}</td>
                        <td style={{ fontSize: '0.85rem', color: 'var(--color-text-muted)' }}>{log.createdAt}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </section>
        )}
      </div>
    </AppLayout>
  );
}
