import React, { useState, useEffect } from 'react';
import MarkdownEditor from './MarkdownEditor';

interface EditModalProps {
  isOpen: boolean;
  title: string;
  initialValue: string;
  multiline?: boolean;
  markdown?: boolean; // New prop for markdown editor
  onClose: () => void;
  onSave: (value: string) => void;
}

const EditModal: React.FC<EditModalProps> = ({ isOpen, title, initialValue, multiline = false, markdown = false, onClose, onSave }) => {
  const [value, setValue] = useState(initialValue);

  useEffect(() => {
    setValue(initialValue);
  }, [initialValue]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-in fade-in duration-200">
      <div className="bg-surface border border-border rounded-xl w-full max-w-2xl shadow-2xl flex flex-col max-h-[90vh]">
        <div className="p-4 border-b border-border flex justify-between items-center bg-surfaceHighlight/20">
          <h3 className="font-bold text-textMain">{title}</h3>
          <button onClick={onClose} className="text-textMuted hover:text-white transition-colors text-xl leading-none">&times;</button>
        </div>
        
        <div className="p-4 flex-1 overflow-hidden flex flex-col">
          {multiline ? (
            markdown ? (
              <MarkdownEditor
                value={value}
                onChange={setValue}
                className="flex-1"
              />
            ) : (
              <textarea
                className="w-full h-64 md:h-96 bg-[#0b0b0d] border border-border rounded-lg p-3 text-sm font-mono text-gray-300 focus:border-accentInfo focus:outline-none resize-none"
                value={value}
                onChange={(e) => setValue(e.target.value)}
              />
            )
          ) : (
             <input
              type="text"
              className="w-full bg-[#0b0b0d] border border-border rounded-lg p-3 text-sm text-gray-300 focus:border-accentInfo focus:outline-none"
              value={value}
              onChange={(e) => setValue(e.target.value)}
             />
          )}
          {multiline && !markdown && <p className="text-xs text-textMuted mt-2">Unterstützt Markdown Formatierung.</p>}
        </div>

        <div className="p-4 border-t border-border flex justify-end gap-3 bg-surfaceHighlight/10">
          <button 
            onClick={onClose}
            className="px-4 py-2 text-sm font-medium text-textMuted hover:text-white transition-colors"
          >
            Abbrechen
          </button>
          <button 
            onClick={() => { onSave(value); onClose(); }}
            className="px-4 py-2 text-sm font-medium bg-accentInfo hover:bg-accentInfo/90 text-white rounded transition-colors shadow-lg shadow-accentInfo/20"
          >
            Speichern
          </button>
        </div>
      </div>
    </div>
  );
};

export default EditModal;
