'use client';

import { useState } from 'react';
import { Trash2, ChevronDown, ChevronUp } from 'lucide-react';
import { Button } from '@/components/ui/button';

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: number;
  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);

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

  // Get display name and color for label
  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',
    };
  };

  // Calculate count per label type
  const labelCounts = spanAnnotations.reduce((acc, span) => {
    acc[span.label] = (acc[span.label] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

  // Sort by start_time descending (most recent first)
  const sortedSpans = [...spanAnnotations].sort((a, b) => b.start_time - a.start_time);

  return (
    <div className="flex flex-col">
      {/* Header with collapse toggle */}
      <button
        onClick={() => setExpanded(!expanded)}
        className="w-full flex items-center justify-between px-2 py-2 hover:bg-secondary/50 rounded"
      >
        <span className="text-sm font-semibold text-foreground">
          Span Annotations ({spanAnnotations.length})
        </span>
        {expanded ? (
          <ChevronUp className="w-4 h-4" />
        ) : (
          <ChevronDown className="w-4 h-4" />
        )}
      </button>

      {expanded && (
        <>
          {/* Count summary */}
          {spanAnnotations.length > 0 && (
            <div className="text-xs text-muted-foreground px-2 mb-2">
              {Object.entries(labelCounts).map(([labelName, count], idx) => {
                const { displayName } = getLabelInfo(labelName);
                return (
                  <span key={labelName}>
                    {idx > 0 && ' | '}
                    {displayName}: {count}
                  </span>
                );
              })}
            </div>
          )}

          {/* Empty state */}
          {spanAnnotations.length === 0 ? (
            <div className="text-xs text-muted-foreground px-2 py-4 text-center">
              No span annotations yet. Use the Span tool to select candle ranges.
            </div>
          ) : (
            /* Span list */
            <div className="flex flex-col gap-1 max-h-64 overflow-y-auto">
              {sortedSpans.map((span) => {
                const { displayName, color } = getLabelInfo(span.label);
                const isSelected = span.id === selectedSpanId;

                return (
                  <div
                    key={span.id}
                    className={`
                      flex items-start gap-2 p-2 rounded cursor-pointer
                      transition-colors
                      ${
                        isSelected
                          ? 'bg-primary/10 border border-primary'
                          : 'hover:bg-secondary/50 border border-transparent'
                      }
                    `}
                    onClick={() => onSelectSpan(span.id)}
                  >
                    <div className="flex-1 min-w-0">
                      {/* Time range */}
                      <div className="text-xs text-muted-foreground">
                        {formatTime(span.start_time)} → {formatTime(span.end_time)}
                      </div>

                      {/* Label badge */}
                      <div className="mt-1">
                        <span
                          className="px-2 py-0.5 rounded text-xs font-medium text-white"
                          style={{ backgroundColor: color }}
                        >
                          {displayName}
                        </span>
                      </div>

                      {/* Additional info */}
                      {(span.confidence || span.outcome) && (
                        <div className="mt-1 text-xs text-muted-foreground flex gap-2">
                          {span.confidence && <span>Confidence: {span.confidence}</span>}
                          {span.outcome && <span>Outcome: {span.outcome}</span>}
                        </div>
                      )}

                      {/* Notes preview */}
                      {span.notes && (
                        <div className="mt-1 text-xs text-muted-foreground truncate">
                          {span.notes}
                        </div>
                      )}
                    </div>

                    {/* Delete button */}
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-6 w-6 p-0 hover:bg-destructive/20 hover:text-destructive"
                      onClick={(e) => {
                        e.stopPropagation();
                        onDeleteSpan(span.id);
                      }}
                    >
                      <Trash2 className="w-3 h-3" />
                    </Button>
                  </div>
                );
              })}
            </div>
          )}
        </>
      )}
    </div>
  );
}
