import { useState, useMemo } from 'react';
import { useParams } from 'react-router';
import {
  StatCard, StatusDot, Badge, MonoText, Sparkline,
  DataTable, DetailPanel, ProcessorTimeline, RouteFlow,
} from '@cameleer/design-system';
import type { Column } from '@cameleer/design-system';
import { useSearchExecutions, useExecutionStats, useStatsTimeseries, useExecutionDetail, useProcessorSnapshot } from '../../api/queries/executions';
import { useGlobalFilters } from '@cameleer/design-system';
import type { ExecutionSummary } from '../../api/types';

interface Row extends ExecutionSummary { id: string }

export default function Dashboard() {
  const { appId, routeId } = useParams();
  const { timeRange } = useGlobalFilters();
  const timeFrom = timeRange.start.toISOString();
  const timeTo = timeRange.end.toISOString();

  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [detailTab, setDetailTab] = useState('overview');
  const [processorIdx, setProcessorIdx] = useState<number | null>(null);

  const { data: stats } = useExecutionStats(timeFrom, timeTo, routeId, appId);
  const { data: timeseries } = useStatsTimeseries(timeFrom, timeTo, routeId, appId);
  const { data: searchResult } = useSearchExecutions({
    timeFrom, timeTo,
    routeId: routeId || undefined,
    group: appId || undefined,
    offset: 0, limit: 50,
  }, true);
  const { data: detail } = useExecutionDetail(selectedId);
  const { data: snapshot } = useProcessorSnapshot(selectedId, processorIdx);

  const rows: Row[] = useMemo(() =>
    (searchResult?.data || []).map((e: ExecutionSummary) => ({ ...e, id: e.executionId })),
    [searchResult],
  );

  const sparklineData = useMemo(() =>
    (timeseries?.buckets || []).map((b: any) => b.totalCount as number),
    [timeseries],
  );

  const columns: Column<Row>[] = [
    {
      key: 'status', header: 'Status', width: '80px',
      render: (v) => <StatusDot variant={v === 'COMPLETED' ? 'success' : v === 'FAILED' ? 'error' : 'running'} />,
    },
    { key: 'routeId', header: 'Route', render: (v) => <MonoText size="sm">{String(v)}</MonoText> },
    { key: 'groupName', header: 'App', render: (v) => <Badge label={String(v)} color="auto" /> },
    { key: 'executionId', header: 'Exchange ID', render: (v) => <MonoText size="xs">{String(v).slice(0, 12)}</MonoText> },
    { key: 'startTime', header: 'Started', sortable: true, render: (v) => new Date(v as string).toLocaleTimeString() },
    {
      key: 'durationMs', header: 'Duration', sortable: true,
      render: (v) => `${v}ms`,
    },
  ];

  const detailTabs = detail ? [
    {
      label: 'Overview', value: 'overview',
      content: (
        <div style={{ display: 'grid', gap: '0.75rem', padding: '1rem' }}>
          <div><strong>Execution ID:</strong> <MonoText size="sm">{detail.executionId}</MonoText></div>
          <div><strong>Status:</strong> <Badge label={detail.status} color={detail.status === 'COMPLETED' ? 'success' : 'error'} /></div>
          <div><strong>Route:</strong> {detail.routeId}</div>
          <div><strong>Duration:</strong> {detail.durationMs}ms</div>
          {detail.errorMessage && <div><strong>Error:</strong> {detail.errorMessage}</div>}
        </div>
      ),
    },
    {
      label: 'Processors', value: 'processors',
      content: detail.children ? (
        <ProcessorTimeline
          processors={flattenProcessors(detail.children)}
          totalMs={detail.durationMs}
          onProcessorClick={(_p, i) => setProcessorIdx(i)}
          selectedIndex={processorIdx ?? undefined}
        />
      ) : <div style={{ padding: '1rem' }}>No processor data</div>,
    },
  ] : [];

  return (
    <div>
      <div style={{ display: 'flex', gap: '1rem', marginBottom: '1.5rem', flexWrap: 'wrap' }}>
        <StatCard label="Total Exchanges" value={stats?.totalCount ?? 0} sparkline={sparklineData} />
        <StatCard label="Failed" value={stats?.failedCount ?? 0} accent="error" />
        <StatCard label="Avg Duration" value={`${stats?.avgDurationMs ?? 0}ms`} />
        <StatCard label="P99 Duration" value={`${stats?.p99LatencyMs ?? 0}ms`} accent="warning" />
        <StatCard label="Active" value={stats?.activeCount ?? 0} accent="running" />
      </div>

      <DataTable
        columns={columns}
        data={rows}
        onRowClick={(row) => { setSelectedId(row.id); setProcessorIdx(null); }}
        selectedId={selectedId ?? undefined}
        sortable
        pageSize={25}
      />

      <DetailPanel
        open={!!selectedId}
        onClose={() => setSelectedId(null)}
        title={selectedId ? `Exchange ${selectedId.slice(0, 12)}...` : ''}
        tabs={detailTabs}
      />
    </div>
  );
}

function flattenProcessors(nodes: any[]): any[] {
  const result: any[] = [];
  let offset = 0;
  function walk(node: any) {
    result.push({
      name: node.processorId || node.processorType,
      type: node.processorType,
      durationMs: node.durationMs ?? 0,
      status: node.status === 'COMPLETED' ? 'ok' : node.status === 'FAILED' ? 'fail' : 'ok',
      startMs: offset,
    });
    offset += node.durationMs ?? 0;
    if (node.children) node.children.forEach(walk);
  }
  nodes.forEach(walk);
  return result;
}
