import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Image from '@tiptap/extension-image'; // <--- Import Image extension
import Youtube from '@tiptap/extension-youtube'; // <--- Import Youtube extension
import axios from 'axios';
import { toast } from 'sonner';

import { useRef } from 'react';
import { Toggle } from '@/Components/ui/toggle';
import { Separator } from '@/Components/ui/separator';
import {
    Bold, Italic, Strikethrough, List, ListOrdered, Heading2, Quote, Redo, Undo,
    Image as ImageIcon, Youtube as YoutubeIcon // <--- Import new icons
} from 'lucide-react';
import { cn } from '@/lib/utils';

const MenuBar = ({ editor }) => {
    const fileInputRef = useRef(null);

    if (!editor) {
        return null;
    }

    // --- Image Upload Logic ---
    const handleImageUpload = (e) => {
        const file = e.target.files[0];
        if (!file) return;

        const formData = new FormData();
        formData.append('image', file);

        toast.promise(axios.post(route('api.admin.editor.image.upload'), formData), {
            loading: 'Uploading image...',
            success: (response) => {
                const url = response.data.url;
                editor.chain().focus().setImage({ src: url }).run();
                return 'Image uploaded successfully!';
            },
            error: 'Upload failed.',
        });

        // Reset file input
        e.target.value = '';
    };

    // --- Video Embed Logic ---
    const handleVideoEmbed = () => {
        const url = prompt('Enter YouTube video URL:');
        if (url) {
            editor.chain().focus().setYoutubeVideo({ src: url }).run();
        }
    };

    return (
        <div className="flex flex-wrap items-center gap-1 border-b border-input p-2 bg-muted/50">
            {/* Hidden file input */}
            <input 
                type="file" 
                ref={fileInputRef} 
                onChange={handleImageUpload} 
                className="hidden"
                accept="image/*"
            />

            {/* Existing Buttons */}
            <Toggle size="sm" pressed={editor.isActive('bold')} onPressedChange={() => editor.chain().focus().toggleBold().run()}>
                <Bold className="h-4 w-4" />
            </Toggle>
            <Toggle size="sm" pressed={editor.isActive('italic')} onPressedChange={() => editor.chain().focus().toggleItalic().run()}>
                <Italic className="h-4 w-4" />
            </Toggle>
            <Toggle size="sm" pressed={editor.isActive('strike')} onPressedChange={() => editor.chain().focus().toggleStrike().run()}>
                <Strikethrough className="h-4 w-4" />
            </Toggle>
            <Separator orientation="vertical" className="h-8 mx-2" />
            <Toggle size="sm" pressed={editor.isActive('heading', { level: 2 })} onPressedChange={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}>
                <Heading2 className="h-4 w-4" />
            </Toggle>
            <Toggle size="sm" pressed={editor.isActive('bulletList')} onPressedChange={() => editor.chain().focus().toggleBulletList().run()}>
                <List className="h-4 w-4" />
            </Toggle>
            <Toggle size="sm" pressed={editor.isActive('orderedList')} onPressedChange={() => editor.chain().focus().toggleOrderedList().run()}>
                <ListOrdered className="h-4 w-4" />
            </Toggle>
            <Toggle size="sm" pressed={editor.isActive('blockquote')} onPressedChange={() => editor.chain().focus().toggleBlockquote().run()}>
                <Quote className="h-4 w-4" />
            </Toggle>
            <Separator orientation="vertical" className="h-8 mx-2" />

            {/* --- NEW BUTTONS --- */}
            <Toggle size="sm" onClick={() => fileInputRef.current.click()}>
                <ImageIcon className="h-4 w-4" />
            </Toggle>
            <Toggle size="sm" onClick={handleVideoEmbed}>
                <YoutubeIcon className="h-4 w-4" />
            </Toggle>
            
            <Separator orientation="vertical" className="h-8 mx-2" />
            <Toggle size="sm" onClick={() => editor.chain().focus().undo().run()} disabled={!editor.can().undo()}>
                <Undo className="h-4 w-4" />
            </Toggle>
            <Toggle size="sm" onClick={() => editor.chain().focus().redo().run()} disabled={!editor.can().redo()}>
                <Redo className="h-4 w-4" />
            </Toggle>
        </div>
    );
};

export default function RichTextEditor({ content, onChange, className }) {
    const editor = useEditor({
        extensions: [
            StarterKit.configure({
                heading: { levels: [2, 3] },
            }),
            Image, // Register Image extension
            Youtube.configure({ // Register and configure YouTube extension
                controls: true,
                modestBranding: true,
            }),
        ],
        content: content,
        onUpdate: ({ editor }) => {
            onChange(editor.getHTML());
        },
        editorProps: {
            attributes: {
                // Add prose-img for styling images and prose-iframe for videos
                class: 'prose prose-img:rounded-md prose-iframe:aspect-video prose-iframe:w-full prose-iframe:rounded-lg dark:prose-invert min-h-[250px] w-full max-w-none rounded-b-md p-4 focus:outline-none',
            },
        },
    });

    return (
        <div className={cn("rounded-md border border-input bg-background", className)}>
            <MenuBar editor={editor} />
            <EditorContent editor={editor} />
        </div>
    );
}