use crate::message::Message;

use iced::Font;
use iced::alignment::{Horizontal, Vertical};
use iced::daemon::DefaultStyle;
use iced::font::Style;
use iced::widget::text::default;

use iced::theme::Palette;
use iced::widget::Button;
use iced::widget::{TextInput, column, text};
use iced::{
    Alignment, Color, Event, Length, Padding, Task,
    event::{self, Status},
    keyboard::{Key, key::Named},
    widget::{Column, button, canvas, container, pick_list, row, scrollable, slider},
};
use iced::{Element, Theme, theme};
use iced_aw::menu::{self, Item};
use iced_aw::menu_bar;
use iced_aw::widget::color_picker;
use iced_aw::widget::menu::Menu;

use std::f32::consts::PI;
use std::time::Instant;

use crate::MyApp;

pub fn music_view(app: &MyApp) -> iced::Element<Message> {
    let mut i = 0;
    let entries = app.all_sounds.clone();
    //Create all polygon options
    let polygon_rows: Vec<Element<Message>> = app
        .music
        .current_frame(app.current_delta)
        .polygons
        .iter()
        .map(|polygon| {
            let current_index = i;
            let but = button(text("").size(20).center()).on_press(Message::SubmitColor(i));
            let c = column![
                row![
                    text(&polygon.name).size(24),
                    button(text("").size(20)).on_press(Message::Remove(i)),
                    color_picker(
                        polygon.show_color_picker,
                        polygon.color,
                        but,
                        Message::CancelColor(i),
                        move |color| Message::ChooseColor(i, color)
                    ),
                    pick_list(entries.clone(), Some(&polygon.sound_name), move |s| {
                        Message::ChangeSound(current_index, s)
                    })
                    .text_size(20),
                ]
                .spacing(20),
                row![
                    TextInput::new("90", &polygon.global_teta.to_degrees().floor().to_string())
                        .on_input(move |new_value| Message::ChangeDegree(current_index, new_value))
                        .width(Length::FillPortion(1)),
                    row![
                        slider(0.0..=2.0 * PI, polygon.global_teta, move |f| {
                            Message::ChangeTeta(current_index, f)
                        })
                        .step(2. * PI / 10_000.)
                        .width(Length::FillPortion(9))
                    ]
                    .padding(Padding::from(16)),
                ]
                .spacing(5),
            ]
            .spacing(10)
            .into();
            i += 1;
            c
        })
        .collect();
    let ngon_options: Vec<String> = (5..=42).map(|sides| format!("Ngon{sides}")).collect();
    let all_options: Vec<String> = [
        "Segment",
        "Triangle",
        "Square",
        "Nr6In30",
        "Nr7In30",
        "Nr8In30",
        "Nr9In30",
        "Nr8In42",
        "Nr9In42",
        "Nr10aIn42",
        "Nr10bIn42",
    ]
    .iter()
    .map(|s| s.to_string())
    .chain(ngon_options)
    .collect();

    let polygon_column = scrollable(Column::with_children(polygon_rows).spacing(24));

    let menu_tpl_1 = |items| Menu::new(items).max_width(200.0).offset(15.0).spacing(5.0);
    let save_menu = menu_tpl_1(vec![
        Item::new(button("Save File").on_press(Message::Save)),
        Item::new(button("Load Menu").on_press(Message::GoToLoadView).style(
            |theme: &Theme, status| {
                let palette = theme.extended_palette();

                match status {
                    button::Status::Active => {
                        if !app.already_save {
                            button::Style::default().with_background(palette.danger.strong.color)
                        } else {
                            button::primary(theme, status)
                        }
                    }
                    _ => button::primary(theme, status),
                }
            },
        )),
        Item::new("CTRL+F for quit without save."),
    ]);
    column![
        menu_bar!((text("File").size(20), save_menu)(
            text("Shortcuts").size(20),
            menu_tpl_1(vec![Item::new("󰐊 SPACE"), Item::new("󰆓 CTRL+S")])
        ))
        .draw_path(menu::DrawPath::Backdrop)
        .spacing(20),
        text(&app.music.file_name)
            .width(Length::FillPortion(1))
            .size(32),
        row![
            container(
                canvas(app.music.current_frame(app.current_delta))
                    .height(Length::FillPortion(1))
                    .width(Length::FillPortion(1))
            ),
            column![
                text("Polygon options").size(26),
                pick_list(all_options, Some("Choose polygon".to_string()), |s| {
                    Message::AddPolygon(s)
                })
                .text_size(18),
                polygon_column,
            ]
            .spacing(10)
            .height(Length::FillPortion(1))
            .width(Length::FillPortion(2)),
        ]
        .height(Length::FillPortion(2))
        .spacing(20),
        column![
            row![
                button(text(if app.paused { "󰐊" } else { "󰏤" }).size(28).center())
                    .on_press(if app.can_unpaused {
                        Message::TogglePaused
                    } else {
                        Message::None
                    })
                    .width(Length::FillPortion(1)),
                row![
                    TextInput::new("MM:SS:CS", &app.str_time)
                        .on_input(|new_value| Message::ChangeDeltaString(new_value))
                        .size(28),
                    text("/").size(30),
                    TextInput::new("MM:SS:CS", &app.str_music_length)
                        .on_input(|new_value| Message::LengthChange(new_value))
                        .size(28),
                ]
                .width(Length::FillPortion(10)),
                TextInput::new("1.0", &format!("{:.1} sec/rev", &app.music.nb_sec_for_rev))
                    .on_input(|new_value| Message::ChangeNbPerSec(new_value))
                    .size(28)
                    .width(Length::FillPortion(2)),
                button(text("").size(28).center())
                    .on_press(Message::SlidePointLeft)
                    .width(Length::FillPortion(1)),
                button(text("").size(28).center())
                    .on_press(Message::AddPoint)
                    .width(Length::FillPortion(1)),
                button(text("").size(28).center())
                    .on_press(Message::SlidePointRight)
                    .width(Length::FillPortion(1)),
                button(text("").size(28).center())
                    .on_press(Message::RemovePoint)
                    .width(Length::FillPortion(1)),
            ]
            .spacing(20),
            column![
                /*
                slider(0.0..=app.music.length, self.current_delta, move |f| {
                    Message::ChangeDelta(f)
                })
                .step(&app.music.length / 10_000.),*/
                canvas(&app.music)
                    .height(Length::FillPortion(1))
                    .width(Length::FillPortion(1))
            ]
            .spacing(0),
        ]
        .spacing(20)
        .height(Length::FillPortion(1))
        .width(Length::FillPortion(1)),
    ]
    .spacing(25)
    .padding(25)
    .into()
}

pub fn load_file_view(app: &MyApp) -> iced::Element<Message> {
    row![
        column![
            TextInput::new("Name File", &app.file_name_to_creat)
                .on_input(|new_value| Message::SetFileNameCreat(new_value)),
            button("Create File").on_press(Message::CreatFile),
            text(if app.show_warning_message_creat {
                "Warning: File already exists. Delete it or change the file name!"
            } else {
                ""
            })
            .style(|theme: &Theme| {
                let palette = theme.extended_palette();

                text::Style {
                    color: Some(palette.danger.strong.color),
                }
            },)
        ]
        .align_x(Horizontal::Center)
        .width(Length::F),
        column![
            pick_list(
                app.all_saves.clone(),
                Some(&app.music.file_name),
                move |s| Message::FileNameChanged(s),
            ),
            button("Load File").on_press(Message::Load),
        ]
        .align_x(Horizontal::Center)
    ]
    .align_y(Vertical::Center)
    .into()
}
