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

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 Pagination = { page: number; perPage: number; total: number; lastPage: number };
type Filters = { user: string; action: string; from: string; to: string };

type Props = {
  auditLogs: AuditEntry[];
  loginLogs: LoginEntry[];
  pagination: Pagination;
  filters: Filters;
};

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

  const search = () => {
    router.get('/school/audit-logs', { ...f, page: 1 }, { preserveState: true });
  };

  const goPage = (p: number) => {
    router.get('/school/audit-logs', { ...f, page: p }, { preserveState: true });
  };

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

        {/* فیلترها */}
        <section className="panel-card">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.65rem', alignItems: 'flex-end' }}>
            <div className="form-group" style={{ flex: '1 1 150px' }}>
              <label className="form-label">نام/کاربری</label>
              <input className="form-input" placeholder="جستجو..." value={f.user} onChange={e => setF(v => ({ ...v, user: e.target.value }))} />
            </div>
            <div className="form-group" style={{ flex: '1 1 150px' }}>
              <label className="form-label">نوع عملیات</label>
              <input className="form-input" placeholder="مثلاً: login" value={f.action} onChange={e => setF(v => ({ ...v, action: e.target.value }))} />
            </div>
            <div style={{ flex: '1 1 170px' }}><JalaliDatePicker label="از تاریخ" value={f.from} onChange={(value) => setF(v => ({ ...v, from: value }))} /></div>
            <div style={{ flex: '1 1 170px' }}><JalaliDatePicker label="تا تاریخ" value={f.to} onChange={(value) => setF(v => ({ ...v, to: value }))} /></div>
            <button className="btn btn-primary" type="button" onClick={search} style={{ flexShrink: 0 }}>
              <i className="bi bi-search" /> جستجو
            </button>
            <button className="btn btn-ghost" type="button" onClick={() => { setF({ user: '', action: '', from: '', to: '' }); router.get('/school/audit-logs'); }}>
              پاک کردن
            </button>
          </div>
        </section>

        <div className="tab-bar">
          <button className={`tab-btn${tab === 'audit' ? ' active' : ''}`} type="button" onClick={() => setTab('audit')}>
            <i className="bi bi-journal-check" /> فعالیت‌ها ({pagination.total})
          </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>

                {/* صفحه‌بندی */}
                {pagination.lastPage > 1 && (
                  <div style={{ display: 'flex', justifyContent: 'center', gap: '0.4rem', marginTop: '1rem', flexWrap: 'wrap' }}>
                    {Array.from({ length: pagination.lastPage }, (_, i) => i + 1).map(p => (
                      <button
                        key={p}
                        className={`btn btn-sm ${p === pagination.page ? 'btn-primary' : 'btn-ghost'}`}
                        type="button"
                        onClick={() => goPage(p)}
                      >
                        {p}
                      </button>
                    ))}
                  </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>
  );
}
