use iced::{
    Background,
    Element,
    Length,
    widget::{
        button,
        column,
        container,
        row,
        scrollable,
        text,
    },
};
use storybook::syntax::ast::Value;

use crate::{
    app::{
        Editor,
        Message,
        Tab,
    },
    theme::*,
    ui::components::metadata_field,
};

pub fn view(editor: &Editor) -> Element<'_, Message> {
    // If there's an active tab, show its content
    if let Some(idx) = editor.active_tab {
        if let Some(tab) = editor.tabs.get(idx) {
            return match tab {
                | Tab::Character(name) => character_editor_view(editor, name),
                | Tab::File(state) => super::file_editor::view(state, idx),
            };
        }
    }

    // Otherwise show welcome/status screen
    welcome_view(editor)
}

// file_editor_view is now handled by the file_editor module

fn character_editor_view<'a>(editor: &'a Editor, char_name: &str) -> Element<'a, Message> {
    if let Some(ref project) = editor.project {
        // Find the selected character
        let character = project
            .files
            .iter()
            .flat_map(|f| &f.declarations)
            .find_map(|decl| {
                if let storybook::ResolvedDeclaration::Character(c) = decl {
                    if &c.name == char_name {
                        return Some(c);
                    }
                }
                None
            });

        if let Some(char) = character {
            // Character editor form
            let header = row![
                text("Character Editor").size(24).color(Gold::_500),
                text(format!(" – {}", char.name))
                    .size(24)
                    .color(Neutral::CREAM),
            ];

            let mut fields_list = column![].spacing(Spacing::LARGE);

            // Name field with metadata styling
            fields_list = fields_list.push(metadata_field("Name", &char.name));

            // Show all fields with soft metadata styling
            for (field_name, field_value) in &char.fields {
                let value_text = match field_value {
                    | Value::Number(n) => format!("{}", n),
                    | Value::Decimal(n) => format!("{}", n),
                    | Value::Text(s) => s.clone(),
                    | Value::Boolean(b) => format!("{}", b),
                    | Value::List(items) => {
                        format!("[{} items]", items.len())
                    },
                    | Value::Identifier(id) => id.join("::"),
                    | Value::ProseBlock(prose) => {
                        format!(
                            "[Prose: {}...]",
                            prose.content.chars().take(30).collect::<String>()
                        )
                    },
                    | Value::Range(start, end) => {
                        format!("{:?}..{:?}", start, end)
                    },
                    | _ => "[Complex value]".to_string(),
                };

                fields_list = fields_list.push(metadata_field(field_name, &value_text));
            }

            // Add right padding to fields so they don't overlap with scrollbar
            let fields_with_padding = container(fields_list).padding([0.0, Spacing::LARGE]);

            let content = column![header, scrollable(fields_with_padding)]
                .spacing(Spacing::LARGE)
                .padding(Spacing::LARGE);

            return container(content)
                .width(Length::Fill)
                .height(Length::Fill)
                .style(|_theme| container::Style {
                    background: Some(Background::Color(Aubergine::_900)),
                    ..Default::default()
                })
                .into();
        }
    }

    // Character not found
    let content = column![text("Character not found").size(16).color(Semantic::ERROR)]
        .spacing(Spacing::MEDIUM)
        .padding(Spacing::LARGE);

    container(content)
        .width(Length::Fill)
        .height(Length::Fill)
        .style(|_theme| container::Style {
            background: Some(Background::Color(Aubergine::_900)),
            ..Default::default()
        })
        .into()
}

fn welcome_view<'a>(editor: &'a Editor) -> Element<'a, Message> {
    let content = if let Some(ref error) = editor.error_message {
        // Show error message
        column![
            text("Error Loading Project")
                .size(24)
                .color(Semantic::ERROR),
            text(error).size(14).color(Neutral::WARM_GRAY_100),
        ]
        .spacing(Spacing::MEDIUM)
    } else if editor.project.is_some() {
        // Project loaded but no file selected
        column![
            text("Project Loaded").size(32).color(Neutral::CREAM),
            text("Select a file from the file tree to edit")
                .size(16)
                .color(Neutral::WARM_GRAY_100),
        ]
        .spacing(Spacing::MEDIUM)
    } else if editor.project_path.is_some() {
        // Loading state
        column![text("Loading Project...").size(24).color(Neutral::CREAM),].spacing(Spacing::MEDIUM)
    } else {
        // Welcome state with recent projects
        let mut welcome_col = column![
            text("Welcome to Storybook Editor")
                .size(32)
                .color(Neutral::CREAM),
        ]
        .spacing(Spacing::MEDIUM);

        // Show recent projects if any
        if !editor.recent_projects.projects.is_empty() {
            welcome_col = welcome_col.push(text("Recent Projects").size(20).color(Gold::_500));

            let mut projects_list = column![].spacing(Spacing::SMALL);

            for recent in &editor.recent_projects.projects {
                let project_button = button(
                    column![
                        text(&recent.name).size(15).color(Neutral::CREAM),
                        text(recent.path.to_string_lossy().to_string())
                            .size(12)
                            .color(Neutral::WARM_GRAY_400),
                    ]
                    .spacing(2),
                )
                .on_press(Message::ProjectSelected(Some(recent.path.clone())))
                .padding(Spacing::MEDIUM)
                .style(|_theme, status| button::Style {
                    background: match status {
                        | button::Status::Hovered => Some(Background::Color(Aubergine::_700)),
                        | _ => Some(Background::Color(Aubergine::_800)),
                    },
                    text_color: Neutral::CREAM,
                    border: iced::Border {
                        color: Aubergine::_600,
                        width: 1.0,
                        radius: 4.0.into(),
                    },
                    ..Default::default()
                });

                projects_list = projects_list.push(project_button);
            }

            welcome_col = welcome_col.push(projects_list);
        } else {
            welcome_col = welcome_col.push(
                text("Use File → Open to open a project")
                    .size(16)
                    .color(Neutral::WARM_GRAY_100),
            );
        }

        welcome_col.spacing(Spacing::LARGE)
    };

    container(content)
        .width(Length::Fill)
        .height(Length::Fill)
        .padding(Spacing::XXLARGE)
        .style(|_theme| container::Style {
            background: Some(Background::Color(Aubergine::_900)),
            ..Default::default()
        })
        .into()
}
