import { useState, useEffect, useRef } from 'react';
import type { PausePointData } from '../../types/api';

interface PausePointEditorProps {
  pausePoint: PausePointData;
  position: { x: number; y: number };
  onSave: (adjustedMs: number) => void;
  onCancel: () => void;
  onRegenerateTTS: () => void;
  isRegenerationQueued: boolean;
}

export function PausePointEditor({
  pausePoint,
  position,
  onSave,
  onCancel,
  onRegenerateTTS,
  isRegenerationQueued,
}: PausePointEditorProps) {
  const effectiveMs = pausePoint.adjusted_ms ?? pausePoint.original_ms;
  const [value, setValue] = useState(effectiveMs);
  const [inputValue, setInputValue] = useState((effectiveMs / 1000).toFixed(3));
  const [error, setError] = useState<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // Only reset input when a DIFFERENT pause point is selected (by cue_index),
  // not when the object reference changes due to parent re-renders
  useEffect(() => {
    const ms = pausePoint.adjusted_ms ?? pausePoint.original_ms;
    setValue(ms);
    setInputValue((ms / 1000).toFixed(3));
    setError(null);
  }, [pausePoint.cue_index]);

  useEffect(() => {
    // Focus input on mount
    inputRef.current?.focus();
    inputRef.current?.select();
  }, []);

  const validateValue = (ms: number): string | null => {
    if (ms < pausePoint.min_bound_ms) {
      return `Cannot be earlier than ${formatMs(pausePoint.min_bound_ms)}`;
    }
    if (ms > pausePoint.max_bound_ms) {
      return `Cannot be later than ${formatMs(pausePoint.max_bound_ms)}`;
    }
    return null;
  };

  const handleSave = () => {
    const parsed = parseFloat(inputValue);
    if (isNaN(parsed)) {
      setError('Invalid number');
      return;
    }
    const ms = Math.round(parsed * 1000);
    const validationError = validateValue(ms);
    if (validationError) {
      setError(validationError);
      return;
    }
    onSave(ms);
  };

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

  const handleBlur = () => {
    const parsed = parseFloat(inputValue);
    if (isNaN(parsed)) {
      // Revert to previous valid value
      setInputValue((value / 1000).toFixed(3));
      return;
    }
    const ms = Math.round(parsed * 1000);
    setValue(ms);
    setError(validateValue(ms));
  };

  const formatMs = (ms: number) => {
    const totalSeconds = Math.floor(ms / 1000);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;
    const milliseconds = Math.floor(ms % 1000);
    return `${minutes}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(3, '0')}`;
  };

  return (
    <div
      className="fixed z-50 bg-white border border-gray-200 rounded-lg shadow-lg p-4 min-w-64"
      style={{ left: position.x, top: position.y }}
    >
      <div className="flex justify-between items-center mb-3">
        <h4 className="text-sm font-semibold text-gray-900">
          Pause Point {pausePoint.cue_index}
        </h4>
        <button
          onClick={onCancel}
          className="text-gray-400 hover:text-gray-600"
        >
          <svg className="w-4 h-4" 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="space-y-3">
        {/* Current value input */}
        <div>
          <label className="block text-xs text-gray-500 mb-1">
            Pause time (seconds)
          </label>
          <div className="flex items-center gap-2">
            <input
              ref={inputRef}
              type="text"
              inputMode="decimal"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onBlur={handleBlur}
              onKeyDown={handleKeyDown}
              className={`flex-1 px-2 py-1 text-sm border rounded ${
                error ? 'border-red-500' : 'border-gray-300'
              } focus:outline-none focus:ring-2 focus:ring-blue-500`}
            />
            <span className="text-xs text-gray-500">{formatMs(value)}</span>
          </div>
          {error && (
            <p className="text-xs text-red-500 mt-1">{error}</p>
          )}
        </div>

        {/* Bounds info */}
        <div className="text-xs text-gray-500 bg-gray-50 rounded p-2">
          <div>Min: {formatMs(pausePoint.min_bound_ms)}</div>
          <div>Max: {formatMs(pausePoint.max_bound_ms)}</div>
          <div>Original: {formatMs(pausePoint.original_ms)}</div>
        </div>

        {/* TTS Regeneration */}
        <div className="border-t pt-3">
          <button
            onClick={onRegenerateTTS}
            disabled={isRegenerationQueued}
            className={`w-full text-sm py-1.5 rounded ${
              isRegenerationQueued
                ? 'bg-amber-100 text-amber-700 cursor-not-allowed'
                : 'bg-orange-100 text-orange-700 hover:bg-orange-200'
            }`}
          >
            {isRegenerationQueued ? 'Regeneration Queued' : 'Queue TTS Regeneration'}
          </button>
        </div>

        {/* Action buttons */}
        <div className="flex gap-2">
          <button
            onClick={onCancel}
            className="flex-1 px-3 py-1.5 text-sm border border-gray-300 rounded hover:bg-gray-50"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={!!error}
            className={`flex-1 px-3 py-1.5 text-sm text-white rounded ${
              error
                ? 'bg-gray-300 cursor-not-allowed'
                : 'bg-blue-600 hover:bg-blue-700'
            }`}
          >
            Save
          </button>
        </div>
      </div>
    </div>
  );
}
