'use client';
import React, { useEffect, useRef, useState } from 'react';
import { Bold, Italic, List, ListOrdered, AlignLeft, AlignCenter, AlignRight, Link as LinkIcon, Heading1, Heading2, Quote, Check, X } from 'lucide-react';

interface RichTextEditorProps {
  label: string;
  value: string;
  onChange: (value: string) => void;
}

const ToolbarButton = ({ icon: Icon, onClick, active = false, title }: any) => (
  <button
    type="button"
    onMouseDown={(e) => e.preventDefault()} // Prevent focus loss from editor
    onClick={onClick}
    className={`p-2 rounded transition ${
      active 
        ? 'bg-slate-200 text-slate-900' 
        : 'text-slate-500 hover:text-primary hover:bg-slate-100'
    }`}
    title={title}
  >
    <Icon size={18} />
  </button>
);

const RichTextEditor: React.FC<RichTextEditorProps> = ({ label, value, onChange }) => {
  const editorRef = useRef<HTMLDivElement>(null);
  const [isFocused, setIsFocused] = useState(false);
  const [showLinkInput, setShowLinkInput] = useState(false);
  const [linkUrl, setLinkUrl] = useState('');
  
  // Track if we are currently editing to avoid loop updates
  const isTyping = useRef(false);

  // Initialize content or update if value changes externally (not from typing)
  useEffect(() => {
    if (editorRef.current && value !== editorRef.current.innerHTML && !isTyping.current) {
       editorRef.current.innerHTML = value;
    }
  }, [value]);

  const handleInput = () => {
    if (editorRef.current) {
      isTyping.current = true;
      onChange(editorRef.current.innerHTML);
      // Reset typing flag after a short delay to allow external updates again if needed
      setTimeout(() => { isTyping.current = false; }, 100);
    }
  };

  const execCommand = (command: string, arg: string | undefined = undefined) => {
    document.execCommand(command, false, arg);
    if (editorRef.current) {
      editorRef.current.focus();
      handleInput();
    }
  };

  const saveLink = () => {
    if (linkUrl) {
      execCommand('createLink', linkUrl);
      setLinkUrl('');
      setShowLinkInput(false);
    }
  };

  return (
    <div className="w-full relative">
      <label className="block text-sm font-medium text-slate-700 mb-2">{label}</label>
      <div className={`border rounded-lg overflow-hidden bg-white transition-all ${isFocused ? 'ring-2 ring-primary border-transparent' : 'border-slate-300'}`}>
        {/* Toolbar */}
        <div className="flex flex-wrap items-center gap-1 p-2 border-b border-slate-200 bg-slate-50 relative">
          <ToolbarButton icon={Bold} onClick={() => execCommand('bold')} title="Bold" />
          <ToolbarButton icon={Italic} onClick={() => execCommand('italic')} title="Italic" />
          <ToolbarButton icon={Heading1} onClick={() => execCommand('formatBlock', 'H2')} title="Heading" />
          <ToolbarButton icon={Heading2} onClick={() => execCommand('formatBlock', 'H3')} title="Subheading" />
          <div className="w-px h-6 bg-slate-300 mx-1"></div>
          <ToolbarButton icon={List} onClick={() => execCommand('insertUnorderedList')} title="Bullet List" />
          <ToolbarButton icon={ListOrdered} onClick={() => execCommand('insertOrderedList')} title="Numbered List" />
          <div className="w-px h-6 bg-slate-300 mx-1"></div>
          <ToolbarButton icon={AlignLeft} onClick={() => execCommand('justifyLeft')} title="Align Left" />
          <ToolbarButton icon={AlignCenter} onClick={() => execCommand('justifyCenter')} title="Align Center" />
          <ToolbarButton icon={AlignRight} onClick={() => execCommand('justifyRight')} title="Align Right" />
          <div className="w-px h-6 bg-slate-300 mx-1"></div>
          <ToolbarButton icon={Quote} onClick={() => execCommand('formatBlock', 'BLOCKQUOTE')} title="Quote" />
          
          <ToolbarButton 
            icon={LinkIcon} 
            active={showLinkInput}
            onClick={() => {
              if (showLinkInput) {
                setShowLinkInput(false);
              } else {
                // Check if text is selected
                const selection = window.getSelection();
                if (selection && selection.toString().length > 0) {
                   setShowLinkInput(true);
                   setLinkUrl('https://');
                } else {
                   alert("Please select some text first to add a link.");
                }
              }
            }} 
            title="Link" 
          />

          {/* Link Input Popover */}
          {showLinkInput && (
            <div className="absolute top-full left-0 mt-2 p-2 bg-white shadow-xl rounded-lg border border-slate-200 z-10 flex items-center gap-2 w-full max-w-sm">
              <input 
                type="text" 
                value={linkUrl}
                onChange={(e) => setLinkUrl(e.target.value)}
                className="flex-1 px-3 py-1 text-sm border border-slate-300 rounded focus:ring-2 focus:ring-primary outline-none"
                placeholder="https://example.com"
                autoFocus
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    e.preventDefault();
                    saveLink();
                  }
                }}
              />
              <button 
                type="button"
                onClick={saveLink}
                className="p-1 bg-green-100 text-green-700 rounded hover:bg-green-200"
              >
                <Check size={16} />
              </button>
              <button 
                type="button"
                onClick={() => setShowLinkInput(false)}
                className="p-1 bg-red-100 text-red-700 rounded hover:bg-red-200"
              >
                <X size={16} />
              </button>
            </div>
          )}
        </div>
        
        {/* Editor Area */}
        <div
          ref={editorRef}
          className="p-4 min-h-[300px] outline-none prose max-w-none"
          contentEditable
          onInput={handleInput}
          onFocus={() => setIsFocused(true)}
          onBlur={() => setIsFocused(false)}
        />
      </div>
      <p className="text-xs text-slate-400 mt-1">Select text to apply formatting.</p>
    </div>
  );
};

export default RichTextEditor;