import React, { useState, useEffect } from 'react';
import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Link from '@tiptap/extension-link';
import Youtube from '@tiptap/extension-youtube'; 
import CustomImage from '@/Components/TiptapExtensions/CustomImage'; 
import SocialEmbed from '@/Components/TiptapExtensions/SocialEmbed';

// Icons
import { 
    Bold, Italic, List, ListOrdered, Image as ImageIcon, 
    Quote, Undo, Redo, Youtube as YoutubeIcon,
    Instagram as InstagramIcon, CodeXml 
} from 'lucide-react';

// UI Components
import { Button } from "@/components/ui/button";
import { Toggle } from "@/components/ui/toggle";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea"; 
import axios from 'axios';
import { toast } from 'sonner';

// --- Custom X (Twitter) Icon ---
const XIcon = ({ className }) => (
    <svg viewBox="0 0 24 24" aria-hidden="true" className={className} fill="currentColor">
        <path d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z" />
    </svg>
);

const MenuBar = ({ editor, uploadUrl }) => {
    if (!editor) return null;

    // --- Embed Modal State ---
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modalType, setModalType] = useState(null); 
    const [inputUrl, setInputUrl] = useState('');

    // --- Source Code Modal State ---
    const [isSourceOpen, setIsSourceOpen] = useState(false);
    const [sourceCode, setSourceCode] = useState('');

    // --- Handlers: Embeds ---
    const openModal = (e, type) => {
        if(e) e.preventDefault(); 
        setModalType(type);
        setInputUrl('');
        setIsModalOpen(true);
    };

    const handleInsertEmbed = (e) => {
        if(e && e.preventDefault) e.preventDefault();
        if (!inputUrl) { setIsModalOpen(false); return; }

        if (modalType === 'youtube') {
            editor.commands.setYoutubeVideo({ src: inputUrl });
        } else if (modalType === 'twitter' || modalType === 'instagram') {
            editor.chain().focus().insertContent({
                type: 'socialEmbed',
                attrs: { url: inputUrl, type: modalType }
            }).run();
        }
        setIsModalOpen(false);
        setInputUrl('');
        toast.success(`${modalType === 'twitter' ? 'X' : modalType} embed added!`);
    };

    // --- Handlers: Source Code ---
    const openSourceModal = (e) => {
        if(e) e.preventDefault();
        const html = editor.getHTML();
        setSourceCode(html);
        setIsSourceOpen(true);
    };

    const handleUpdateSource = (e) => {
        if(e && e.preventDefault) e.preventDefault();
        editor.commands.setContent(sourceCode);
        setIsSourceOpen(false);
        toast.success("Content updated from source!");
    };

    const uploadImage = async (e) => {
        const file = e.target.files[0];
        if (!file) return;
        const formData = new FormData();
        formData.append('image', file);
        toast.promise(axios.post(uploadUrl, formData, { headers: { 'Content-Type': 'multipart/form-data' } }), {
            loading: 'Uploading image...',
            success: (response) => {
                if (response.data.url) {
                    editor.chain().focus().insertContent({ type: 'customImage', attrs: { src: response.data.url, caption: '' } }).run();
                }
                return 'Image uploaded!';
            },
            error: 'Upload failed.'
        });
        e.target.value = '';
    };

    return (
        <>
            <div className="border-b bg-muted/30 p-2 flex flex-wrap gap-1 items-center rounded-t-lg sticky top-0 z-10">
                <Toggle size="sm" type="button" pressed={editor.isActive('bold')} onPressedChange={() => editor.chain().focus().toggleBold().run()}>
                    <Bold className="h-4 w-4" />
                </Toggle>
                <Toggle size="sm" type="button" pressed={editor.isActive('italic')} onPressedChange={() => editor.chain().focus().toggleItalic().run()}>
                    <Italic className="h-4 w-4" />
                </Toggle>
                <Toggle size="sm" type="button" pressed={editor.isActive('bulletList')} onPressedChange={() => editor.chain().focus().toggleBulletList().run()}>
                    <List className="h-4 w-4" />
                </Toggle>
                <Toggle size="sm" type="button" pressed={editor.isActive('orderedList')} onPressedChange={() => editor.chain().focus().toggleOrderedList().run()}>
                    <ListOrdered className="h-4 w-4" />
                </Toggle>
                <Toggle size="sm" type="button" pressed={editor.isActive('blockquote')} onPressedChange={() => editor.chain().focus().toggleBlockquote().run()}>
                    <Quote className="h-4 w-4" />
                </Toggle>
                
                <div className="h-4 w-px bg-border mx-1" />

                <Button variant="ghost" size="sm" type="button" className="h-8 w-8 p-0" asChild title="Upload Image">
                    <label className="cursor-pointer">
                        <ImageIcon className="h-4 w-4" />
                        <input type="file" className="hidden" accept="image/*" onChange={uploadImage} />
                    </label>
                </Button>

                <Button variant="ghost" size="sm" type="button" className="h-8 w-8 p-0" onClick={(e) => openModal(e, 'youtube')} title="Embed YouTube">
                    <YoutubeIcon className="h-4 w-4 text-foreground" />
                </Button>

                <Button variant="ghost" size="sm" type="button" className="h-8 w-8 p-0" onClick={(e) => openModal(e, 'twitter')} title="Embed X (Twitter)">
                    <XIcon className="h-3.5 w-3.5 text-foreground" />
                </Button>
                
                <Button variant="ghost" size="sm" type="button" className="h-8 w-8 p-0" onClick={(e) => openModal(e, 'instagram')} title="Embed Instagram">
                    <InstagramIcon className="h-4 w-4 text-foreground" />
                </Button>

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

                {/* --- Source Code Button --- */}
                <Button variant="ghost" size="sm" type="button" className="h-8 w-8 p-0" onClick={openSourceModal} title="Edit HTML Source">
                    <CodeXml className="h-4 w-4 text-purple-600" />
                </Button>

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

                <Button variant="ghost" size="sm" type="button" onClick={() => editor.chain().focus().undo().run()} disabled={!editor.can().undo()} className="h-8 w-8 p-0">
                    <Undo className="h-4 w-4" />
                </Button>
                <Button variant="ghost" size="sm" type="button" onClick={() => editor.chain().focus().redo().run()} disabled={!editor.can().redo()} className="h-8 w-8 p-0">
                    <Redo className="h-4 w-4" />
                </Button>
            </div>

            {/* --- Embed Dialog Modal --- */}
            <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
                <DialogContent className="sm:max-w-md">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2 capitalize">
                            {modalType === 'twitter' ? <XIcon className="w-4 h-4" /> : 
                             modalType === 'instagram' ? <InstagramIcon className="w-5 h-5" /> : 
                             <YoutubeIcon className="w-5 h-5" />}
                            Embed {modalType === 'twitter' ? 'X Post' : modalType}
                        </DialogTitle>
                        <DialogDescription>
                            Paste the full URL of the {modalType === 'twitter' ? 'X' : modalType} content you want to display.
                        </DialogDescription>
                    </DialogHeader>
                    <div className="flex items-center space-x-2 py-4">
                        <div className="grid flex-1 gap-2">
                            <Label htmlFor="link" className="sr-only">Link</Label>
                            <Input
                                id="link"
                                placeholder="https://..."
                                value={inputUrl}
                                onChange={(e) => setInputUrl(e.target.value)}
                                onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleInsertEmbed(); } }}
                                autoFocus
                            />
                        </div>
                    </div>
                    <DialogFooter className="sm:justify-end">
                        <Button type="button" variant="secondary" onClick={() => setIsModalOpen(false)}>Cancel</Button>
                        <Button type="button" onClick={handleInsertEmbed}>Insert Embed</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* --- Source Code Modal --- */}
            <Dialog open={isSourceOpen} onOpenChange={setIsSourceOpen}>
                <DialogContent className="max-w-3xl max-h-[80vh] flex flex-col">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2">
                            <CodeXml className="w-5 h-5 text-purple-600" />
                            HTML Source Editor
                        </DialogTitle>
                        <DialogDescription>
                            Edit the raw HTML content directly. Be careful with syntax.
                        </DialogDescription>
                    </DialogHeader>
                    
                    <div className="flex-1 py-2">
                        <Textarea 
                            className="font-mono text-sm h-[400px] w-full resize-none bg-muted/30"
                            value={sourceCode}
                            onChange={(e) => setSourceCode(e.target.value)}
                            spellCheck={false}
                        />
                    </div>

                    <DialogFooter>
                        <Button type="button" variant="secondary" onClick={() => setIsSourceOpen(false)}>Cancel</Button>
                        <Button type="button" onClick={handleUpdateSource}>Update Source</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </>
    );
};

const extensions = [
    StarterKit,
    Link.configure({ openOnClick: false }),
    Youtube.configure({ controls: true, modestBranding: true, allowFullscreen: true, nocookie: true }),
    CustomImage,
    SocialEmbed, 
];

export default function TiptapEditor({ content, onChange, uploadUrl = '/api/user/editor/image-upload' }) {
    
    const editor = useEditor({
        extensions,
        content: content, 
        editorProps: {
            attributes: {
                class: 'prose prose-sm dark:prose-invert max-w-none min-h-[300px] p-4 focus:outline-none',
            },
        },
        onUpdate: ({ editor }) => {
            onChange(editor.getHTML());
        },
    });

    useEffect(() => {
        if (editor && content !== undefined) {
            if (editor.getHTML() !== content) {
                setTimeout(() => {
                    editor.commands.setContent(content, false);
                }, 0);
            }
        }
    }, [content, editor]);

    return (
        <div className="border rounded-lg shadow-sm w-full bg-card flex flex-col">
            <MenuBar editor={editor} uploadUrl={uploadUrl} />
            <EditorContent editor={editor} className="flex-1" />
        </div>
    );
}