use crate::DbPool;
use crate::api::ClientVersion;
use crate::providers::Provider;
use crate::status::*;
use crate::util::cache::VideoCache;
use crate::util::discord::{format_error_chain, send_discord_error_report};
use crate::util::time::parse_time_to_seconds;
use crate::videos::{ServerOptions, VideoItem};
use async_trait::async_trait;
use error_chain::error_chain;
use htmlentity::entity::{ICodedDataTrait, decode};
use std::vec;

pub const CHANNEL_METADATA: crate::providers::ProviderChannelMetadata =
    crate::providers::ProviderChannelMetadata {
        group_id: "mainstream-tube",
        tags: &["tube", "clips", "mixed"],
    };

error_chain! {
    foreign_links {
        Io(std::io::Error);
        HttpRequest(wreq::Error);
    }
}

#[derive(Debug, Clone)]
pub struct PornzogProvider {
    url: String,
}

impl PornzogProvider {
    pub fn new() -> Self {
        PornzogProvider {
            url: "https://pornzog.com".to_string(),
        }
    }

    fn build_channel(&self, _clientversion: ClientVersion) -> Channel {
        Channel {
            id: "pornzog".to_string(),
            name: "Pornzog".to_string(),
            description: "Watch free porn videos at PornZog Free Porn Clips. More than 1 million videos, watch for free now!".to_string(),
            premium: false,
            favicon: "https://www.google.com/s2/favicons?sz=64&domain=pornzog.com".to_string(),
            status: "active".to_string(),
            categories: vec![],
            options: vec![ChannelOption {
                id: "sort".to_string(),
                title: "Sort".to_string(),
                description: "Sort the Videos".to_string(),
                systemImage: "list.number".to_string(),
                colorName: "blue".to_string(),
                options: vec![
                    FilterOption {
                        id: "recent".to_string(),
                        title: "Recent".to_string(),
                    },
                    FilterOption {
                        id: "relevance".to_string(),
                        title: "Relevance".to_string(),
                    },
                    FilterOption {
                        id: "viewed".to_string(),
                        title: "Most Viewed".to_string(),
                    },
                    FilterOption {
                        id: "rated".to_string(),
                        title: "Most Rated".to_string(),
                    },
                    FilterOption {
                        id: "longest".to_string(),
                        title: "Longest".to_string(),
                    },
                ],
                multiSelect: false,
            }],
            nsfw: true,
            cacheDuration: None,
            ytdlpCommand: Some("yt-dlp --impersonate chrome-120".to_string())
        }
    }

    async fn query(
        &self,
        cache: VideoCache,
        page: u8,
        query: &str,
        sort: String,
        options: ServerOptions,
    ) -> Result<Vec<VideoItem>> {
        let mut search_params = vec![format!("page={}", page), "site=hdzog".to_string()];
        if !query.is_empty() {
            search_params.push(format!("s={}", query.replace(" ", "+")));
        }
        let sort_string = match sort.as_str() {
            "relevance" => "o=relevance",
            "viewed" => "o=viewed",
            "rated" => "o=rated",
            "longest" => "o=longest",
            _ => "o=recent",
        };
        search_params.push(format!("{}", &sort_string));

        let video_url = format!("{}/search/?{}", self.url, search_params.join("&"));

        let old_items = match cache.get(&video_url) {
            Some((time, items)) => {
                if time.elapsed().unwrap_or_default().as_secs() < 60 * 5 {
                    return Ok(items.clone());
                } else {
                    let _ = cache.check().await;
                    return Ok(items.clone());
                }
            }
            None => vec![],
        };

        // SAFE: Check if requester exists instead of unwrap()
        let mut requester = match options.requester.clone() {
            Some(r) => r,
            None => return Ok(old_items),
        };

        let text = requester
            .get(&video_url, None)
            .await
            .map_err(|e| format!("{}", e))?;
        let video_items: Vec<VideoItem> = self.get_video_items_from_html(text.clone());

        if !video_items.is_empty() {
            cache.remove(&video_url);
            cache.insert(video_url.clone(), video_items.clone());
        } else {
            return Ok(old_items);
        }
        Ok(video_items)
    }

    fn get_video_items_from_html(&self, html: String) -> Vec<VideoItem> {
        if html.is_empty() {
            return vec![];
        }

        let mut items: Vec<VideoItem> = Vec::new();

        // Helper for safe splitting: returns Option<&str>
        fn get_part<'a>(input: &'a str, separator: &str, index: usize) -> Option<&'a str> {
            input.split(separator).nth(index)
        }

        // Split HTML safely
        let sections: Vec<&str> = html.split("class=\"paginator\"").collect();
        let body = match sections.get(0) {
            Some(s) => s,
            None => return vec![],
        };

        let raw_videos: Vec<&str> = body.split("class=\"thumb-video ").skip(1).collect();

        for (idx, video_segment) in raw_videos.iter().enumerate() {
            // Attempt to parse each item. If one fails, we log it and continue to the next
            // instead of crashing the whole request.
            let result: Option<VideoItem> = (|| {
                let mut video_url = get_part(video_segment, "href=\"", 1)?
                    .split("\"")
                    .next()?
                    .to_string();

                if video_url.starts_with("/") {
                    video_url = format!("{}{}", self.url, video_url);
                }

                let title_raw = get_part(video_segment, "alt=\"", 1)?.split("\"").next()?;
                let title = decode(title_raw.as_bytes())
                    .to_string()
                    .unwrap_or(title_raw.to_string());

                // The ID is the 5th element in a "/" split: e.g., "", "video", "123", "title"
                let id = video_url.split("/").nth(4)?.to_string();

                let thumb = get_part(video_segment, "data-original=\"", 1)?
                    .split("\"")
                    .next()?
                    .to_string();

                let raw_duration = get_part(video_segment, "class=\"duration\">", 1)?
                    .split("<")
                    .next()?;
                let duration = parse_time_to_seconds(raw_duration).unwrap_or(0) as u32;
                let tags_section = get_part(video_segment, "class=\"tags\"", 1)?
                    .split("</p>")
                    .next()?;

                let tags = tags_section
                    .split("<a href=\"")
                    .skip(1)
                    .filter_map(|el| {
                        let name = el.split(">").nth(1)?.split("<").next()?;
                        Some(name.to_string())
                    })
                    .collect::<Vec<String>>();

                Some(
                    VideoItem::new(id, title, video_url, "pornzog".to_string(), thumb, duration)
                        .tags(tags),
                )
            })();

            match result {
                Some(item) => items.push(item),
                None => eprintln!("Warning: Failed to parse video item at index {}", idx),
            }
        }
        items
    }
}

#[async_trait]
impl Provider for PornzogProvider {
    async fn get_videos(
        &self,
        cache: VideoCache,
        pool: DbPool,
        sort: String,
        query: Option<String>,
        page: String,
        per_page: String,
        options: ServerOptions,
    ) -> Vec<VideoItem> {
        let _ = per_page;
        let _ = pool;

        let page_num = page.parse::<u8>().unwrap_or(1);
        let query_str = query.unwrap_or_default();

        match self.query(cache, page_num, &query_str, sort, options).await {
            Ok(v) => v,
            Err(e) => {
                eprintln!("Error fetching videos from Pornzog: {}", e);

                // 1. Create a collection of owned data so we don't hold references to `e`
                let mut error_reports = Vec::new();

                // Iterating through the error chain to collect data into owned Strings
                for cause in e.iter().skip(1) {
                    error_reports.push((
                        cause.to_string(),               // Title
                        format_error_chain(cause),       // Description/Chain
                        format!("caused by: {}", cause), // Message
                    ));
                }

                // 2. Now that we aren't holding any `&dyn StdError`, we can safely .await
                for (title, chain_str, msg) in error_reports {
                    let _ = send_discord_error_report(
                        title,
                        Some(chain_str),
                        Some("Pornzog Provider"),
                        Some(&msg),
                        file!(),
                        line!(),
                        module_path!(),
                    )
                    .await;
                }

                vec![]
            }
        }
    }

    fn get_channel(&self, clientversion: ClientVersion) -> Option<Channel> {
        Some(self.build_channel(clientversion))
    }
}
