import React, { useState, KeyboardEvent, useEffect } from 'react';
import { FaTimes, FaCheck } from 'react-icons/fa';
import { API, PlaylistItem, getDisplayTitle } from '../api/player';

interface RenameFavoriteModalProps {
  isOpen: boolean;
  onClose: () => void;
  favorite: PlaylistItem | null;
}

const RenameFavoriteModal: React.FC<RenameFavoriteModalProps> = ({ isOpen, onClose, favorite }) => {
  const [title, setTitle] = useState('');
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    if (favorite) {
      setTitle(getDisplayTitle(favorite));
    }
  }, [favorite]);

  const handleSave = async () => {
    if (!favorite || !title.trim()) return;
    
    setIsSaving(true);

    try {
      await API.updateFavoriteTitle(favorite.filename, title);
      onClose();
    } catch (error) {
      console.error('Failed to rename favorite:', error);
    } finally {
      setIsSaving(false);
    }
  };

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

  if (!isOpen || !favorite) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-violet-900 w-full max-w-md rounded-lg p-4 shadow-lg">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-white text-xl font-bold">Rename Favorite</h2>

          <button onClick={onClose} className="text-white/60 hover:text-white">
            <FaTimes size={24} />
          </button>
        </div>

        <div className="mb-4">
          <label className="text-white/80 block mb-2">Original filename:</label>
          <div className="text-white/60 text-sm truncate bg-black/20 p-2 rounded-lg mb-4">
            {favorite.filename}
          </div>
          
          <label className="text-white/80 block mb-2">Title:</label>
          <input
            type="text"
            autoFocus
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Enter new title..."
            className="p-2 rounded-lg border-2 border-violet-500 w-full bg-black/20 text-white"
          />
        </div>

        <div className="flex justify-end gap-2">
          <button
            onClick={onClose}
            className="bg-black/30 text-white p-2 rounded-lg px-4 hover:bg-black/40"
          >
            Cancel
          </button>
          
          <button
            onClick={handleSave}
            disabled={isSaving || !title.trim()}
            className="bg-violet-500 text-white p-2 rounded-lg px-4 disabled:opacity-50 flex items-center gap-2"
          >
            <FaCheck size={16} />
            Save
          </button>
        </div>
      </div>
    </div>
  );
};

export default RenameFavoriteModal;
