import React, { useEffect, useRef, useState } from 'react';
import {
    Bold,
    Italic,
    Heading1,
    Heading2,
    Heading3,
    List,
    ListOrdered,
    Link as LinkIcon,
    Code2,
    Eye,
    FileText,
    Table as TableIcon,
    Terminal,
    Quote,
    Undo,
    Redo,
    Sparkles
} from 'lucide-react';

interface DarkCKEditorProps {
    value: string;
    onChange: (value: string) => void;
    placeholder?: string;
}

export function DarkCKEditor({ value, onChange, placeholder }: DarkCKEditorProps) {
    const [editorMode, setEditorMode] = useState<'visual' | 'preview' | 'code'>('visual');
    const [content, setContent] = useState(value || '');
    const visualEditableRef = useRef<HTMLDivElement>(null);
    const isInternalUpdate = useRef(false);

    useEffect(() => {
        if (!isInternalUpdate.current) {
            setContent(value || '');
            if (visualEditableRef.current && visualEditableRef.current.innerHTML !== (value || '')) {
                visualEditableRef.current.innerHTML = value || '';
            }
        }
        isInternalUpdate.current = false;
    }, [value]);

    const handleContentChange = (newVal: string) => {
        isInternalUpdate.current = true;
        setContent(newVal);
        onChange(newVal);
    };

    const handleVisualInput = () => {
        if (visualEditableRef.current) {
            const html = visualEditableRef.current.innerHTML;
            handleContentChange(html);
        }
    };

    const execCmd = (command: string, value: string | undefined = undefined) => {
        if (editorMode !== 'visual') {
            setEditorMode('visual');
        }
        setTimeout(() => {
            if (visualEditableRef.current) {
                visualEditableRef.current.focus();
                document.execCommand(command, false, value);
                handleVisualInput();
            }
        }, 50);
    };

    const insertCustomHTML = (htmlToInsert: string) => {
        if (editorMode === 'visual') {
            if (visualEditableRef.current) {
                visualEditableRef.current.focus();
                document.execCommand('insertHTML', false, htmlToInsert);
                handleVisualInput();
            }
        } else if (editorMode === 'code') {
            const textarea = document.getElementById('dark-editor-source-textarea') as HTMLTextAreaElement;
            if (textarea) {
                const start = textarea.selectionStart;
                const end = textarea.selectionEnd;
                const updated = content.substring(0, start) + htmlToInsert + content.substring(end);
                handleContentChange(updated);
            } else {
                handleContentChange(content + htmlToInsert);
            }
        } else {
            handleContentChange(content + htmlToInsert);
        }
    };

    const insertCodeBlockSnippet = () => {
        const snippet = `\n<pre><code class="language-typescript">// TypeScript Implementation Example
interface ServiceConfig {
    apiKey: string;
    timeoutMs: number;
    maxRetries: number;
}

export function initializeService(config: ServiceConfig) {
    console.log("Service active:", config.apiKey);
}
</code></pre>\n<p></p>`;
        insertCustomHTML(snippet);
    };

    const insertTableSnippet = () => {
        const tableHtml = `\n<table>
<thead>
<tr>
<th>Metric / Feature</th>
<th>Standard Tier</th>
<th>Enterprise Tier</th>
</tr>
</thead>
<tbody>
<tr>
<td>Response SLA</td>
<td>&lt; 24 Hours</td>
<td>&lt; 15 Minutes (24/7)</td>
</tr>
<tr>
<td>Dedicated Engineering</td>
<td>Shared Sprints</td>
<td>Dedicated Core Team</td>
</tr>
<tr>
<td>Cloud Infrastructure</td>
<td>Standard Cluster</td>
<td>Multi-Region HA & 99.99% SLA</td>
</tr>
</tbody>
</table>\n<p></p>`;
        insertCustomHTML(tableHtml);
    };

    const handlePromptLink = () => {
        const url = prompt('Enter URL link (e.g. https://techinsoul.com):', 'https://');
        if (url) {
            execCmd('createLink', url);
        }
    };

    return (
        <div className="rounded-2xl border border-slate-800 bg-[#060B18] overflow-hidden focus-within:border-[#00F2FE] transition-all">
            {/* Top Bar Mode Switch & Action Bar */}
            <div className="flex flex-wrap items-center justify-between px-4 py-2.5 bg-[#0B132B] border-b border-slate-800 text-xs gap-2">
                <div className="flex items-center gap-1 bg-[#060B18] p-1 rounded-xl border border-slate-800">
                    <button
                        type="button"
                        onClick={() => {
                            setEditorMode('visual');
                            setTimeout(() => {
                                if (visualEditableRef.current) {
                                    visualEditableRef.current.innerHTML = content;
                                }
                            }, 30);
                        }}
                        className={`px-3 py-1.5 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all ${
                            editorMode === 'visual'
                                ? 'bg-gradient-to-r from-[#00F2FE] to-[#38BDF8] text-[#060B18] shadow-sm'
                                : 'text-slate-400 hover:text-white'
                        }`}
                    >
                        <FileText className="w-3.5 h-3.5" /> Visual Editor
                    </button>
                    <button
                        type="button"
                        onClick={() => setEditorMode('preview')}
                        className={`px-3 py-1.5 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all ${
                            editorMode === 'preview'
                                ? 'bg-gradient-to-r from-[#00F2FE] to-[#38BDF8] text-[#060B18] shadow-sm'
                                : 'text-slate-400 hover:text-white'
                        }`}
                    >
                        <Eye className="w-3.5 h-3.5" /> Live Preview
                    </button>
                    <button
                        type="button"
                        onClick={() => setEditorMode('code')}
                        className={`px-3 py-1.5 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all ${
                            editorMode === 'code'
                                ? 'bg-gradient-to-r from-[#00F2FE] to-[#38BDF8] text-[#060B18] shadow-sm'
                                : 'text-slate-400 hover:text-white'
                        }`}
                    >
                        <Code2 className="w-3.5 h-3.5" /> Source HTML
                    </button>
                </div>

                {/* Quick Insert Snippet Actions */}
                <div className="flex items-center gap-2">
                    <button
                        type="button"
                        onClick={insertCodeBlockSnippet}
                        className="px-2.5 py-1.5 rounded-lg bg-[#1C2541] hover:bg-[#253256] text-[#00F2FE] border border-cyan-500/30 text-xs font-semibold flex items-center gap-1.5 transition-all"
                        title="Insert Monospaced Code Snippet Block"
                    >
                        <Terminal className="w-3.5 h-3.5" /> + Code Block
                    </button>
                    <button
                        type="button"
                        onClick={insertTableSnippet}
                        className="px-2.5 py-1.5 rounded-lg bg-[#1C2541] hover:bg-[#253256] text-[#38BDF8] border border-sky-500/30 text-xs font-semibold flex items-center gap-1.5 transition-all"
                        title="Insert Glassmorphism Comparison Table"
                    >
                        <TableIcon className="w-3.5 h-3.5" /> + Table
                    </button>
                </div>
            </div>

            {/* Visual Formatting Toolbar */}
            <div className="flex flex-wrap items-center gap-1 px-4 py-2 bg-[#080E21] border-b border-slate-800/80 text-slate-300 text-xs">
                <button
                    type="button"
                    onClick={() => execCmd('formatBlock', '<h2>')}
                    className="px-2 py-1 rounded hover:bg-[#00F2FE]/10 hover:text-[#00F2FE] text-slate-300 font-bold"
                    title="Heading 2"
                >
                    H2
                </button>
                <button
                    type="button"
                    onClick={() => execCmd('formatBlock', '<h3>')}
                    className="px-2 py-1 rounded hover:bg-[#00F2FE]/10 hover:text-[#00F2FE] text-slate-300 font-bold"
                    title="Heading 3"
                >
                    H3
                </button>
                <button
                    type="button"
                    onClick={() => execCmd('formatBlock', '<p>')}
                    className="px-2 py-1 rounded hover:bg-[#00F2FE]/10 hover:text-[#00F2FE] text-slate-300"
                    title="Paragraph"
                >
                    P
                </button>
                <div className="w-px h-4 bg-slate-800 mx-1" />
                <button
                    type="button"
                    onClick={() => execCmd('bold')}
                    className="p-1.5 rounded hover:bg-[#00F2FE]/10 hover:text-[#00F2FE] text-slate-300"
                    title="Bold"
                >
                    <Bold className="w-3.5 h-3.5" />
                </button>
                <button
                    type="button"
                    onClick={() => execCmd('italic')}
                    className="p-1.5 rounded hover:bg-[#00F2FE]/10 hover:text-[#00F2FE] text-slate-300"
                    title="Italic"
                >
                    <Italic className="w-3.5 h-3.5" />
                </button>
                <button
                    type="button"
                    onClick={() => execCmd('insertUnorderedList')}
                    className="p-1.5 rounded hover:bg-[#00F2FE]/10 hover:text-[#00F2FE] text-slate-300"
                    title="Bulleted List"
                >
                    <List className="w-3.5 h-3.5" />
                </button>
                <button
                    type="button"
                    onClick={() => execCmd('insertOrderedList')}
                    className="p-1.5 rounded hover:bg-[#00F2FE]/10 hover:text-[#00F2FE] text-slate-300"
                    title="Numbered List"
                >
                    <ListOrdered className="w-3.5 h-3.5" />
                </button>
                <button
                    type="button"
                    onClick={() => execCmd('formatBlock', '<blockquote>')}
                    className="p-1.5 rounded hover:bg-[#00F2FE]/10 hover:text-[#00F2FE] text-slate-300"
                    title="Quote Block"
                >
                    <Quote className="w-3.5 h-3.5" />
                </button>
                <button
                    type="button"
                    onClick={handlePromptLink}
                    className="p-1.5 rounded hover:bg-[#00F2FE]/10 hover:text-[#00F2FE] text-slate-300"
                    title="Insert Link"
                >
                    <LinkIcon className="w-3.5 h-3.5" />
                </button>
                <div className="w-px h-4 bg-slate-800 mx-1" />
                <button
                    type="button"
                    onClick={() => execCmd('undo')}
                    className="p-1.5 rounded hover:bg-[#00F2FE]/10 hover:text-[#00F2FE] text-slate-400"
                    title="Undo"
                >
                    <Undo className="w-3.5 h-3.5" />
                </button>
                <button
                    type="button"
                    onClick={() => execCmd('redo')}
                    className="p-1.5 rounded hover:bg-[#00F2FE]/10 hover:text-[#00F2FE] text-slate-400"
                    title="Redo"
                >
                    <Redo className="w-3.5 h-3.5" />
                </button>
            </div>

            {/* Editor Body */}
            {editorMode === 'visual' && (
                <div className="p-6 bg-[#060B18] min-h-[380px] max-h-[620px] overflow-y-auto">
                    <div
                        ref={visualEditableRef}
                        contentEditable
                        onInput={handleVisualInput}
                        onBlur={handleVisualInput}
                        dangerouslySetInnerHTML={{ __html: content }}
                        className="article-prose prose prose-invert max-w-none text-[#F8FAFC] focus:outline-none min-h-[350px]"
                        style={{ whiteSpace: 'normal' }}
                    />
                </div>
            )}

            {editorMode === 'preview' && (
                <div className="p-6 bg-[#060B18] max-h-[620px] overflow-y-auto">
                    <div className="text-xs text-slate-500 mb-4 pb-2 border-b border-slate-800/80 flex items-center justify-between">
                        <span>Live Rendering Output Preview</span>
                        <span className="text-[#00F2FE] font-mono">{content.length} characters</span>
                    </div>
                    <div
                        className="article-prose prose prose-invert max-w-none text-[#F8FAFC]"
                        dangerouslySetInnerHTML={{ __html: content || '<p class="text-slate-500 italic">No content entered yet...</p>' }}
                    />
                </div>
            )}

            {editorMode === 'code' && (
                <div className="p-3 bg-[#03060E]">
                    <textarea
                        id="dark-editor-source-textarea"
                        rows={20}
                        value={content}
                        onChange={(e) => handleContentChange(e.target.value)}
                        placeholder="Raw HTML content..."
                        className="w-full bg-transparent p-3 text-xs font-mono text-[#00F2FE] focus:outline-none resize-y leading-relaxed"
                    />
                </div>
            )}
        </div>
    );
}
