'use client';

import { useMemo } from 'react';
import { formatDuration } from '@/lib/utils';

interface Span {
  trace_id: string;
  span_id: string;
  parent_span_id?: string;
  service: string;
  operation: string;
  start_time: string;
  end_time: string;
  duration_ns: number;
  status: { code: string; message?: string };
  kind: string;
  attributes?: Record<string, any>;
}

interface Trace {
  trace_id: string;
  spans: Span[];
  duration_ns: number;
  start_time: string;
}

interface TraceTimelineProps {
  trace: Trace;
}

export function TraceTimeline({ trace }: TraceTimelineProps) {
  const { spans, minTime, maxTime, duration } = useMemo(() => {
    if (!trace.spans || trace.spans.length === 0) {
      return { spans: [], minTime: 0, maxTime: 0, duration: 0 };
    }

    const times = trace.spans.map((s) => ({
      start: new Date(s.start_time).getTime(),
      end: new Date(s.end_time).getTime(),
    }));

    const minTime = Math.min(...times.map((t) => t.start));
    const maxTime = Math.max(...times.map((t) => t.end));
    const duration = maxTime - minTime;

    // Sort spans by start time
    const sortedSpans = [...trace.spans].sort(
      (a, b) => new Date(a.start_time).getTime() - new Date(b.start_time).getTime()
    );

    return { spans: sortedSpans, minTime, maxTime, duration };
  }, [trace]);

  const serviceColors: Record<string, string> = {};
  const colors = [
    'bg-indigo-500',
    'bg-blue-500',
    'bg-green-500',
    'bg-yellow-500',
    'bg-purple-500',
    'bg-pink-500',
    'bg-cyan-500',
  ];

  spans.forEach((span, i) => {
    if (!serviceColors[span.service]) {
      serviceColors[span.service] = colors[Object.keys(serviceColors).length % colors.length];
    }
  });

  if (spans.length === 0) {
    return (
      <div className="flex items-center justify-center h-64 bg-gray-900/50 rounded-lg border border-gray-800 text-gray-500">
        No spans in this trace
      </div>
    );
  }

  return (
    <div className="bg-gray-900/50 rounded-lg border border-gray-800 overflow-hidden">
      {/* Header */}
      <div className="p-4 border-b border-gray-800">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="font-medium text-white">
              Trace: {trace.trace_id.slice(0, 16)}...
            </h3>
            <p className="text-sm text-gray-400">
              {spans.length} spans • {formatDuration(trace.duration_ns)}
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            {Object.entries(serviceColors).map(([service, color]) => (
              <span
                key={service}
                className="flex items-center gap-1 text-xs text-gray-400"
              >
                <span className={`w-2 h-2 rounded ${color}`} />
                {service}
              </span>
            ))}
          </div>
        </div>
      </div>

      {/* Timeline */}
      <div className="p-4 space-y-2 max-h-[400px] overflow-auto">
        {spans.map((span, i) => {
          const startOffset = new Date(span.start_time).getTime() - minTime;
          const spanDuration = span.duration_ns / 1000000; // ns to ms
          
          const left = duration > 0 ? (startOffset / duration) * 100 : 0;
          const width = duration > 0 ? Math.max((spanDuration / (duration / 1000000)) * 100, 1) : 100;
          
          const hasError = span.status?.code === 'ERROR';
          const color = hasError ? 'bg-red-500' : serviceColors[span.service];

          return (
            <div key={span.span_id} className="group">
              <div className="flex items-center gap-2 mb-1">
                <span className="text-xs text-gray-500 w-20 text-right font-mono">
                  {formatDuration(span.duration_ns)}
                </span>
                <span className={`w-2 h-2 rounded ${color}`} />
                <span className="text-sm text-gray-300 truncate flex-1">
                  {span.service}
                </span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-20" />
                <div className="flex-1 h-6 bg-gray-800 rounded relative">
                  <div
                    className={`absolute h-full rounded ${color} opacity-75 hover:opacity-100 transition-opacity cursor-pointer`}
                    style={{
                      left: `${left}%`,
                      width: `${Math.max(width, 0.5)}%`,
                      minWidth: '4px',
                    }}
                    title={`${span.operation}\n${formatDuration(span.duration_ns)}`}
                  />
                </div>
              </div>
              <div className="flex items-center gap-2 mt-1">
                <div className="w-20" />
                <span className="text-xs text-gray-500 truncate">
                  {span.operation}
                  {hasError && (
                    <span className="ml-2 text-red-400">
                      ⚠ {span.status.message || 'Error'}
                    </span>
                  )}
                </span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
