//! 文档查看器组件 - Phase 4 UI 整合
//! 
//! 统一文档查看界面，支持代码/Markdown/PDF/纯文本

#![allow(non_snake_case)]

use dioxus::prelude::*;
use crate::core::{
    CodeReader,
    renderer::{Renderer, RenderConfig, RenderTheme, DocumentType},
    renderer_enhanced::{EnhancedRenderer, TocGenerator},
    math_renderer::MathMarkdownRenderer,
};

/// 文档类型
#[derive(Debug, Clone, PartialEq)]
pub enum DocType {
    Code,
    Markdown,
    Pdf,
    PlainText,
    Unknown,
}

impl DocType {
    pub fn from_extension(ext: &str) -> Self {
        match ext.to_lowercase().as_str() {
            "rs" | "js" | "ts" | "py" | "go" | "java" | "c" | "cpp" | "cs" | "rb" | "swift" | "kt" | "scala" | "sh" | "sql" | "html" | "css" | "json" | "yaml" | "xml" => DocType::Code,
            "md" | "markdown" => DocType::Markdown,
            "pdf" => DocType::Pdf,
            "txt" => DocType::PlainText,
            _ => DocType::Unknown,
        }
    }
}

/// 查看器状态
#[derive(Debug, Clone, Default)]
pub struct ViewerState {
    /// 当前文档路径
    pub path: String,
    /// 文档类型
    pub doc_type: DocType,
    /// 文档内容
    pub content: String,
    /// 是否显示目录
    pub show_toc: bool,
    /// 当前主题
    pub theme: RenderTheme,
    /// 字体大小
    pub font_size: u16,
    /// 缩放比例 (PDF)
    pub zoom: f32,
    /// 当前页码 (PDF)
    pub page: usize,
}

/// 文档查看器组件
#[component]
pub fn DocumentViewer(
    path: String,
    content: String,
    on_close: EventHandler<Option<String>>,
) -> Element {
    let mut state = use_signal(|| ViewerState {
        path: path.clone(),
        doc_type: DocType::Unknown,
        content: content.clone(),
        show_toc: true,
        theme: RenderTheme::Dark,
        font_size: 14,
        zoom: 1.0,
        page: 0,
    });
    
    let mut renderer = use_signal(|| EnhancedRenderer::new());
    let mut math_renderer = use_signal(|| MathMarkdownRenderer::default());
    
    // 初始化文档类型
    use_effect(move || {
        let ext = std::path::Path::new(&path)
            .extension()
            .and_then(|s| s.to_str())
            .unwrap_or("");
        
        state.write().doc_type = DocType::from_extension(ext);
    });
    
    // 渲染内容
    let rendered_html = use_memo(move || {
        let state_ref = state.read();
        match state_ref.doc_type {
            DocType::Code => {
                let code_reader = CodeReader::new().ok()?;
                let code_doc = code_reader.parse(&state_ref.path, &state_ref.content).ok()?;
                let renderer = Renderer::new(RenderConfig::default()).ok()?;
                renderer.render_to_html(&DocumentType::Code(code_doc)).ok()
            }
            DocType::Markdown => {
                // 使用数学公式渲染器
                math_renderer.read().render(&state_ref.content).ok()
            }
            DocType::Pdf => {
                // TODO: PDF 渲染待实现
                Some(format!("<div><p>PDF 查看器 (待实现)</p><p>路径：{}</p></div>", state_ref.path))
            }
            DocType::PlainText => {
                let renderer = Renderer::new(RenderConfig::default()).ok()?;
                renderer.render_to_html(&DocumentType::PlainText(state_ref.content.clone())).ok()
            }
            DocType::Unknown => {
                Some(format!("<div><p>未知文件类型</p><p>路径：{}</p></div>", state_ref.path))
            }
        }
    });
    
    // 生成目录 (仅 Markdown)
    let toc_html = use_memo(move || {
        let state_ref = state.read();
        if state_ref.doc_type == DocType::Markdown && state_ref.show_toc {
            let mut toc_gen = TocGenerator::new();
            let toc = toc_gen.generate(&state_ref.content);
            Some(toc_gen.to_html(&toc))
        } else {
            None
        }
    });
    
    let theme_class = match state.read().theme {
        RenderTheme::Dark => "dark",
        RenderTheme::Light => "light",
        _ => "dark",
    };
    
    rsx! {
        div {
            class: "document-viewer {theme_class}",
            style: "display: flex; flex-direction: column; height: 100vh;",
            
            // 工具栏
            ViewerToolbar {
                state: state,
                on_close: on_close,
            }
            
            // 主内容区
            div {
                class: "viewer-content",
                style: "display: flex; flex: 1; overflow: hidden;",
                
                // 目录侧边栏
                if state.read().show_toc && toc_html().is_some() {
                    div {
                        class: "toc-sidebar",
                        style: "width: 250px; background: #1e293b; color: #fff; padding: 20px; overflow-y: auto; border-right: 1px solid #475569;",
                        dangerous_inner_html: toc_html().unwrap()
                    }
                }
                
                // 文档内容
                div {
                    class: "document-content",
                    style: "flex: 1; overflow-y: auto; padding: 40px; background: #1a1a2e; color: #eaeaea;",
                    dangerous_inner_html: rendered_html().unwrap_or_default()
                }
            }
        }
    }
}

/// 查看器工具栏
#[component]
fn ViewerToolbar(
    state: Signal<ViewerState>,
    on_close: EventHandler<Option<String>>,
) -> Element {
    let doc_name = state.read().path.split('/').last().unwrap_or("Untitled").to_string();
    
    rsx! {
        div {
            class: "viewer-toolbar",
            style: "display: flex; align-items: center; justify-content: space-between; padding: 10px 20px; background: #0f172a; border-bottom: 1px solid #1e293b; color: #f1f5f9;",
            
            div {
                class: "toolbar-left",
                style: "display: flex; align-items: center; gap: 15px;",
                
                button {
                    class: "toolbar-btn",
                    onclick: move |_| on_close.call(None),
                    style: "background: none; border: none; color: #f1f5f9; cursor: pointer; font-size: 16px; padding: 5px;",
                    "✕"
                }
                
                span {
                    class: "doc-title",
                    style: "font-weight: 600; font-size: 14px;",
                    "{doc_name}"
                }
                
                span {
                    class: "doc-type-badge",
                    style: "background: #00adb5; color: #fff; padding: 2px 8px; border-radius: 4px; font-size: 12px;",
                    "{get_doc_type_label(&state.read().doc_type)}"
                }
            }
            
            div {
                class: "toolbar-right",
                style: "display: flex; align-items: center; gap: 10px;",
                
                // 主题切换
                button {
                    class: "toolbar-btn",
                    onclick: move |_| {
                        let current = state.read().theme;
                        state.write().theme = match current {
                            RenderTheme::Dark => RenderTheme::Light,
                            _ => RenderTheme::Dark,
                        };
                    },
                    style: "background: #1e293b; border: 1px solid #475569; color: #f1f5f9; padding: 5px 10px; border-radius: 4px; cursor: pointer;",
                    "🌓"
                }
                
                // 字体大小
                button {
                    class: "toolbar-btn",
                    onclick: move |_| {
                        let current = state.read().font_size;
                        if current < 24 {
                            state.write().font_size = current + 2;
                        }
                    },
                    style: "background: #1e293b; border: 1px solid #475569; color: #f1f5f9; padding: 5px 10px; border-radius: 4px; cursor: pointer;",
                    "A+"
                }
                
                button {
                    class: "toolbar-btn",
                    onclick: move |_| {
                        let current = state.read().font_size;
                        if current > 10 {
                            state.write().font_size = current - 2;
                        }
                    },
                    style: "background: #1e293b; border: 1px solid #475569; color: #f1f5f9; padding: 5px 10px; border-radius: 4px; cursor: pointer;",
                    "A-"
                }
                
                // 目录切换
                button {
                    class: "toolbar-btn",
                    onclick: move |_| {
                        state.write().show_toc = !state.read().show_toc;
                    },
                    style: "background: #1e293b; border: 1px solid #475569; color: #f1f5f9; padding: 5px 10px; border-radius: 4px; cursor: pointer;",
                    "📑"
                }
            }
        }
    }
}

fn get_doc_type_label(doc_type: &DocType) -> &'static str {
    match doc_type {
        DocType::Code => "CODE",
        DocType::Markdown => "MARKDOWN",
        DocType::Pdf => "PDF",
        DocType::PlainText => "TEXT",
        DocType::Unknown => "UNKNOWN",
    }
}

/// 查看器 CSS
pub fn get_viewer_css() -> &'static str {
    r#"
    .document-viewer {
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    }
    
    .document-viewer.dark {
        --bg-primary: #1a1a2e;
        --bg-secondary: #16213e;
        --text-primary: #eaeaea;
        --accent-color: #00adb5;
    }
    
    .document-viewer.light {
        --bg-primary: #ffffff;
        --bg-secondary: #f7fafc;
        --text-primary: #1a202c;
        --accent-color: #00adb5;
    }
    
    .document-content {
        line-height: 1.6;
    }
    
    .document-content h1, .document-content h2, .document-content h3 {
        margin-top: 24px;
        margin-bottom: 16px;
        font-weight: 600;
        line-height: 1.25;
    }
    
    .document-content h1 { font-size: 2em; border-bottom: 1px solid #475569; padding-bottom: 0.3em; }
    .document-content h2 { font-size: 1.5em; border-bottom: 1px solid #475569; padding-bottom: 0.3em; }
    .document-content h3 { font-size: 1.25em; }
    
    .document-content code {
        background-color: rgba(0, 173, 181, 0.1);
        padding: 0.2em 0.4em;
        border-radius: 3px;
        font-family: "SF Mono", Monaco, "Cascadia Code", monospace;
        font-size: 85%;
    }
    
    .document-content pre {
        background-color: #0f3460;
        padding: 16px;
        border-radius: 6px;
        overflow: auto;
        margin-bottom: 16px;
    }
    
    .document-content pre code {
        background: none;
        padding: 0;
        font-size: 100%;
    }
    
    .toc-sidebar ul {
        list-style: none;
        padding-left: 0;
    }
    
    .toc-sidebar li {
        margin-bottom: 8px;
    }
    
    .toc-sidebar a {
        color: #94a3b8;
        text-decoration: none;
    }
    
    .toc-sidebar a:hover {
        color: #00adb5;
    }
    
    .katex {
        font-size: 1.1em;
    }
    
    .katex-display {
        overflow-x: auto;
        overflow-y: hidden;
        padding: 10px 0;
    }
    "#
}
