use crate::widgets::content_view;

use super::db;
use super::widgets;
use iced::widget::row;
use iced::widget::scrollable;
use iced::widget::text_input;
use iced::widget::markdown::Url;
use iced::Task;
use iced::{
    widget::{button, column, container, text},
    Element,
    Length::Fill,
};

pub fn user_interface() -> iced::Result {
    iced::run(update, view)
}

#[derive(Clone, Debug)]
pub enum Page {
    Home,
    FeedView,
    AllItems,
    ItemView,
    Testing,
}

struct State {
    page: Page,
    current_feed: usize,
    current_item: usize,
    feed_input: String
}
impl Default for State {
    fn default() -> Self {
        State { 
            page: Page::Home,
            current_feed: 0,
            current_item: 0,
            feed_input: String::from("")
         }
    }
}

#[derive(Debug, Clone)]
pub enum Message {
    ChangePage(Page),
    LoadFeed(usize),
    AddFeed(String),
    LoadItem(usize),
    FieldUpdated(AppField,String),
    LinkClicked(Url),
    Done(String),
    ResetDB
}

#[derive(Debug,Clone)]
pub enum AppField {
    FeedInput
}

async fn add_feed_background(url: String) -> String {
    println!("Adding feed!");
    db::add_feed(&url);
    "Done adding feed".to_string()
}

fn update(state: &mut State, mes: Message) -> Task<Message>{
    match mes {
        Message::ChangePage(p) => {
            state.page=p;
            Task::none()
        },
        Message::LoadFeed(feed_id) => {
            state.current_feed = feed_id;
            state.page=Page::FeedView;
            Task::none()
        },
        Message::AddFeed(f) => {
            state.feed_input = "".to_string();
            Task::perform(
                add_feed_background(f.to_string()),
                Message::Done
            )
        },
        Message::LinkClicked(l) => {
            println!("Link clicked: {}",l);
            Task::none()
        }
        Message::LoadItem(id) => {
            state.current_item = id;
            state.page = Page::ItemView;
            Task::none()
        }
        Message::Done(_) => {Task::none()},
        Message::FieldUpdated(field, value) => {
            match field {
                AppField::FeedInput => {
                    state.feed_input=value;
                }
            }
            Task::none()
        },
        Message::ResetDB => {
            db::reset();
            Task::none()
        }

    }



}

fn view(state: &State) -> Element<'_, Message> {
    match state.page {
        Page::Home => home(&state),
        Page::FeedView => feed_layout(&state),
        Page::AllItems => item_list(&state),
        Page::ItemView => item_view(&state),
        Page::Testing => testing(&state),
    }
}

fn home(_state: &State) -> Element<'_, Message> {
    container(column!(
        scrollable(widgets::list_feeds()).width(iced::Fill).height(iced::Fill),
        button("Go to test!").on_press(Message::ChangePage(Page::Testing))
    ))
    .padding(15)
    .height(Fill)
    .width(Fill)
    .into()
}


fn feed_layout(state: &State) -> Element<'_, Message> {
    container(
        column!(
            button(text("Home")).on_press(Message::ChangePage(Page::Home)),
            scrollable(widgets::list_items(state.current_feed)).width(iced::Fill).height(iced::Fill),
        )
    )
        .height(Fill)
        .width(Fill)
        .into()
}

fn item_view(state: &State) -> Element<'_, Message> {
    let item = db::get_item(state.current_item);
    container(
        column!(
            row!(
                button(text("Home")).on_press(Message::ChangePage(Page::Home)),
                button(text("Feed")).on_press(Message::ChangePage(Page::FeedView))
            ).spacing(10),
            content_view(item),
        )
    )
        .height(Fill)
        .width(Fill)
        .into()
}

fn item_list(_: &State) -> Element<'_,Message>{
    todo!()
}
fn testing(state: &State) -> Element<'_, Message> {
    column!(
        text("Dev Panel"),
        button("Add gabe.rocks").on_press(Message::AddFeed(String::from("https://gabe.rocks/rss"))),
        button("Add LSN").on_press(Message::AddFeed(String::from("https://libresolutions.network/rss"))),
        row!(
            text_input("Add a feed",&state.feed_input).on_input(|val| Message::FieldUpdated(AppField::FeedInput,val)).width(300),
            button("Add feed!").on_press(Message::AddFeed(state.feed_input.clone()))
        ).spacing(5).padding(10),
        button("Wipe DB").on_press(Message::ResetDB),
        button("go back!").on_press(Message::ChangePage(Page::Home))
    )
    .spacing(5)
    .into()
}
