import { useState } from 'react';
import { useAuthStore } from '../../auth/auth-store';
import { useAuditLog, type AuditLogParams } from '../../api/queries/admin/audit';
import styles from './AuditLogPage.module.css';

function defaultFrom(): string {
  const d = new Date();
  d.setDate(d.getDate() - 7);
  return d.toISOString().slice(0, 10);
}

function defaultTo(): string {
  return new Date().toISOString().slice(0, 10);
}

export function AuditLogPage() {
  const roles = useAuthStore((s) => s.roles);

  if (!roles.includes('ADMIN')) {
    return (
      <div className={styles.page}>
        <div className={styles.accessDenied}>
          Access Denied — this page requires the ADMIN role.
        </div>
      </div>
    );
  }

  return <AuditLogContent />;
}

function AuditLogContent() {
  const [from, setFrom] = useState(defaultFrom);
  const [to, setTo] = useState(defaultTo);
  const [username, setUsername] = useState('');
  const [category, setCategory] = useState('');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(0);
  const [expandedRow, setExpandedRow] = useState<string | null>(null);
  const pageSize = 25;

  const params: AuditLogParams = {
    from: from || undefined,
    to: to || undefined,
    username: username || undefined,
    category: category || undefined,
    search: search || undefined,
    page,
    size: pageSize,
  };

  const audit = useAuditLog(params);
  const data = audit.data;
  const totalPages = data ? Math.ceil(data.total / pageSize) : 0;
  const showingFrom = data && data.total > 0 ? page * pageSize + 1 : 0;
  const showingTo = data ? Math.min((page + 1) * pageSize, data.total) : 0;

  return (
    <div className={styles.page}>
      <div className={styles.header}>
        <h1 className={styles.pageTitle}>Audit Log</h1>
        {data && (
          <span className={styles.totalCount}>{data.total.toLocaleString()} events</span>
        )}
      </div>

      <div className={styles.filters}>
        <div className={styles.filterGroup}>
          <label className={styles.filterLabel}>From</label>
          <input
            type="date"
            className={styles.filterInput}
            value={from}
            onChange={(e) => { setFrom(e.target.value); setPage(0); }}
          />
        </div>
        <div className={styles.filterGroup}>
          <label className={styles.filterLabel}>To</label>
          <input
            type="date"
            className={styles.filterInput}
            value={to}
            onChange={(e) => { setTo(e.target.value); setPage(0); }}
          />
        </div>
        <div className={styles.filterGroup}>
          <label className={styles.filterLabel}>User</label>
          <input
            type="text"
            className={styles.filterInput}
            placeholder="Username..."
            value={username}
            onChange={(e) => { setUsername(e.target.value); setPage(0); }}
          />
        </div>
        <div className={styles.filterGroup}>
          <label className={styles.filterLabel}>Category</label>
          <select
            className={styles.filterSelect}
            value={category}
            onChange={(e) => { setCategory(e.target.value); setPage(0); }}
          >
            <option value="">All</option>
            <option value="INFRA">INFRA</option>
            <option value="AUTH">AUTH</option>
            <option value="USER_MGMT">USER_MGMT</option>
            <option value="CONFIG">CONFIG</option>
          </select>
        </div>
        <div className={styles.filterGroup}>
          <label className={styles.filterLabel}>Search</label>
          <input
            type="text"
            className={styles.filterInput}
            placeholder="Search..."
            value={search}
            onChange={(e) => { setSearch(e.target.value); setPage(0); }}
          />
        </div>
      </div>

      {audit.isLoading ? (
        <div className={styles.loading}>Loading...</div>
      ) : !data || data.events.length === 0 ? (
        <div className={styles.emptyState}>No audit events found for the selected filters.</div>
      ) : (
        <>
          <div className={styles.tableWrapper}>
            <table className={styles.table}>
              <thead>
                <tr>
                  <th>Timestamp</th>
                  <th>User</th>
                  <th>Category</th>
                  <th>Action</th>
                  <th>Target</th>
                  <th>Result</th>
                </tr>
              </thead>
              <tbody>
                {data.events.map((event) => (
                  <>
                    <tr
                      key={event.id}
                      className={`${styles.eventRow} ${expandedRow === event.id ? styles.eventRowExpanded : ''}`}
                      onClick={() =>
                        setExpandedRow((prev) => (prev === event.id ? null : event.id))
                      }
                    >
                      <td className={styles.mono}>
                        {formatTimestamp(event.timestamp)}
                      </td>
                      <td>{event.username}</td>
                      <td>
                        <span className={styles.categoryBadge}>{event.category}</span>
                      </td>
                      <td>{event.action}</td>
                      <td className={styles.mono}>{event.target}</td>
                      <td>
                        <span
                          className={`${styles.resultBadge} ${
                            event.result === 'SUCCESS' ? styles.resultSuccess : styles.resultFailure
                          }`}
                        >
                          {event.result}
                        </span>
                      </td>
                    </tr>
                    {expandedRow === event.id && (
                      <tr key={`${event.id}-detail`} className={styles.detailRow}>
                        <td colSpan={6}>
                          <pre className={styles.detailJson}>
                            {JSON.stringify(event.detail, null, 2)}
                          </pre>
                        </td>
                      </tr>
                    )}
                  </>
                ))}
              </tbody>
            </table>
          </div>

          <div className={styles.pagination}>
            <button
              type="button"
              className={styles.pageBtn}
              disabled={page === 0}
              onClick={() => setPage((p) => p - 1)}
            >
              Previous
            </button>
            <span className={styles.pageInfo}>
              Showing {showingFrom}-{showingTo} of {data.total.toLocaleString()}
            </span>
            <button
              type="button"
              className={styles.pageBtn}
              disabled={page >= totalPages - 1}
              onClick={() => setPage((p) => p + 1)}
            >
              Next
            </button>
          </div>
        </>
      )}
    </div>
  );
}

function formatTimestamp(iso: string): string {
  try {
    const d = new Date(iso);
    return d.toLocaleString(undefined, {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    });
  } catch {
    return iso;
  }
}
