'use client';

import { useState } from 'react';
import { Trash2, ChevronDown } from 'lucide-react';

interface SpanAnnotation {
  id: number;
  chart_id: number;
  start_time: number;
  end_time: number;
  label: string;
  confidence: number | null;
  outcome: string | null;
  notes: string | null;
  sub_spans: any;
  color: string;
  created_at: number;
}

interface SpanLabelType {
  id: number;
  name: string;
  display_name: string;
  color: string;
  hotkey: string | null;
  is_active: boolean;
  sort_order: number;
  created_at: number;
}

interface SpanAnnotationListProps {
  spanAnnotations: SpanAnnotation[];
  spanLabelTypes: SpanLabelType[];
  selectedSpanId: number | null;
  onSelectSpan: (spanId: number) => void;
  onDeleteSpan: (spanId: number) => void;
}

export default function SpanAnnotationList({
  spanAnnotations,
  spanLabelTypes,
  selectedSpanId,
  onSelectSpan,
  onDeleteSpan,
}: SpanAnnotationListProps) {
  const [expanded, setExpanded] = useState(true);

  const formatTime = (timestamp: number) => {
    return new Date(timestamp * 1000).toLocaleString('en-US', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const getLabelInfo = (labelName: string) => {
    const labelType = spanLabelTypes.find((t) => t.name === labelName);
    return {
      displayName: labelType?.display_name || labelName.replace(/_/g, ' ').toUpperCase(),
      color: labelType?.color || '#2196F3',
    };
  };

  const sortedSpans = [...spanAnnotations].sort((a, b) => b.start_time - a.start_time);

  return (
    <div>
      <button
        onClick={() => setExpanded(!expanded)}
        className="w-full flex items-center justify-between py-1"
      >
        <span className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">
          Annotations ({spanAnnotations.length})
        </span>
        <ChevronDown className={`w-3 h-3 text-muted-foreground transition-transform ${expanded ? 'rotate-180' : ''}`} />
      </button>

      {expanded && (
        <div className="space-y-1 mt-1">
          {spanAnnotations.length === 0 ? (
            <p className="text-[10px] text-muted-foreground text-center py-3">
              No annotations yet.
            </p>
          ) : (
            sortedSpans.map((span) => {
              const { displayName, color } = getLabelInfo(span.label);
              const isSelected = span.id === selectedSpanId;

              return (
                <div
                  key={span.id}
                  onClick={() => onSelectSpan(span.id)}
                  className={`flex items-start gap-1.5 p-1.5 rounded cursor-pointer transition-colors ${
                    isSelected
                      ? 'bg-primary/10 border border-primary'
                      : 'hover:bg-secondary/50 border border-transparent'
                  }`}
                >
                  <div className="flex-1 min-w-0">
                    <div className="text-[10px] text-muted-foreground font-mono">
                      {formatTime(span.start_time)} → {formatTime(span.end_time)}
                    </div>
                    <span
                      className="px-1.5 py-0.5 rounded text-[10px] font-medium text-white mt-0.5 inline-block"
                      style={{ backgroundColor: color }}
                    >
                      {displayName}
                    </span>
                    {(span.confidence || span.outcome) && (
                      <div className="mt-0.5 text-[10px] text-muted-foreground flex gap-2">
                        {span.confidence && <span>C:{span.confidence}</span>}
                        {span.outcome && <span>{span.outcome}</span>}
                      </div>
                    )}
                  </div>
                  <button
                    className="p-0.5 text-muted-foreground hover:text-destructive flex-shrink-0"
                    onClick={(e) => {
                      e.stopPropagation();
                      onDeleteSpan(span.id);
                    }}
                  >
                    <Trash2 className="w-3 h-3" />
                  </button>
                </div>
              );
            })
          )}
        </div>
      )}
    </div>
  );
}
