import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router';
import { Input, Button, LogViewer } from '@cameleer/design-system';
import type { LogEntry } from '@cameleer/design-system';
import { useLogs } from '../../../api/queries/logs';
import type { LogEntryResponse } from '../../../api/queries/logs';
import { useEnvironmentStore } from '../../../api/environment-store';
import { mapLogLevel } from '../../../utils/agent-utils';
import logStyles from './LogTab.module.css';
import diagramStyles from '../ExecutionDiagram.module.css';

interface LogTabProps {
  applicationId: string;
  exchangeId?: string;
  processorId: string | null;
}

function matchesProcessor(e: LogEntryResponse, pid: string): boolean {
  // Prefer the explicit MDC key set by the agent
  if (e.mdc?.['cameleer.processorId'] === pid) return true;
  // Fallback: fuzzy match in message/logger for older agents
  if (e.message?.includes(pid)) return true;
  if (e.loggerName?.includes(pid)) return true;
  return false;
}

export function LogTab({ applicationId, exchangeId, processorId }: LogTabProps) {
  const [filter, setFilter] = useState('');
  const navigate = useNavigate();

  const environment = useEnvironmentStore((s) => s.environment) ?? '';
  const { data: logPage, isLoading } = useLogs(
    { exchangeId, environment, limit: 500 },
    { enabled: !!exchangeId && !!environment },
  );

  const entries = useMemo<LogEntry[]>(() => {
    if (!logPage?.data) return [];
    let items = [...logPage.data];

    // If a processor is selected, filter logs to that processor
    if (processorId) {
      items = items.filter((e) => matchesProcessor(e, processorId));
    }

    // Text filter
    if (filter) {
      const q = filter.toLowerCase();
      items = items.filter((e) =>
        e.message?.toLowerCase().includes(q) ||
        e.level?.toLowerCase().includes(q) ||
        e.loggerName?.toLowerCase().includes(q)
      );
    }

    return items.map((e) => ({
      timestamp: e.timestamp ?? '',
      level: mapLogLevel(e.level),
      message: e.message ?? '',
      source: e.source ?? undefined,
    }));
  }, [logPage, processorId, filter]);

  if (isLoading) {
    return <div className={diagramStyles.emptyState}>Loading logs...</div>;
  }

  return (
    <div className={logStyles.container}>
      <div className={logStyles.filterBar}>
        <Input
          placeholder="Filter logs..."
          value={filter}
          onChange={(e) => setFilter(e.target.value)}
          onClear={() => setFilter('')}
          className={logStyles.filterInput}
        />
      </div>
      <div className={logStyles.logList}>
        {entries.length === 0 ? (
          <div className={diagramStyles.emptyState}>
            {processorId ? 'No logs for this processor' : 'No logs available'}
          </div>
        ) : (
          <>
            <LogViewer entries={entries} maxHeight={360} />
            {exchangeId && (
              <div className={logStyles.footer}>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => navigate(`/runtime/${applicationId}`)}
                >
                  Open in Runtime {'\u2192'}
                </Button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
