'use client';

import { useEffect, useState } from 'react';
import { Alert, App, Button, Input, Select } from 'antd';
import { Icon } from '../ui/Icon';
import { ChipTag, PageHeader, TablePager } from './PlatformPrimitives';
import { AUDIT_ACTION_LABELS, auditActionLabel, describeAuditDetails, relTime } from './platformFormat';
import { ApiError, apiRequest, getApiBaseUrl } from '../../lib/api';
import type { PlatformAuditLogItem } from './platformTypes';

interface AuditPage {
  items: PlatformAuditLogItem[];
  total: number;
  page: number;
  pageSize: number;
}

/** Names the record an audit entry is about, using the organization or person stored with it. */
function formatTarget(log: PlatformAuditLogItem): string {
  const meta = log.metadata as Record<string, unknown> | null;
  if (meta && typeof meta.organizationName === 'string') return `Organization: ${meta.organizationName}`;
  if (meta && typeof meta.name === 'string') return `${log.targetType ?? 'Record'}: ${meta.name}`;
  if (meta && typeof meta.email === 'string') return `${log.targetType ?? 'User'}: ${meta.email}`;
  return log.targetType || '—';
}

/** Full platform audit trail with server-side paging, search and an action filter, plus an Excel export. */
export function PlatformAuditView() {
  const { message } = App.useApp();
  const [search, setSearch] = useState('');
  const [q, setQ] = useState('');
  const [action, setAction] = useState<string | undefined>(undefined);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [data, setData] = useState<AuditPage | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [reload, setReload] = useState(0);
  const [exporting, setExporting] = useState(false);

  useEffect(() => {
    const id = setTimeout(() => {
      const trimmed = search.trim();
      setQ((prev) => {
        if (prev !== trimmed) setPage(1);
        return trimmed;
      });
    }, 300);
    return () => clearTimeout(id);
  }, [search]);

  useEffect(() => {
    let active = true;
    const params = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
    if (q) params.set('q', q);
    if (action) params.set('action', action);
    void (async () => {
      setLoading(true);
      setError(null);
      try {
        const res = await apiRequest<AuditPage>(`/platform/audit-logs/page?${params.toString()}`);
        if (active) setData(res);
      } catch (err) {
        if (active) setError(err instanceof ApiError ? err.message : 'Audit events could not be loaded.');
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => {
      active = false;
    };
  }, [page, pageSize, q, action, reload]);

  const handleExportExcel = async () => {
    try {
      setExporting(true);
      const res = await fetch(`${getApiBaseUrl()}/platform/audit-logs/export`, { credentials: 'include' });
      if (!res.ok) throw new Error(`Export failed with status ${res.status}`);
      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `platform-audit-logs-${new Date().toISOString().slice(0, 10)}.xlsx`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
      message.success('Platform audit logs exported to Excel.');
    } catch {
      message.error('Failed to export audit logs to Excel.');
    } finally {
      setExporting(false);
    }
  };

  const items = data?.items ?? [];
  const filtering = Boolean(q || action);

  return (
    <div>
      <PageHeader
        eyebrow="Governance"
        title="Platform audit"
        subtitle="Append-only trail of platform administrative actions persisted in the database."
        actions={
          <Button icon={<Icon name="download" size={14} />} loading={exporting} onClick={handleExportExcel}>
            Export Excel
          </Button>
        }
      />

      {error ? (
        <Alert
          type="error"
          showIcon
          title={error}
          className="mb-4"
          action={
            <Button size="small" onClick={() => setReload((n) => n + 1)}>
              Retry
            </Button>
          }
        />
      ) : null}

      <div className="tcx-surface-card overflow-hidden">
        <div className="flex flex-wrap items-center justify-between gap-3 border-b border-[var(--tcx-border)] px-4 py-3.5">
          <div className="flex w-full flex-wrap items-center gap-2 sm:w-auto">
            <Input allowClear prefix={<Icon name="search" size={15} />} placeholder="Search organization, actor, email or IP…" aria-label="Search audit events" value={search} onChange={(e) => setSearch(e.target.value)} className="w-full sm:!w-[320px]" />
            <Select
              allowClear
              placeholder="All actions"
              aria-label="Filter by action"
              value={action}
              onChange={(v) => {
                setAction(v);
                setPage(1);
              }}
              className="w-full sm:!w-[210px]"
              options={Object.entries(AUDIT_ACTION_LABELS).map(([value, label]) => ({ value, label }))}
            />
          </div>
          <span className="text-[12.5px] text-[var(--tcx-muted)]">{data ? `${data.total} ${filtering ? 'matching' : 'recorded'} event${data.total === 1 ? '' : 's'}` : ''}</span>
        </div>

        <div className="tcx-table-scroll">
          <table className="tcx-table">
            <thead>
              <tr>
                <th>When</th>
                <th>Actor</th>
                <th>Action</th>
                <th>Target</th>
                <th>Details</th>
                <th>IP</th>
              </tr>
            </thead>
            <tbody>
              {loading && items.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-10 text-center text-[var(--tcx-muted)]">
                    Loading audit events…
                  </td>
                </tr>
              ) : items.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-10 text-center text-[var(--tcx-muted)]">
                    {filtering ? 'No audit events match your filters.' : 'No platform audit events recorded yet.'}
                  </td>
                </tr>
              ) : (
                items.map((a) => (
                  <tr key={a.id} className={loading ? 'opacity-60' : undefined}>
                    <td className="whitespace-nowrap text-[var(--tcx-muted)]" title={new Date(a.createdAt).toLocaleString('en-IN')}>
                      {relTime(a.createdAt)}
                    </td>
                    <td>
                      {a.actor ? (
                        <div>
                          <div className="font-medium">{a.actor.name}</div>
                          <div className="text-[12px] text-[var(--tcx-muted)]">{a.actor.email}</div>
                        </div>
                      ) : (
                        <span className="text-[var(--tcx-muted)]">System</span>
                      )}
                    </td>
                    <td title={a.action}>
                      <ChipTag>{auditActionLabel(a.action)}</ChipTag>
                    </td>
                    <td>{formatTarget(a)}</td>
                    <td className="max-w-[300px] truncate text-[12.5px] text-[var(--tcx-text-2)]" title={a.metadata ? JSON.stringify(a.metadata) : undefined}>
                      {describeAuditDetails(a.action, a.metadata)}
                    </td>
                    <td className="font-mono text-[12px] text-[var(--tcx-muted)]">{a.ipAddress || '—'}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        <TablePager page={page} pageSize={pageSize} total={data?.total ?? 0} onPageChange={setPage} onPageSizeChange={setPageSize} pageSizeOptions={['20', '50', '100']} />
      </div>
    </div>
  );
}
