import { useMemo } from 'react';
import { Panel } from '@/components/ui/Panel';
import { DataTable, type Column } from '@/components/ui/DataTable';
import { Badge } from '@/components/ui/Badge';
import { EmptyState } from '@/components/ui/EmptyState';
import { History } from 'lucide-react';
import type { HistoryEntry } from './McpRequestBuilder';

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface McpHistoryProps {
  onReplay: (entry: HistoryEntry) => void;
  /** Increment this counter to force re-read from localStorage. */
  revision: number;
}

// ---------------------------------------------------------------------------
// Row type (flat version for DataTable)
// ---------------------------------------------------------------------------

interface HistoryRow {
  server: string;
  tool: string;
  paramsSummary: string;
  status: 'success' | 'error';
  timing: number;
  timestamp: string;
  _raw: HistoryEntry;
}

// ---------------------------------------------------------------------------
// Columns
// ---------------------------------------------------------------------------

const columns: Column<HistoryRow>[] = [
  { key: 'server', header: 'Server' },
  { key: 'tool', header: 'Tool' },
  { key: 'paramsSummary', header: 'Params', render: (v) => (
    <span className="font-mono text-xs truncate max-w-[200px] inline-block" title={String(v)}>
      {String(v)}
    </span>
  )},
  {
    key: 'status',
    header: 'Status',
    render: (v) => (
      <Badge status={v === 'success' ? 'ok' : 'error'}>{String(v)}</Badge>
    ),
  },
  {
    key: 'timing',
    header: 'Timing',
    sortable: true,
    render: (v) => <span>{String(v)} ms</span>,
  },
  {
    key: 'timestamp',
    header: 'Timestamp',
    sortable: true,
    render: (v) => {
      try {
        return <span>{new Date(String(v)).toLocaleTimeString()}</span>;
      } catch {
        return <span>{String(v)}</span>;
      }
    },
  },
];

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

const HISTORY_KEY = 'mcp-history';

function loadHistory(): HistoryEntry[] {
  try {
    const raw = localStorage.getItem(HISTORY_KEY);
    return raw ? (JSON.parse(raw) as HistoryEntry[]) : [];
  } catch {
    return [];
  }
}

function truncateParams(params: string, maxLen = 60): string {
  const trimmed = params.replace(/\s+/g, ' ').trim();
  return trimmed.length > maxLen ? trimmed.slice(0, maxLen) + '...' : trimmed;
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export function McpHistory({ onReplay, revision }: McpHistoryProps) {
  const rows = useMemo<HistoryRow[]>(() => {
    // revision is used to trigger re-computation
    void revision;
    return loadHistory().map((entry) => ({
      server: entry.server,
      tool: entry.tool,
      paramsSummary: truncateParams(entry.params),
      status: entry.status,
      timing: entry.timing,
      timestamp: entry.timestamp,
      _raw: entry,
    }));
  }, [revision]);

  return (
    <Panel title="History">
      {rows.length === 0 ? (
        <EmptyState
          icon={History}
          title="No history yet"
          description="Execute a tool to start building history."
        />
      ) : (
        <DataTable
          columns={columns}
          data={rows}
          pageSize={10}
          onRowClick={(row) => onReplay(row._raw)}
        />
      )}
    </Panel>
  );
}
