use crate::ui::main_window::{MainWindowMsg, TabContent};
use crate::utils::step_downloader::{self as downloader, JlcSearchResultItem};
#[allow(unused_imports)]
use anyhow::Result;
use iced::{Length, Task, alignment::Horizontal, widget::Column};
use tracing::info;

#[derive(Default)]
pub struct JlcDownloader {
    search_word: String,
    search_results: Vec<JlcSearchResultItem>,
    search_error: String,
}
#[allow(dead_code)]
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum JlcDownloaderMsg {
    Nothing,
    KeywordChanged(String),
    KeywordSearchResult(Vec<JlcSearchResultItem>),
    KeywordSearchError(String),
    SearchPart,
}

impl TabContent for JlcDownloader {
    type TabMessage = JlcDownloaderMsg;

    fn update(&mut self, msg: Self::TabMessage) -> Task<MainWindowMsg> {
        match msg {
            JlcDownloaderMsg::Nothing => {
                info!("JlcDownloaderMsg::Nothing");
            }
            JlcDownloaderMsg::KeywordChanged(k) => {
                self.search_word = k;
            }
            JlcDownloaderMsg::SearchPart => {
                return Task::perform(downloader::search_keyword(self.search_word.clone()), |x| {
                    match x {
                        Ok(v) => {
                            MainWindowMsg::JlcDownloader(JlcDownloaderMsg::KeywordSearchResult(v))
                        }
                        Err(e) => {
                            let e = format!("{e:?}");
                            MainWindowMsg::JlcDownloader(JlcDownloaderMsg::KeywordSearchError(e))
                        }
                    }
                });
            }
            JlcDownloaderMsg::KeywordSearchResult(rest) => {
                info!("JlcDownloaderMsg::KeywordSearchResult");
                self.search_error.clear();
                self.search_results = rest;
            }
            JlcDownloaderMsg::KeywordSearchError(e) => {
                self.search_error = e;
            }
        }
        Task::none()
    }

    fn content(&self) -> iced::Element<'_, MainWindowMsg> {
        let h = iced::widget::row![
            iced::widget::text("搜索元件：").align_y(iced::Alignment::Center),
            iced::widget::text_input("元件名或嘉立创编号", &self.search_word)
                .on_input(MainWindowMsg::SearchKeywordChanged),
            iced::widget::button("搜索")
                .on_press(MainWindowMsg::JlcDownloader(JlcDownloaderMsg::SearchPart)),
        ]
        .height(Length::Shrink)
        .spacing(40);
        let c = Column::new()
            .align_x(Horizontal::Left)
            .width(Length::Fill)
            .height(Length::Fill)
            .push(h);

        return c.into();
    }
}
