import React, { useState } from 'react';
import { Edit2, Save, X } from 'lucide-react';
import { processApi } from '../api/client';

export default function SubtitleEditor({ segments, jobId, onUpdate, compact = false }) {
  const [editingIndex, setEditingIndex] = useState(null);
  const [editText, setEditText] = useState('');
  const [isSaving, setIsSaving] = useState(false);

  const formatTime = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    const ms = Math.floor((seconds % 1) * 100);
    return `${mins}:${String(secs).padStart(2, '0')}.${String(ms).padStart(2, '0')}`;
  };

  const handleEdit = (index) => {
    setEditingIndex(index);
    setEditText(segments[index].translated || segments[index].text);
  };

  const handleSave = async () => {
    if (editingIndex === null) return;

    const updatedSegments = [...segments];
    updatedSegments[editingIndex] = {
      ...updatedSegments[editingIndex],
      translated: editText,
    };

    setIsSaving(true);
    try {
      await processApi.updateTranscript(jobId, updatedSegments);
      onUpdate(updatedSegments);
      setEditingIndex(null);
    } catch (err) {
      console.error('Failed to save:', err);
      alert('저장 실패');
    } finally {
      setIsSaving(false);
    }
  };

  const handleCancel = () => {
    setEditingIndex(null);
    setEditText('');
  };

  // Show all segments (scrollable)
  const displayedSegments = segments;

  return (
    <div>
      {!compact && (
        <>
          <h3 className="font-medium mb-4">자막 편집</h3>
          <p className="text-sm text-gray-500 mb-4">
            번역된 자막을 수정할 수 있습니다. 클릭하여 편집하세요.
          </p>
        </>
      )}

      <div className={`space-y-2 overflow-y-auto ${compact ? 'max-h-64' : 'max-h-[500px]'}`}>
        {displayedSegments.map((segment, index) => (
          <div
            key={index}
            className={`p-3 rounded-lg border transition-colors ${
              editingIndex === index
                ? 'border-red-500 bg-gray-800'
                : 'border-gray-800 hover:border-gray-700'
            }`}
          >
            <div className="flex items-start gap-3">
              <span className="text-xs text-gray-500 font-mono whitespace-nowrap pt-1">
                {formatTime(segment.start)}
              </span>

              {editingIndex === index ? (
                <div className="flex-1 space-y-2">
                  <textarea
                    value={editText}
                    onChange={(e) => setEditText(e.target.value)}
                    className="w-full bg-gray-900 border border-gray-700 rounded px-3 py-2 text-sm focus:outline-none focus:border-red-500"
                    rows={2}
                    autoFocus
                  />
                  <div className="flex gap-2">
                    <button
                      onClick={handleSave}
                      disabled={isSaving}
                      className="btn-primary py-1 px-3 text-sm flex items-center gap-1"
                    >
                      <Save size={14} />
                      {isSaving ? '저장 중...' : '저장'}
                    </button>
                    <button
                      onClick={handleCancel}
                      className="btn-secondary py-1 px-3 text-sm flex items-center gap-1"
                    >
                      <X size={14} />
                      취소
                    </button>
                  </div>
                </div>
              ) : (
                <div
                  className="flex-1 cursor-pointer group"
                  onClick={() => handleEdit(index)}
                >
                  <div className="text-sm">
                    {segment.translated || segment.text}
                  </div>
                  {segment.translated && segment.text !== segment.translated && (
                    <div className="text-xs text-gray-500 mt-1">
                      원문: {segment.text}
                    </div>
                  )}
                  <Edit2
                    size={14}
                    className="text-gray-600 group-hover:text-gray-400 mt-1"
                  />
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
