'use client';

import { useEffect, useMemo, useState } from 'react';
import { type AuditTrailEntry, seedAuditTrailEntries } from '../lib/audit-trail';

function formatDate(value: string) {
  const date = new Date(value);
  return {
    day: date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }),
    time: date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }),
  };
}

function downloadCsv(rows: AuditTrailEntry[]) {
  const header = ['Timestamp', 'Admin User', 'Action Type', 'Module', 'IP Address', 'Severity', 'Details'];
  const csvRows = rows.map((row) =>
    [
      row.timestamp,
      row.adminUser,
      row.actionType,
      row.module,
      row.ipAddress,
      row.severity,
      row.details,
    ]
      .map((cell) => `"${String(cell).replaceAll('"', '""')}"`)
      .join(','),
  );

  const blob = new Blob([[header.join(','), ...csvRows].join('\n')], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.download = 'audit-trail-export.csv';
  anchor.click();
  URL.revokeObjectURL(url);
}

type Props = {
  initialEntries: AuditTrailEntry[];
  initialTotal?: number;
  initialPage?: number;
  initialPageSize?: number;
  initialTotalPages?: number;
};

const PAGE_SIZE_OPTIONS = [10, 25, 50, 100];

function buildVisiblePages(page: number, totalPages: number) {
  if (totalPages <= 5) {
    return Array.from({ length: totalPages }, (_, index) => index + 1);
  }

  const start = Math.max(1, Math.min(page - 2, totalPages - 4));
  return Array.from({ length: 5 }, (_, index) => start + index);
}

export function AuditTrailBoard({
  initialEntries,
  initialTotal,
  initialPage,
  initialPageSize,
  initialTotalPages,
}: Props) {
  const [allEntries] = useState<AuditTrailEntry[]>(initialEntries.length > 0 ? initialEntries : seedAuditTrailEntries);
  const [entries, setEntries] = useState<AuditTrailEntry[]>(initialEntries.length > 0 ? initialEntries : seedAuditTrailEntries);
  const [total, setTotal] = useState(initialTotal ?? initialEntries.length);
  const [page, setPage] = useState(initialPage ?? 1);
  const [pageSize, setPageSize] = useState(initialPageSize ?? 50);
  const [totalPages, setTotalPages] = useState(initialTotalPages ?? 1);
  const [range, setRange] = useState('7d');
  const [adminUser, setAdminUser] = useState('all');
  const [actionType, setActionType] = useState('all');
  const [moduleName, setModuleName] = useState('all');
  const [search, setSearch] = useState('');
  const [selectedEntryId, setSelectedEntryId] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setSelectedEntryId(initialEntries[0]?.id ?? seedAuditTrailEntries[0]?.id ?? null);
  }, [initialEntries]);

  useEffect(() => {
    const controller = new AbortController();
    const timeout = window.setTimeout(async () => {
      try {
        setIsLoading(true);
        const params = new URLSearchParams();
        params.set('page', String(page));
        params.set('limit', String(pageSize));
        if (range !== 'all') params.set('range', range);
        if (adminUser !== 'all') params.set('user', adminUser);
        if (actionType !== 'all') params.set('actionType', actionType);
        if (moduleName !== 'all') params.set('module', moduleName);
        if (search.trim()) params.set('search', search.trim());

        const response = await fetch(`/api/audit-trail?${params.toString()}`, {
          method: 'GET',
          signal: controller.signal,
          cache: 'no-store',
        });

        if (!response.ok) {
          return;
        }

        const payload = (await response.json()) as {
          items: Array<{
            id: string;
            actorName: string;
            actionType: string;
            module: string;
            ipAddress: string | null;
            severity: 'default' | 'alert';
            details: string;
            createdAt: string;
          }>;
          total: number;
          page: number;
          pageSize: number;
          totalPages: number;
        };

        const normalized = payload.items.map((entry) => ({
          id: entry.id,
          timestamp: entry.createdAt,
          adminUser: entry.actorName,
          actionType: entry.actionType,
          module: entry.module,
          ipAddress: entry.ipAddress || '-',
          severity: entry.severity,
          details: entry.details,
        }));

        setEntries(normalized);
        setTotal(payload.total);
        setPage(payload.page);
        setPageSize(payload.pageSize);
        setTotalPages(payload.totalPages);
      } catch (error) {
        if ((error as Error).name !== 'AbortError') {
          console.error(error);
        }
      } finally {
        setIsLoading(false);
      }
    }, 250);

    return () => {
      controller.abort();
      window.clearTimeout(timeout);
    };
  }, [actionType, adminUser, moduleName, page, pageSize, range, search]);

  const selectedEntry =
    entries.find((entry) => entry.id === selectedEntryId) ?? entries[0] ?? null;

  useEffect(() => {
    if (!selectedEntryId && entries[0]?.id) {
      setSelectedEntryId(entries[0].id);
      return;
    }

    if (selectedEntryId && !entries.some((entry) => entry.id === selectedEntryId)) {
      setSelectedEntryId(entries[0]?.id ?? null);
    }
  }, [entries, selectedEntryId]);

  const users = Array.from(new Set(allEntries.map((entry) => entry.adminUser)));
  const actions = Array.from(new Set(allEntries.map((entry) => entry.actionType)));
  const modules = Array.from(new Set(allEntries.map((entry) => entry.module)));

  const alertsCount = allEntries.filter((entry) => entry.severity === 'alert').length;
  const mostActiveAdmin =
    users
      .map((user) => ({
        user,
        count: allEntries.filter((entry) => entry.adminUser === user).length,
      }))
      .sort((a, b) => b.count - a.count)[0] ?? { user: 'Admin User', count: 0 };
  const visiblePages = useMemo(() => buildVisiblePages(page, totalPages), [page, totalPages]);
  const pageStart = entries.length === 0 ? 0 : (page - 1) * pageSize + 1;
  const pageEnd = entries.length === 0 ? 0 : (page - 1) * pageSize + entries.length;

  return (
    <>
      <section className="page-header">
        <div>
          <p className="page-eyebrow">Settings</p>
          <h1 className="page-heading">Audit Trail</h1>
          <p className="page-copy">Monitor administrative actions, role changes, and system modifications from one place.</p>
        </div>
        <button type="button" className="audit-export-button" onClick={() => downloadCsv(entries)}>
          <span className="material-symbols-outlined">download</span>
          Export to Excel
        </button>
        <a
          className="audit-export-button secondary"
          href={`/api/audit-trail/export?${new URLSearchParams({
            ...(range !== 'all' ? { range } : {}),
            ...(adminUser !== 'all' ? { user: adminUser } : {}),
            ...(actionType !== 'all' ? { actionType } : {}),
            ...(moduleName !== 'all' ? { module: moduleName } : {}),
            ...(search.trim() ? { search: search.trim() } : {}),
          }).toString()}`}
        >
          <span className="material-symbols-outlined">download</span>
          Export Server CSV
        </a>
      </section>

      <section className="audit-kpi-grid">
        <article className="audit-kpi-card">
          <div className="audit-kpi-head">
            <span>Total Actions (Last 24H)</span>
            <span className="material-symbols-outlined">history</span>
          </div>
          <div className="audit-kpi-metric">
            <strong>{entries.length.toLocaleString('en-US')}</strong>
            <span className="audit-kpi-trend is-positive">12.5%</span>
          </div>
          <div className="audit-kpi-bar">
            <div style={{ width: `${Math.min(100, 35 + entries.length * 8)}%` }} />
          </div>
        </article>

        <article className="audit-kpi-card">
          <div className="audit-kpi-head">
            <span>Security Alerts</span>
            <span className="material-symbols-outlined audit-danger">security</span>
          </div>
          <div className="audit-kpi-metric">
            <strong>{alertsCount.toString().padStart(2, '0')}</strong>
            <span className="audit-kpi-trend is-danger">Critical</span>
          </div>
          <p>Failed login bursts and suspicious access activity are surfaced here.</p>
        </article>

        <article className="audit-kpi-card">
          <div className="audit-kpi-head">
            <span>Most Active Admin</span>
            <span className="material-symbols-outlined audit-secondary">person</span>
          </div>
          <div className="audit-kpi-user">
            <div className="audit-avatar">{mostActiveAdmin.user.slice(0, 1)}</div>
            <div>
              <strong>{mostActiveAdmin.user}</strong>
              <span>{mostActiveAdmin.count} actions performed</span>
            </div>
          </div>
        </article>
      </section>

      <section className="audit-filter-bar">
        <div className="audit-filter-title">
          <span className="material-symbols-outlined">filter_list</span>
          <span>Filters</span>
        </div>

        <label className="audit-filter-field">
          <span>Date Range</span>
          <select value={range} onChange={(event) => {
            setRange(event.target.value);
            setPage(1);
          }}>
            <option value="24h">Last 24 Hours</option>
            <option value="7d">Last 7 Days</option>
            <option value="30d">Last 30 Days</option>
            <option value="all">All Time</option>
          </select>
        </label>

        <label className="audit-filter-field">
          <span>Admin User</span>
          <select value={adminUser} onChange={(event) => {
            setAdminUser(event.target.value);
            setPage(1);
          }}>
            <option value="all">All Admins</option>
            {users.map((user) => (
              <option key={user} value={user}>
                {user}
              </option>
            ))}
          </select>
        </label>

        <label className="audit-filter-field">
          <span>Action Type</span>
          <select value={actionType} onChange={(event) => {
            setActionType(event.target.value);
            setPage(1);
          }}>
            <option value="all">All Actions</option>
            {actions.map((action) => (
              <option key={action} value={action}>
                {action}
              </option>
            ))}
          </select>
        </label>

        <label className="audit-filter-field">
          <span>Module</span>
          <select value={moduleName} onChange={(event) => {
            setModuleName(event.target.value);
            setPage(1);
          }}>
            <option value="all">All Modules</option>
              {modules.map((module) => (
              <option key={module} value={module}>
                {module}
              </option>
            ))}
          </select>
        </label>

        <label className="audit-filter-search">
          <span>Search</span>
          <input
            type="search"
            value={search}
            onChange={(event) => {
              setSearch(event.target.value);
              setPage(1);
            }}
            placeholder="Search logs, admin names..."
          />
        </label>

        <button
          type="button"
          className="audit-reset-button"
          onClick={() => {
            setRange('7d');
            setAdminUser('all');
            setActionType('all');
            setModuleName('all');
            setSearch('');
            setPage(1);
          }}
        >
          Reset All
        </button>
      </section>

      <section className="audit-layout">
        <article className="audit-table-card">
          {isLoading ? <div className="audit-loading-bar" /> : null}
          <table className="audit-table">
            <thead>
              <tr>
                <th>Timestamp</th>
                <th>Admin User</th>
                <th>Action Type</th>
                <th>Module</th>
                <th>IP Address</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {entries.map((entry) => {
                const stamp = formatDate(entry.timestamp);
                const isSelected = entry.id === selectedEntry?.id;
                return (
                  <tr
                    key={entry.id}
                    className={`${entry.severity === 'alert' ? 'is-alert' : ''} ${isSelected ? 'is-selected' : ''}`}
                  >
                    <td>
                      <div className="audit-stamp">
                        <strong>{stamp.day}</strong>
                        <span>{stamp.time}</span>
                      </div>
                    </td>
                    <td>
                      <div className="audit-user-cell">
                        <div className={`audit-avatar small ${entry.severity === 'alert' ? 'is-alert' : ''}`}>
                          {entry.adminUser.slice(0, 1)}
                        </div>
                        <span>{entry.adminUser}</span>
                      </div>
                    </td>
                    <td>
                      <span className={`audit-action-pill tone-${entry.severity === 'alert' ? 'alert' : 'default'}`}>
                        {entry.actionType}
                      </span>
                    </td>
                    <td>{entry.module}</td>
                    <td className="audit-mono">{entry.ipAddress}</td>
                    <td className="audit-actions-cell">
                      <button type="button" onClick={() => setSelectedEntryId(entry.id)}>
                        View Details
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          <div className="audit-pagination">
            <div className="audit-pagination-meta">
              <span>
                Showing {pageStart} to {pageEnd} of {total} results
              </span>
              <label className="audit-page-size">
                <span>Show</span>
                <select
                  value={pageSize}
                  onChange={(event) => {
                    setPageSize(Number(event.target.value));
                    setPage(1);
                  }}
                >
                  {PAGE_SIZE_OPTIONS.map((option) => (
                    <option key={option} value={option}>
                      {option}
                    </option>
                  ))}
                </select>
                <span>rows</span>
              </label>
            </div>
            <div className="audit-pagination-buttons">
              <button type="button" disabled={page <= 1} onClick={() => setPage((current) => Math.max(1, current - 1))}>
                <span className="material-symbols-outlined">chevron_left</span>
              </button>
              {visiblePages.map((pageNumber) => (
                <button
                  key={pageNumber}
                  type="button"
                  className={pageNumber === page ? 'is-active' : ''}
                  onClick={() => setPage(pageNumber)}
                >
                  {pageNumber}
                </button>
              ))}
              {visiblePages[visiblePages.length - 1] < totalPages ? <span>...</span> : null}
              {visiblePages[visiblePages.length - 1] < totalPages ? (
                <button type="button" onClick={() => setPage(totalPages)}>
                  {totalPages}
                </button>
              ) : null}
              <button type="button" disabled={page >= totalPages} onClick={() => setPage((current) => Math.min(totalPages, current + 1))}>
                <span className="material-symbols-outlined">chevron_right</span>
              </button>
            </div>
          </div>
        </article>

        <aside className="audit-detail-card">
          {selectedEntry ? (
            <>
              <div className="card-head">
                <div>
                  <p className="card-kicker">Selected Event</p>
                  <h3>{selectedEntry.actionType}</h3>
                </div>
                <span className={`audit-action-pill tone-${selectedEntry.severity === 'alert' ? 'alert' : 'default'}`}>
                  {selectedEntry.module}
                </span>
              </div>
              <div className="detail-stack">
                <div>
                  <strong>{selectedEntry.adminUser}</strong>
                  <span>Actor</span>
                </div>
                <div>
                  <strong>{formatDate(selectedEntry.timestamp).day} {formatDate(selectedEntry.timestamp).time}</strong>
                  <span>Timestamp</span>
                </div>
                <div>
                  <strong>{selectedEntry.ipAddress}</strong>
                  <span>IP Address</span>
                </div>
                <div>
                  <strong>{selectedEntry.details}</strong>
                  <span>Details</span>
                </div>
              </div>
            </>
          ) : (
            <p>No audit entries found.</p>
          )}
        </aside>
      </section>
    </>
  );
}
