'use client';

import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Slider } from '@/components/ui/slider';
import type { SpanLabelType } from '@/types';

// SpanLabelType is imported from @/types above.

interface SpanData {
  start_time: number;
  end_time: number;
  label?: string;
  confidence?: number | null;
  outcome?: string | null;
  notes?: string | null;
}

interface SpanPopoverProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  spanLabelTypes: SpanLabelType[];
  initialData?: SpanData;
  onSave: (data: {
    label: string;
    confidence: number | null;
    outcome: string | null;
    notes: string | null;
  }) => void;
  onCancel: () => void;
}

export default function SpanPopover({
  open,
  onOpenChange,
  spanLabelTypes,
  initialData,
  onSave,
  onCancel,
}: SpanPopoverProps) {
  const [label, setLabel] = useState<string>(initialData?.label || '');
  const [confidence, setConfidence] = useState<number>(initialData?.confidence || 3);
  const [outcome, setOutcome] = useState<string>(initialData?.outcome || 'none');
  const [notes, setNotes] = useState<string>(initialData?.notes || '');

  // Reset form when dialog opens with new initial data
  useEffect(() => {
    if (open && initialData) {
      setLabel(initialData.label || '');
      setConfidence(initialData.confidence || 3);
      setOutcome(initialData.outcome || 'none');
      setNotes(initialData.notes || '');
    }
  }, [open, initialData]);

  const handleSave = () => {
    if (!label) return; // Validation: label is required

    onSave({
      label,
      confidence: confidence,
      outcome: outcome === 'none' ? null : outcome,
      notes: notes.trim() || null,
    });

    // Reset form
    setLabel('');
    setConfidence(3);
    setOutcome('none');
    setNotes('');
  };

  const handleCancel = () => {
    // Reset form
    setLabel('');
    setConfidence(3);
    setOutcome('none');
    setNotes('');
    onCancel();
  };

  const handleEscape = (e: KeyboardEvent) => {
    if (e.key === 'Escape' && open) {
      handleCancel();
    }
  };

  useEffect(() => {
    window.addEventListener('keydown', handleEscape);
    return () => window.removeEventListener('keydown', handleEscape);
  }, [open]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Span Annotation</DialogTitle>
          <DialogDescription>
            Assign a pattern label and optional metadata to this span.
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-4 py-4">
          {/* Label Selection */}
          <div className="grid gap-2">
            <Label htmlFor="label">Pattern Label *</Label>
            <Select value={label} onValueChange={setLabel}>
              <SelectTrigger id="label">
                <SelectValue placeholder="Select a pattern label" />
              </SelectTrigger>
              <SelectContent>
                {spanLabelTypes
                  .filter((type) => type.is_active)
                  .sort((a, b) => a.sort_order - b.sort_order)
                  .map((type) => (
                    <SelectItem key={type.id} value={type.name}>
                      <div className="flex items-center gap-2">
                        <div
                          className="w-3 h-3 rounded"
                          style={{ backgroundColor: type.color }}
                        />
                        {type.display_name}
                        {type.hotkey && (
                          <span className="text-xs text-muted-foreground ml-auto">
                            ({type.hotkey})
                          </span>
                        )}
                      </div>
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
          </div>

          {/* Confidence Slider */}
          <div className="grid gap-2">
            <Label htmlFor="confidence">
              Confidence: {confidence}
            </Label>
            <Slider
              id="confidence"
              min={1}
              max={5}
              step={1}
              value={[confidence]}
              onValueChange={(values) => setConfidence(values[0])}
              className="w-full"
            />
            <div className="flex justify-between text-xs text-muted-foreground">
              <span>1 (Low)</span>
              <span>5 (High)</span>
            </div>
          </div>

          {/* Outcome Selection */}
          <div className="grid gap-2">
            <Label htmlFor="outcome">Outcome</Label>
            <Select value={outcome} onValueChange={setOutcome}>
              <SelectTrigger id="outcome">
                <SelectValue placeholder="Select outcome" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">None</SelectItem>
                <SelectItem value="win">Win</SelectItem>
                <SelectItem value="loss">Loss</SelectItem>
                <SelectItem value="breakeven">Break Even</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Notes Textarea */}
          <div className="grid gap-2">
            <Label htmlFor="notes">Notes</Label>
            <Textarea
              id="notes"
              placeholder="Add any notes about this pattern..."
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              rows={3}
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleCancel}>
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={!label}>
            Save
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
