import React, { useEffect, useRef } from 'react';
import { AlignedSegment } from '../services/transcriptionApi';
import { formatTime } from '../utils/subtitleUtils';

interface SegmentEditorProps {
  segment: AlignedSegment;
  segmentIndex: number;
  onUpdateText: (index: number, text: string) => void;
  onDeleteSegment: (index: number) => void;
  onClose: () => void;
}

export default function SegmentEditor({
  segment,
  segmentIndex,
  onUpdateText,
  onDeleteSegment,
  onClose,
}: SegmentEditorProps) {
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    // Focus the textarea when component mounts
    if (textareaRef.current) {
      textareaRef.current.focus();
      textareaRef.current.select();
    }
  }, []);

  const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const newText = e.target.value;
    onUpdateText(segmentIndex, newText);
  };

  const handleDelete = () => {
    onDeleteSegment(segmentIndex);
    onClose();
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Escape') {
      e.preventDefault();
      onClose();
    }
  };

  return (
    <div className="bg-gray-800 border-b border-gray-700 p-4">
      <div className="flex items-start justify-between mb-3">
        <div className="flex-1">
          <h3 className="text-sm font-semibold text-white mb-1">
            Edit Segment #{segmentIndex + 1}
          </h3>
          <div className="text-xs text-gray-400">
            {formatTime(segment.start)} - {formatTime(segment.end)} ({segment.duration.toFixed(1)}s)
          </div>
        </div>
        <button
          onClick={onClose}
          className="text-gray-400 hover:text-white transition-colors ml-4"
          title="Close editor"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <div className="mb-3">
        <textarea
          ref={textareaRef}
          value={segment.text}
          onChange={handleTextChange}
          onKeyDown={handleKeyDown}
          className="w-full p-2 bg-gray-700 text-white border border-gray-600 rounded resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          rows={1}
          placeholder="Enter segment text..."
        />
      </div>

      <div className="flex justify-end">
        <button
          onClick={handleDelete}
          className="px-3 py-1 bg-red-600 hover:bg-red-700 text-white text-sm rounded transition-colors"
          title="Delete this segment"
        >
          Delete
        </button>
      </div>
    </div>
  );
}
