import { useState, useEffect } from 'react';
import { VTTParser, VTTValidator, type VTTCue } from '../../lib/vtt';

interface VttEditorProps {
  vttContent: string;
  onChange: (content: string) => void;
  title: string;
  readOnly?: boolean;
}

export function VttEditor({ vttContent, onChange, title, readOnly = false }: VttEditorProps) {
  const [cues, setCues] = useState<VTTCue[]>([]);
  const [errors, setErrors] = useState<string[]>([]);
  const [editingCue, setEditingCue] = useState<number | null>(null);

  useEffect(() => {
    try {
      const parsedCues = VTTParser.parse(vttContent);
      setCues(parsedCues);
      
      // Validate content
      const validation = VTTValidator.validate(vttContent);
      setErrors(validation.errors);
    } catch (error) {
      setErrors([`Failed to parse VTT: ${error instanceof Error ? error.message : 'Unknown error'}`]);
    }
  }, [vttContent]);

  const updateCueText = (index: number, newText: string) => {
    const updatedCues = [...cues];
    updatedCues[index] = { ...updatedCues[index], text: newText };
    setCues(updatedCues);
    
    // Rebuild VTT and notify parent
    const newVttContent = VTTParser.build(updatedCues);
    onChange(newVttContent);
    
    setEditingCue(null);
  };

  const formatTime = (seconds: number): string => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    
    const wholeSeconds = Math.floor(secs);
    const milliseconds = Math.round((secs - wholeSeconds) * 1000);
    
    if (hours > 0) {
      return `${hours}:${minutes.toString().padStart(2, '0')}:${wholeSeconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(3, '0')}`;
    }
    return `${minutes}:${wholeSeconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(3, '0')}`;
  };

  return (
    <div className="border border-gray-300 rounded-lg">
      {/* Header */}
      <div className="bg-gray-50 px-4 py-3 border-b border-gray-300">
        <h3 className="text-lg font-medium text-gray-900">{title}</h3>
        {errors.length > 0 && (
          <div className="mt-2">
            <div className="text-sm text-red-600">
              <p className="font-medium">Validation Errors:</p>
              <ul className="list-disc list-inside mt-1">
                {errors.map((error, i) => (
                  <li key={i}>{error}</li>
                ))}
              </ul>
            </div>
          </div>
        )}
      </div>

      {/* Cue List */}
      <div className="max-h-96 overflow-y-auto">
        {cues.length === 0 ? (
          <div className="p-4 text-center text-gray-500">
            No cues found in VTT content
          </div>
        ) : (
          <div className="divide-y divide-gray-200">
            {cues.map((cue, index) => (
              <div key={index} className="p-4 hover:bg-gray-50">
                {/* Timing */}
                <div className="text-sm text-gray-500 mb-2 font-mono">
                  {formatTime(cue.startTime)} → {formatTime(cue.endTime)}
                  <span className="ml-2 text-xs">
                    ({((cue.endTime - cue.startTime) * 1000).toFixed(0)}ms)
                  </span>
                </div>
                
                {/* Text Content */}
                {editingCue === index ? (
                  <CueEditor
                    initialText={cue.text}
                    onSave={(newText) => updateCueText(index, newText)}
                    onCancel={() => setEditingCue(null)}
                  />
                ) : (
                  <div className="group">
                    <div className="text-gray-900 whitespace-pre-wrap leading-relaxed">
                      {cue.text}
                    </div>
                    {!readOnly && (
                      <button
                        onClick={() => setEditingCue(index)}
                        className="mt-2 opacity-0 group-hover:opacity-100 text-sm text-blue-600 hover:text-blue-800 transition-opacity"
                      >
                        Edit text
                      </button>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Footer Stats */}
      <div className="bg-gray-50 px-4 py-2 border-t border-gray-300 text-sm text-gray-600">
        {cues.length} cues • Total duration: {formatTime(Math.max(...cues.map(c => c.endTime), 0))}
      </div>
    </div>
  );
}

interface CueEditorProps {
  initialText: string;
  onSave: (text: string) => void;
  onCancel: () => void;
}

function CueEditor({ initialText, onSave, onCancel }: CueEditorProps) {
  const [text, setText] = useState(initialText);

  const handleSave = () => {
    onSave(text);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Escape') {
      onCancel();
    } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
      handleSave();
    }
  };

  return (
    <div className="space-y-2">
      <textarea
        value={text}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={handleKeyDown}
        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
        rows={3}
        autoFocus
      />
      <div className="flex gap-2">
        <button
          onClick={handleSave}
          className="px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700"
        >
          Save (Ctrl+Enter)
        </button>
        <button
          onClick={onCancel}
          className="px-3 py-1 bg-gray-300 text-gray-700 text-sm rounded hover:bg-gray-400"
        >
          Cancel (Esc)
        </button>
      </div>
    </div>
  );
}