use crate::ui::main_window::{MainWindowMsg, TabContent};
use anyhow::Result;
use iced::{Length, alignment::Horizontal, widget::Column};
use log::info;

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

impl TabContent for JlcDownloader {
    type TabMessage = JlcDownloaderMsg;

    fn update(&mut self, msg: Self::TabMessage) {
        match msg {
            JlcDownloaderMsg::Nothing => {
                info!("JlcDownloaderMsg::Nothing");
            }
            JlcDownloaderMsg::KeywordChanged(k) => {
                self.search_word = k;
            }
            JlcDownloaderMsg::SearchPart => {
                info!("Clicked Search");
            }
            _ => {
                info!("Whach out the msg: {msg:?}");
            }
        }
    }

    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(20);
        Column::new()
            .align_x(Horizontal::Left)
            .width(Length::Fill)
            .height(Length::Fill)
            .push(h)
            .into()
    }
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct KeywordSearchItem {
    name: String,
}
impl JlcDownloader {
    pub async fn search_keyword(keyword: &str) -> Result<Vec<KeywordSearchItem>> {
        tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
        for i in 0..10 {
            tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
            info!("In async search_keyword print tick {i}");
        }
        Ok(Vec::new())
    }
    pub async fn fetch_item_images(
        item: &KeywordSearchItem,
    ) -> Result<Vec<iced::widget::image::Handle>> {
        tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
        Ok(Vec::new())
    }
}
