'use client';

import { useState, useEffect } from 'react';
import { ArrowUpCircle, ArrowDownCircle, TrendingUp, Trash2, ChevronDown, ChevronUp, RectangleHorizontal, Layers, Minus } from 'lucide-react';
import { Input } from '@/components/ui/input';
import type { AnnotationType, Annotation, SpanAnnotation, SpanLabelType } from '@/types';

// AnnotationType, Annotation, SpanAnnotation, SpanLabelType are imported from @/types above.

export type Tool = string | 'delete' | null;

interface ToolboxProps {
  activeTool: Tool;
  onToolChange: (tool: Tool) => void;
  onExport: () => void;
  selectedColor: string;
  onColorChange: (color: string) => void;
  annotations?: Annotation[];
  selectedLabelId?: number | null;
  onLabelSelect?: (id: number) => void;
  onLabelDelete?: (id: number) => void;
  activeChartId?: number | null;
  spanAnnotations?: SpanAnnotation[];
  spanLabelTypes?: SpanLabelType[];
  selectedSpanId?: number | null;
  onSelectSpan?: (spanId: number) => void;
  onDeleteSpan?: (spanId: number) => void;
}

export default function Toolbox({
  activeTool,
  onToolChange,
  onExport,
  selectedColor,
  onColorChange,
  annotations = [],
  selectedLabelId = null,
  onLabelSelect,
  onLabelDelete,
  activeChartId,
  spanAnnotations = [],
  spanLabelTypes = [],
  selectedSpanId = null,
  onSelectSpan,
  onDeleteSpan,
}: ToolboxProps) {
  const [labelsExpanded, setLabelsExpanded] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [filterType, setFilterType] = useState<string>('all');
  const [annotationTypes, setAnnotationTypes] = useState<AnnotationType[]>([]);

  useEffect(() => {
    const fetchTypes = async () => {
      try {
        const res = await fetch('/api/annotation-types');
        if (res.ok) {
          const data = await res.json();
          setAnnotationTypes(data.filter((t: AnnotationType) => t.is_active));
        }
      } catch (error) {
        console.error('Failed to fetch annotation types:', error);
      }
    };
    fetchTypes();
  }, []);

  const handleToolClick = (tool: Tool) => {
    if (activeTool === tool) {
      onToolChange(null);
    } else {
      onToolChange(tool);
    }
  };

  const markerTypes = annotationTypes.filter((t) => t.category === 'marker');
  const markerTypeNames = markerTypes.map((t) => t.name);

  const labelAnnotations = annotations
    .filter((a) => markerTypeNames.includes(a.label_type))
    .filter((a) => (filterType === 'all' ? true : a.label_type === filterType))
    .sort((a, b) => b.timestamp - a.timestamp);

  const filteredAnnotations = labelAnnotations.filter((a) => {
    const formattedTime = new Date(a.timestamp * 1000).toLocaleString('en-US', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
    return formattedTime.toLowerCase().includes(searchText.toLowerCase());
  });

  const typeCounts = markerTypes.reduce((acc, type) => {
    acc[type.name] = labelAnnotations.filter((a) => a.label_type === type.name).length;
    return acc;
  }, {} as Record<string, number>);

  const handleLabelDelete = async (id: number, e: React.MouseEvent) => {
    e.stopPropagation();
    try {
      const response = await fetch(`/api/annotations/${id}`, {
        method: 'DELETE',
      });
      if (response.ok) {
        onLabelDelete?.(id);
      }
    } catch (error) {
      console.error('Failed to delete label:', error);
    }
  };

  const colors = [
    { color: '#ef4444', name: 'red' },
    { color: '#22c55e', name: 'green' },
    { color: '#3b82f6', name: 'blue' },
    { color: '#f59e0b', name: 'orange' },
    { color: '#8b5cf6', name: 'purple' },
  ];

  return (
    <div className="space-y-1">
      <p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-1">Tools</p>

      {/* Tool buttons grid */}
      <div className="flex gap-1">
        <button
          onClick={() => handleToolClick('rectangle')}
          className={`flex-1 flex items-center justify-center gap-1 px-1.5 py-1.5 text-xs rounded transition-colors ${
            activeTool === 'rectangle'
              ? 'bg-primary text-primary-foreground'
              : 'bg-secondary/50 hover:bg-secondary text-muted-foreground hover:text-foreground'
          }`}
        >
          <RectangleHorizontal className="w-3.5 h-3.5" /> Rect
        </button>
        <button
          onClick={() => handleToolClick('span')}
          className={`flex-1 flex items-center justify-center gap-1 px-1.5 py-1.5 text-xs rounded transition-colors ${
            activeTool === 'span'
              ? 'bg-primary text-primary-foreground'
              : 'bg-secondary/50 hover:bg-secondary text-muted-foreground hover:text-foreground'
          }`}
        >
          <Layers className="w-3.5 h-3.5" /> Span
        </button>
        <button
          onClick={() => handleToolClick('line')}
          className={`flex-1 flex items-center justify-center gap-1 px-1.5 py-1.5 text-xs rounded transition-colors ${
            activeTool === 'line'
              ? 'bg-primary text-primary-foreground'
              : 'bg-secondary/50 hover:bg-secondary text-muted-foreground hover:text-foreground'
          }`}
        >
          <Minus className="w-3.5 h-3.5" /> Line
        </button>
        <button
          onClick={() => handleToolClick('delete')}
          className={`flex-1 flex items-center justify-center gap-1 px-1.5 py-1.5 text-xs rounded transition-colors ${
            activeTool === 'delete'
              ? 'bg-destructive text-destructive-foreground'
              : 'bg-secondary/50 hover:bg-secondary text-muted-foreground hover:text-foreground'
          }`}
        >
          <Trash2 className="w-3.5 h-3.5" /> Del
        </button>
      </div>

      {/* Marker type buttons (if any) */}
      {markerTypes.length > 0 && (
        <div className="flex gap-1">
          {markerTypes.map((type) => (
            <button
              key={type.id}
              onClick={() => handleToolClick(type.name)}
              className={`flex-1 flex items-center justify-center gap-1 px-1.5 py-1.5 text-xs rounded transition-colors ${
                activeTool === type.name
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-secondary/50 hover:bg-secondary text-muted-foreground hover:text-foreground'
              }`}
            >
              {type.icon === 'arrowUp' ? <ArrowUpCircle className="w-3.5 h-3.5" /> :
               type.icon === 'arrowDown' ? <ArrowDownCircle className="w-3.5 h-3.5" /> :
               <ArrowUpCircle className="w-3.5 h-3.5" />}
              {type.display_name}
            </button>
          ))}
        </div>
      )}

      {/* Color swatches */}
      <div className="flex gap-1 pt-1">
        {colors.map((preset) => {
          const isSelected = selectedColor === preset.color;
          return (
            <button
              key={preset.color}
              onClick={() => onColorChange(preset.color)}
              className={`flex-1 h-6 rounded-sm border-2 transition-all ${
                isSelected
                  ? 'scale-105 ring-1 ring-offset-1 ring-offset-sidebar'
                  : 'opacity-60 hover:opacity-100'
              }`}
              style={{
                backgroundColor: preset.color,
                borderColor: isSelected ? preset.color : 'transparent',
                // @ts-ignore
                '--tw-ring-color': preset.color,
              }}
              title={preset.name}
            />
          );
        })}
      </div>

      {/* Labels Section - collapsible */}
      <button
        onClick={() => setLabelsExpanded(!labelsExpanded)}
        className="w-full flex items-center justify-between py-1 mt-1"
      >
        <span className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">
          Annotations ({labelAnnotations.length})
        </span>
        <ChevronDown className={`w-3 h-3 text-muted-foreground transition-transform ${labelsExpanded ? 'rotate-180' : ''}`} />
      </button>

      {labelsExpanded && (
        <div className="space-y-1 mt-1">
          {/* Count display */}
          {markerTypes.length > 0 && (
            <div className="text-[10px] text-muted-foreground">
              {markerTypes.map((type, idx) => (
                <span key={type.id}>
                  {idx > 0 && ' | '}
                  {type.display_name}: {typeCounts[type.name] || 0}
                </span>
              ))}
            </div>
          )}

          <Input
            placeholder="Search..."
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            className="h-7 text-xs"
          />

          {filterType !== 'all' || markerTypes.length > 1 ? (
            <select
              value={filterType}
              onChange={(e) => setFilterType(e.target.value)}
              className="w-full h-7 px-2 text-xs rounded border border-border bg-card"
            >
              <option value="all">All Types</option>
              {markerTypes.map((type) => (
                <option key={type.id} value={type.name}>
                  {type.display_name}
                </option>
              ))}
            </select>
          ) : null}

          <div className="max-h-40 overflow-y-auto scrollbar-thin space-y-1">
            {filteredAnnotations.length === 0 ? (
              <p className="text-[10px] text-muted-foreground text-center py-3">
                {labelAnnotations.length === 0 ? 'No annotations yet.' : 'No matching labels.'}
              </p>
            ) : (
              filteredAnnotations.map((annotation) => {
                const formattedTime = new Date(annotation.timestamp * 1000).toLocaleString('en-US', {
                  month: 'short',
                  day: 'numeric',
                  hour: '2-digit',
                  minute: '2-digit',
                });
                const isSelected = annotation.id === selectedLabelId;
                const annotationType = annotationTypes.find((t) => t.name === annotation.label_type);

                return (
                  <div
                    key={annotation.id}
                    onClick={() => onLabelSelect?.(annotation.id)}
                    className={`p-1.5 rounded text-[10px] cursor-pointer transition-colors ${
                      isSelected
                        ? 'bg-primary/10 border border-primary'
                        : 'hover:bg-secondary/50 border border-transparent'
                    }`}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex-1 min-w-0">
                        <div className="font-mono text-foreground">{formattedTime}</div>
                        <span
                          className="px-1.5 py-0.5 rounded text-[10px] font-medium mt-0.5 inline-block"
                          style={{
                            backgroundColor: annotationType ? `${annotationType.color}20` : '#e5e7eb',
                            color: annotationType?.color || '#374151',
                          }}
                        >
                          {annotationType?.display_name || annotation.label_type}
                        </span>
                      </div>
                      <button
                        className="p-0.5 text-muted-foreground hover:text-destructive"
                        onClick={(e) => handleLabelDelete(annotation.id, e)}
                      >
                        <Trash2 className="w-3 h-3" />
                      </button>
                    </div>
                  </div>
                );
              })
            )}
          </div>
        </div>
      )}
    </div>
  );
}
