'use client';

import { useState } from 'react';
import type { ConnectionDetail } from '@/features/integrations/api.client';
import { activityLabel, downloadCsv, when } from './data';
import { ICON, LogDropdown, NoLogs, useMenu } from './ui';

/**
 * Logs › Security (and the Auth tab's token history): the app's audit trail, from
 * GET /integrations/connections/private_app:<id> (`activity`).
 */

type Activity = ConnectionDetail['activity'][number];

export function SecurityLog({
  activity,
  error,
  compact = false,
}: {
  activity: Activity[] | null;
  error: string | null;
  compact?: boolean;
}) {
  const { menu, toggle } = useMenu();
  const [actions, setActions] = useState<string[]>([]);
  const [actionSearch, setActionSearch] = useState('');
  const [from, setFrom] = useState('');
  const [to, setTo] = useState('');

  if (error) return <NoLogs title="Couldn't load the history." text={error} />;
  if (activity === null) return <NoLogs title="Loading history…" text="One moment." />;

  const options = [...new Set(activity.map((a) => a.action))];
  const shown = compact
    ? activity
    : activity.filter(
        (a) =>
          (!actions.length || actions.includes(a.action)) &&
          (!from || new Date(a.createdAt) >= new Date(`${from}T00:00:00`)) &&
          (!to || new Date(a.createdAt) <= new Date(`${to}T23:59:59.999`)),
      );

  const table = shown.length ? (
    <div className="la-log-table-wrap">
      <table className="la-log-table">
        <thead>
          <tr>
            <th>Date</th>
            <th>User</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          {shown.map((a) => (
            <tr key={a.id}>
              <td>{when(a.createdAt)}</td>
              <td>{a.actorName}</td>
              <td>{activityLabel(a.action)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  ) : activity.length ? (
    <NoLogs />
  ) : (
    <NoLogs title="No history yet." text="Creating, rotating and revoking the token shows here." />
  );
  if (compact) return table;

  const q = actionSearch.trim().toLowerCase();
  return (
    <>
      <div className="la-log-filters">
        <span>Filter by:</span>
        <LogDropdown
          id="sec-action"
          label={actions.length ? `Action type (${actions.length})` : 'Action type'}
          open={menu}
          onToggle={toggle}
          search
        >
          <input
            type="search"
            placeholder="Search"
            value={actionSearch}
            onChange={(e) => setActionSearch(e.target.value)}
          />
          {options
            .filter((o) => !q || activityLabel(o).toLowerCase().includes(q))
            .map((o) => (
              <label key={o} className="check">
                <input
                  type="checkbox"
                  checked={actions.includes(o)}
                  onChange={(e) =>
                    setActions((cur) =>
                      e.target.checked ? [...cur, o] : cur.filter((x) => x !== o),
                    )
                  }
                />
                <span className="check__box" />
                <span>{activityLabel(o)}</span>
              </label>
            ))}
        </LogDropdown>
        <div className="la-dates">
          <input
            type="date"
            aria-label="From date"
            value={from}
            onChange={(e) => setFrom(e.target.value)}
          />
          <span>to</span>
          <input
            type="date"
            aria-label="To date"
            value={to}
            onChange={(e) => setTo(e.target.value)}
          />
        </div>
      </div>
      <div className="la-log-search-row" style={{ justifyContent: 'flex-end' }}>
        <button
          type="button"
          className="la-export"
          disabled={!shown.length}
          onClick={() =>
            downloadCsv('legacy-app-security-log.csv', [
              ['Date', 'User', 'Action'],
              ...shown.map((a) => [a.createdAt, a.actorName, activityLabel(a.action)]),
            ])
          }
        >
          {ICON.download} Export logs (CSV)
        </button>
      </div>
      {table}
    </>
  );
}
