import React, { useState, useRef, useEffect } from 'react';
import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Image from '@tiptap/extension-image'; // <-- NEW
import axios from 'axios';
import { toast } from 'sonner';
import { 
    Bold, Italic, List, ListOrdered, Heading2, 
    Image as ImageIcon, Code, Loader2 
} from 'lucide-react';
import { Button } from "@/Components/ui/button";
import { useTranslation } from '@/hooks/useTranslation';

const MenuBar = ({ editor, isHtmlMode, toggleHtmlMode, onImageUpload, isUploading }) => {
    const { t } = useTranslation();
    const fileInputRef = useRef(null);

    if (!editor) return null;

    const handleFileSelect = (e) => {
        const file = e.target.files[0];
        if (file) {
            onImageUpload(file, editor);
            e.target.value = null; // reset input
        }
    };

    return (
        <div className="flex flex-wrap items-center justify-between p-1 border-b bg-muted/20 rounded-t-md">
            <div className="flex flex-wrap items-center gap-1">
                <Button 
                    variant="ghost" size="icon" type="button"
                    onClick={() => editor.chain().focus().toggleBold().run()}
                    className={editor.isActive('bold') && !isHtmlMode ? 'bg-muted text-primary' : ''}
                    disabled={isHtmlMode}
                >
                    <Bold className="w-4 h-4" />
                </Button>
                
                <Button 
                    variant="ghost" size="icon" type="button"
                    onClick={() => editor.chain().focus().toggleItalic().run()}
                    className={editor.isActive('italic') && !isHtmlMode ? 'bg-muted text-primary' : ''}
                    disabled={isHtmlMode}
                >
                    <Italic className="w-4 h-4" />
                </Button>

                <div className="w-px h-4 bg-border mx-1 hidden sm:block" />

                <Button 
                    variant="ghost" size="icon" type="button"
                    onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
                    className={editor.isActive('heading', { level: 2 }) && !isHtmlMode ? 'bg-muted text-primary' : ''}
                    disabled={isHtmlMode}
                    title={t('Heading 2')}
                >
                    <Heading2 className="w-4 h-4" />
                </Button>

                <Button 
                    variant="ghost" size="icon" type="button"
                    onClick={() => editor.chain().focus().toggleBulletList().run()}
                    className={editor.isActive('bulletList') && !isHtmlMode ? 'bg-muted text-primary' : ''}
                    disabled={isHtmlMode}
                >
                    <List className="w-4 h-4" />
                </Button>
                
                <Button 
                    variant="ghost" size="icon" type="button"
                    onClick={() => editor.chain().focus().toggleOrderedList().run()}
                    className={editor.isActive('orderedList') && !isHtmlMode ? 'bg-muted text-primary' : ''}
                    disabled={isHtmlMode}
                >
                    <ListOrdered className="w-4 h-4" />
                </Button>

                <div className="w-px h-4 bg-border mx-1 hidden sm:block" />

                {/* IMAGE UPLOAD BUTTON */}
                <Button 
                    variant="ghost" size="icon" type="button"
                    onClick={() => fileInputRef.current?.click()}
                    disabled={isHtmlMode || isUploading}
                    title={t('Upload Image')}
                >
                    {isUploading ? <Loader2 className="w-4 h-4 animate-spin text-primary" /> : <ImageIcon className="w-4 h-4 text-blue-500" />}
                </Button>
                <input 
                    type="file" 
                    accept="image/*" 
                    ref={fileInputRef} 
                    onChange={handleFileSelect} 
                    className="hidden" 
                />
            </div>

            {/* SOURCE CODE TOGGLE */}
            <Button 
                variant={isHtmlMode ? "secondary" : "ghost"} 
                size="sm" 
                type="button"
                onClick={toggleHtmlMode}
                className={`gap-2 ${isHtmlMode ? 'bg-primary/10 text-primary hover:bg-primary/20' : 'text-muted-foreground'}`}
            >
                <Code className="w-4 h-4" /> {isHtmlMode ? t('Visual View') : t('HTML Source')}
            </Button>
        </div>
    );
};

export default function TiptapEditor({ value, onChange }) {
    const { t } = useTranslation();
    const [isHtmlMode, setIsHtmlMode] = useState(false);
    const [htmlContent, setHtmlContent] = useState(value || '');
    const [isUploading, setIsUploading] = useState(false);

    // Initialize Tiptap
    const editor = useEditor({
        extensions: [
            StarterKit,
            Image.configure({
                HTMLAttributes: {
                    class: 'rounded-xl border border-border shadow-sm max-w-full h-auto my-4',
                },
            }),
        ],
        content: value,
        editorProps: {
            attributes: {
                class: 'prose prose-sm sm:prose-base dark:prose-invert max-w-none focus:outline-none min-h-[250px] p-4',
            },
        },
        onUpdate: ({ editor }) => {
            const currentHtml = editor.getHTML();
            setHtmlContent(currentHtml);
            onChange(currentHtml);
        },
    });

    // Sync incoming value changes (e.g., if loaded from backend later)
    useEffect(() => {
        if (editor && value !== htmlContent) {
            editor.commands.setContent(value, false);
            setHtmlContent(value || '');
        }
    }, [value, editor]);

    // Handle AJAX Image Upload
    const uploadImage = async (file, currentEditor) => {
        setIsUploading(true);
        const formData = new FormData();
        formData.append('image', file);

        try {
            const res = await axios.post(route('media.upload'), formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });
            
            // Insert image at cursor position
            currentEditor.chain().focus().setImage({ src: res.data.url }).run();
            toast.success(t('Image uploaded successfully!'));
        } catch (error) {
            toast.error(t('Failed to upload image.'));
        } finally {
            setIsUploading(false);
        }
    };

    // Handle raw HTML changes from textarea
    const handleHtmlChange = (e) => {
        const newHtml = e.target.value;
        setHtmlContent(newHtml);
        onChange(newHtml);
        if (editor) {
            editor.commands.setContent(newHtml, false);
        }
    };

    return (
        <div className={`border rounded-xl bg-card overflow-hidden focus-within:ring-2 focus-within:ring-primary/20 focus-within:border-primary transition-all ${isHtmlMode ? 'ring-2 ring-primary/20 border-primary' : 'border-input'}`}>
            <MenuBar 
                editor={editor} 
                isHtmlMode={isHtmlMode} 
                toggleHtmlMode={() => setIsHtmlMode(!isHtmlMode)}
                onImageUpload={uploadImage}
                isUploading={isUploading}
            />
            
            {isHtmlMode ? (
                <textarea
                    value={htmlContent}
                    onChange={handleHtmlChange}
                    className="w-full min-h-[250px] p-4 bg-zinc-950 text-green-400 font-mono text-sm leading-relaxed border-none focus:ring-0 resize-y"
                    placeholder="<p>Enter raw HTML here...</p>"
                    spellCheck="false"
                />
            ) : (
                <div className="bg-background cursor-text min-h-[250px]" onClick={() => editor?.commands.focus()}>
                    <EditorContent editor={editor} />
                </div>
            )}
        </div>
    );
}