import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button } from '@progress/kendo-react-buttons';
import { marked } from 'marked';
import MetadataEditor from '../components/Editor/MetadataEditor';
import WysiwygEditor from '../components/Editor/WysiwygEditor';
import MarkdownEditor from '../components/Editor/MarkdownEditor';
import EditorModeToggle from '../components/Editor/custom/EditorModeToggle';
import PublishModal from '../components/Editor/UI/PublishModal';
import CancelModal from '../components/Editor/UI/CancelModal';
import { getPostBySlug } from '../data/postsCache';

const EditorPage = React.forwardRef((props, ref) => {
    const { slug } = useParams();
    const navigate = useNavigate();
    const [postData, setPostData] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    
    // Editor state management for dual-mode editing
    const [content, setContent] = useState('');
    const [markdownContent, setMarkdownContent] = useState('');
    const [editMode, setEditMode] = useState('html'); // 'html' or 'markdown'
    const [panes, setPanes] = useState([
        { size: '50%' },
        {}
    ]);

    // Modal state management
    const [showPublishModal, setShowPublishModal] = useState(false);
    const [showCancelModal, setShowCancelModal] = useState(false);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

    useEffect(() => {
        const loadPostData = async () => {
            setIsLoading(true);
            try {
                if (slug) {
                    // Editing existing post
                    const post = await getPostBySlug(slug);
                    setPostData(post || null);
                    if (post?.content) {
                        const htmlContent = marked(post.content);
                        setContent(htmlContent);
                        setMarkdownContent(post.content);
                    }
                } else {
                    // New post
                    setPostData(null);
                }
            } catch (error) {
                console.error('Error loading post:', error);
            } finally {
                setIsLoading(false);
            }
        };
        loadPostData();
    }, [slug]);

    if (isLoading) {
        return (
            <div className="content-wrapper" style={{ 
                padding: '50px',
                textAlign: 'center'
            }} ref={ref}>
                <div>Loading editor...</div>
            </div>
        );
    }

    const handlePublish = () => {
        setShowPublishModal(true);
    };

    const handlePublishConfirm = () => {
        console.log('Publish confirmed', { postData });
        setShowPublishModal(false);
        // Demo functionality - would save and publish the post
        navigate('/dashboard');
    };

    const handleSaveDraft = () => {
        console.log('Save Draft clicked', { postData });
        setHasUnsavedChanges(false);
        // Demo functionality - would save as draft
    };

    const handleCancel = () => {
        setShowCancelModal(true);
    };

    const handleCancelConfirm = () => {
        console.log('Cancel confirmed');
        setShowCancelModal(false);
        setHasUnsavedChanges(false);
        navigate('/dashboard');
    };

    // Editor mode toggle handler
    const toggleMode = () => {
        if (editMode === 'html') {
            // Switch to markdown mode - keep the existing markdown content
            setEditMode('markdown');
            // Reset splitter to 50/50 for markdown editor
            setPanes([
                { size: '50%' },
                {}
            ]);
        } else {
            // Switch to HTML mode - convert markdown to HTML
            const htmlContent = marked(markdownContent);
            setContent(htmlContent);
            setEditMode('html');
        }
    };

    // Markdown change handler
    const handleMarkdownChange = (event) => {
        setMarkdownContent(event.target.value);
        setHasUnsavedChanges(true);
    };

    // Content change handler for WYSIWYG editor
    const handleContentChange = (newContent) => {
        setContent(newContent);
        setHasUnsavedChanges(true);
    };

    // Splitter change handler
    const handleSplitterChange = (event) => {
        setPanes(event.newState);
    };

    return (
        <div 
            className="content-wrapper"
            style={{ 
                padding: '20px 0' // Consistent padding
            }} 
            ref={ref}
        >
            <MetadataEditor postData={postData} />
            
            {/* Mode Toggle Button */}
            <EditorModeToggle editMode={editMode} onToggle={toggleMode} />
            
            {/* Conditional Editor Rendering */}
            {editMode === 'html' ? (
                <WysiwygEditor 
                    content={content} 
                    onContentChange={handleContentChange} 
                />
            ) : (
                <MarkdownEditor 
                    markdownContent={markdownContent}
                    onMarkdownChange={handleMarkdownChange}
                    onSplitterChange={handleSplitterChange}
                    panes={panes}
                />
            )}
            
            {/* Action Buttons */}
            <div style={{ 
                padding: '20px', 
                borderTop: '1px solid #e0e0e0',
                display: 'flex',
                gap: '10px',
                justifyContent: 'flex-end'
            }}>
                <Button onClick={handleCancel}>
                    Cancel
                </Button>
                <Button onClick={handleSaveDraft}>
                    Save as Draft
                </Button>
                <Button onClick={handlePublish} themeColor="primary">
                    Publish
                </Button>
            </div>

            {/* Confirmation Modals */}
            <PublishModal
                isVisible={showPublishModal}
                onClose={() => setShowPublishModal(false)}
                onConfirm={handlePublishConfirm}
                postTitle={postData?.title}
            />
            
            <CancelModal
                isVisible={showCancelModal}
                onClose={() => setShowCancelModal(false)}
                onConfirm={handleCancelConfirm}
                hasUnsavedChanges={hasUnsavedChanges}
            />
        </div>
    );
});

export default EditorPage;