use crate::dictionary::DictionaryState;
use crate::lang::{KanaSet, KanaType};
use crate::navigation::Page::*;
use crate::navigation::{NavigatedPage, Page};
use crate::randomizer::RandomizerState;
use crate::repetitions::RepetitionsState;
use crate::selector::SelectorMessage::ChangeMode;
use crate::styling::*;
use crate::sync::SyncState;
use crate::writing::WritingState;
use crate::{AppState, QuizState, RootMessage};
use iced::widget::button::{Status, Style};
use iced::widget::*;
use iced::{Element, Task, alignment};
use iced_core::Alignment::Center;
use iced_core::Background;
use iced_core::Color;
use std::sync::Arc;
use parking_lot::Mutex;

pub struct SelectorState {
    pub set: KanaSet,
    is_writing: bool,
    state: Arc<Mutex<AppState>>,
}

#[derive(Debug, Clone)]
pub enum SelectorMessage {
    Change,
    Goto,
    Check(usize, bool),
    ChangeMode(bool),
    ToDictionary,
    ToRandomize,
    ToRepetitions,
    ToSync,
}

impl NavigatedPage<SelectorMessage> for SelectorState {
    fn navigate(&mut self, message: &SelectorMessage) -> Option<Page> {
        if let SelectorMessage::Goto = message {
            return if self.is_writing {
                let writing = WritingState::new(&self.set);
                Some(Writing(writing))
            } else {
                let mut quiz = QuizState::new();
                quiz.set = self.set.clone();
                Some(Quiz(quiz))
            };
        }
        if let SelectorMessage::ToDictionary = message {
            return Some(Dictionary(DictionaryState::new(self.state.clone())));
        }
        if let SelectorMessage::ToRandomize = message {
            return Some(Randomizer(RandomizerState::default()));
        }
        if let SelectorMessage::ToRepetitions = message {
            return Some(Repetitions(RepetitionsState::new(self.state.clone())));
        }
        if let SelectorMessage::ToSync = message {
            return Some(Sync(SyncState::new(self.state.clone())));
        }
        None
    }

    fn navigated(&mut self) {}
    fn update(&mut self, message: SelectorMessage) -> Task<RootMessage> {
        match message {
            SelectorMessage::Change => match self.set.chars_type {
                KanaType::Katakana => self.set = KanaSet::hiragana(),
                KanaType::Hiragana => self.set = KanaSet::katakana(),
            },
            SelectorMessage::Check(i, b) => self.set.include_map[i] = b,
            ChangeMode(b) => self.is_writing = b,
            _ => {}
        }
        Task::none()
    }
    fn view(&self) -> Element<'_, SelectorMessage> {
        container(
            iced::widget::column![
                row![
                    button("あ ↔ ア")
                        .on_press(SelectorMessage::Change)
                        .style(jl_button),
                    button("Словарь")
                        .on_press(SelectorMessage::ToDictionary)
                        .style(Self::nav_style),
                    button("Повторение")
                        .on_press(SelectorMessage::ToRepetitions)
                        .style(Self::nav_style),
                    button("Рандомайзер")
                        .on_press(SelectorMessage::ToRandomize)
                        .style(Self::nav_style),
                    button("Синхронизация")
                        .on_press(SelectorMessage::ToSync)
                        .style(Self::nav_style)
                ]
                .spacing(DEFAULT_SPACING),
                scrollable(self.rows_selector()).horizontal(),
                toggler(self.is_writing)
                    .label("Режим письма")
                    .on_toggle(ChangeMode),
                button("К тесту")
                    .on_press(SelectorMessage::Goto)
                    .style(cta_button),
            ]
            .spacing(DEFAULT_SPACING),
        )
        .padding(10)
        .into()
    }
}

impl SelectorState {
    pub fn new(state: Arc<Mutex<AppState>>) -> Self {
        Self {
            set: Default::default(),
            is_writing: false,
            state,
        }
    }

    fn nav_style(theme: &Theme, status: Status) -> Style {
        let mut basic = button::text(theme, status);
        basic.background = if status == Status::Hovered {
            Some(Background::Color(Color::WHITE.scale_alpha(0.1)))
        } else {
            None
        };
        basic.border.radius = BUTTON_RADIUS.into();
        basic
    }

    fn rows_selector(&self) -> Element<'_, SelectorMessage> {
        let mut row = Row::new();

        for i in 0..self.set.dictionary.len() {
            let setup_checked = move |b: bool| -> SelectorMessage { SelectorMessage::Check(i, b) };

            let mut chars_column: Column<'_, _> = Column::new();
            chars_column =
                chars_column.push(checkbox(self.set.include_map[i]).on_toggle(setup_checked));

            for v in &self.set.dictionary[i] {
                chars_column = chars_column.push(
                    container(text!("{}", v.0.clone().to_lowercase()).size(40))
                        .align_y(Center)
                        .align_x(Center)
                        .width(80)
                        .height(80)
                        .style(container::rounded_box),
                );
            }

            row = row.push(
                chars_column
                    .spacing(DEFAULT_SPACING)
                    .align_x(alignment::Horizontal::Center),
            );
        }

        row.spacing(DEFAULT_SPACING).into()
    }
}
