use iced::{
    Element,
    Length,
    widget::{
        button,
        column,
        container,
        row,
        scrollable,
        text,
    },
};

use crate::{
    app::{
        Editor,
        Message,
    },
    file_tree::{
        self,
        FileTreeNode,
    },
    theme::*,
};

pub fn view(editor: &Editor) -> Element<'_, Message> {
    let items = if let Some(ref project) = editor.project {
        let mut file_list = column![].spacing(Spacing::MICRO);

        // Recursively find all .sb files
        let mut sb_files = Vec::new();
        fn collect_sb_files(dir: &std::path::Path, files: &mut Vec<std::path::PathBuf>) {
            if let Ok(entries) = std::fs::read_dir(dir) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("sb") {
                        files.push(path);
                    } else if path.is_dir() {
                        collect_sb_files(&path, files);
                    }
                }
            }
        }
        collect_sb_files(&project.root, &mut sb_files);

        // Build hierarchical tree
        let tree = file_tree::build_tree(&project.root, &sb_files);

        // Render tree
        for node in tree {
            file_list = file_list.push(render_tree_node(node, editor, 0));
        }

        file_list
    } else {
        column![
            text("No project loaded")
                .size(14)
                .color(Neutral::WARM_GRAY_400)
        ]
        .spacing(Spacing::SMALL)
    };

    let content = column![items]
        .spacing(Spacing::SMALL)
        .padding([Spacing::MEDIUM, Spacing::SMALL]);

    container(scrollable(content))
        .width(240)
        .height(Length::Fill)
        .style(|_theme| container::Style {
            background: Some(panel_background()),
            border: subtle_border(),
            ..Default::default()
        })
        .into()
}

fn render_tree_node(node: FileTreeNode, editor: &Editor, depth: usize) -> Element<'_, Message> {
    let indent = (depth as f32) * 16.0; // 16px per level

    match node {
        | FileTreeNode::File { path, name } => {
            // Check if this file has an open tab
            let path_clone = path.clone();
            let is_selected = editor
                .active_tab
                .and_then(|idx| editor.tabs.get(idx))
                .map(|tab| {
                    if let crate::app::Tab::File(state) = tab {
                        &state.path == &path_clone
                    } else {
                        false
                    }
                })
                .unwrap_or(false);

            container(
                button(text(name).size(13).color(if is_selected {
                    Gold::_500
                } else {
                    Neutral::WARM_GRAY_100
                }))
                .on_press(Message::OpenFileTab(path))
                .padding([Spacing::MICRO, Spacing::SMALL])
                .style(move |_theme, status| button::Style {
                    background: if is_selected {
                        Some(iced::Background::Color(Aubergine::_600))
                    } else {
                        match status {
                            | button::Status::Hovered => {
                                Some(iced::Background::Color(Aubergine::_700))
                            },
                            | _ => None,
                        }
                    },
                    text_color: if is_selected {
                        Gold::_500
                    } else {
                        Neutral::WARM_GRAY_100
                    },
                    ..Default::default()
                }),
            )
            .padding(iced::Padding::new(0.0).left(indent)) // Left padding for indent
            .into()
        },
        | FileTreeNode::Folder {
            name,
            path,
            children,
        } => {
            let is_expanded = editor.expanded_folders.contains(&path);
            let folder_path = path.clone();

            let mut col = column![].spacing(Spacing::MICRO);

            // Folder header with chevron
            let chevron = if is_expanded { "▼" } else { "▶" };
            let folder_button = container(
                button(
                    row![
                        text(chevron).size(10).color(Neutral::WARM_GRAY_400),
                        text(format!(" {}", name))
                            .size(13)
                            .color(Neutral::WARM_GRAY_200)
                            .font(iced::Font {
                                weight: iced::font::Weight::Bold,
                                ..Default::default()
                            }),
                    ]
                    .spacing(4),
                )
                .on_press(Message::ToggleFolder(folder_path))
                .padding([Spacing::MICRO, Spacing::SMALL])
                .style(|_theme, status| button::Style {
                    background: match status {
                        | button::Status::Hovered => Some(iced::Background::Color(Aubergine::_700)),
                        | _ => None,
                    },
                    text_color: Neutral::WARM_GRAY_200,
                    ..Default::default()
                }),
            )
            .padding(iced::Padding::new(0.0).left(indent)); // Left padding for indent

            col = col.push(folder_button);

            // Render children if expanded
            if is_expanded {
                for child in children {
                    col = col.push(render_tree_node(child, editor, depth + 1));
                }
            }

            col.into()
        },
    }
}
