use crate::data_provider::history::{HistoryItem, get_history_of_set};
use crate::lang::WordData;
use crate::navigation::{NavigatedPage, Page};
use crate::styling::*;
use crate::{AppState, RootMessage};
use HistoryMessage::Back;
use chrono::Local;
use iced::alignment::Horizontal::Center;
use iced::widget::space::horizontal;
use iced::widget::*;
use iced::{Element, Fill, FillPortion, Task};
use std::sync::Arc;
use parking_lot::Mutex;

#[derive(Clone)]
pub struct HistoryState {
    list: Vec<HistoryItem>,
    words: Vec<WordData>,
}

impl NavigatedPage<HistoryMessage> for HistoryState {
    fn navigate(&mut self, message: &HistoryMessage) -> Option<Page> {
        match message {
            Back => Some(Page::PreviousPage),
        }
    }
    fn navigated(&mut self) {}
    fn update(&mut self, _: HistoryMessage) -> Task<RootMessage> {
        Task::none()
    }

    fn view(&self) -> Element<'_, HistoryMessage> {
        back_overlay(
            iced::widget::row![
                horizontal().width(FillPortion(1)),
                scrollable(self.history_lines().padding(DEFAULT_SPACING))
                    .height(Fill)
                    .width(FillPortion(5)),
                horizontal().width(FillPortion(1))
            ]
            .height(Fill)
            .width(Fill)
            .into(),
            Back,
        )
    }
}

impl HistoryState {
    pub fn new(id: crate::lang::Id, state: Arc<Mutex<AppState>>) -> Self {
        let state = state.lock();
        let history = get_history_of_set(id);
        let words = history
            .iter()
            .map(|item| {
                state
                    .dictionary
                    .iter()
                    .find(|w| w.id == item.word_id)
                    .unwrap()
                    .clone()
            })
            .collect();

        Self {
            list: history,
            words,
        }
    }

    fn history_lines(&self) -> Column<'_, HistoryMessage> {
        let mut column = Column::new();
        for (item, index) in self.list.iter().zip(0..self.list.len()) {
            column = column.push(
                row![
                    iced::widget::column![
                        text!("{}", self.words[index].key)
                            .width(Fill)
                            .align_x(Center),
                        text!("{}", self.words[index].value)
                            .width(Fill)
                            .align_x(Center),
                    ]
                    .align_x(Center),
                    iced::widget::column![
                        text!("{} ➞ {}", item.before, item.after),
                        text!(
                            "{}",
                            item.timestamp.with_timezone(&Local).format("%d.%m %H:%M")
                        )
                    ]
                    .spacing(5)
                    .align_x(Center)
                ]
                .spacing(5),
            );
            column = column.push(rule::horizontal(1));
        }
        column.spacing(5)
    }
}

#[derive(Clone)]
pub enum HistoryMessage {
    Back,
}
