use crate::value_estimation_team::indicators::wiliams_percent_r;

use super::{
    adx, dec, decimal_add, decimal_div, decimal_mul, decimal_sub, dema, duplicate_filter, ema,
    ema_macd, exists_record, get_server_epoch, heatmap_volume,
    insert_pre_suggested_coins, limit_order_sell, remove_keys, rsi, select_filled_buy_orders,
    stoch_rsi, supertrend, tema, try_join_all, update_record3, wiliams_percent_r, AdxData, AllData,
    Arc, BollingerBandData, Client, ClientBuilder, Decimal, DemaData, EmaData, ExchangeInfo,
    FilteredDataValue, HashMap, HashSet, HeatMapLevel, HeatmapVolumeData, MacdData, Mutex,
    RealtimePriceData, RoundingStrategy, RsiData, StochRsiData, SuperTrendArea, SuperTrendSignal,
    SupertrendData, TemaData, ToPrimitive, TradeFee, WiliamsPercentR,
};

// BUY conditions
pub async fn list_up_for_buy(
    alldata: &AllData,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // print rt_price for debugging
    // let a = alldata.rt_price_30m_vec.iter().position(|a| a.0 == "BTCUSDT");
    // println!("BTCUSDT: {:?}", alldata.rt_price_30m_vec[a.unwrap()].1.last().unwrap());

    // basic filtering: filtering valid trade pair
    let mut filtered_data: HashMap<String, FilteredDataValue> = HashMap::new();
    for symbol in &alldata.valid_symbol_vec {
        filtered_data.insert(symbol.clone(), FilteredDataValue::new());
    }

    // current Tema(3) > current Tema(10)
    // let mut keys_to_remove: HashSet<String> = HashSet::new();
    // let tema_3 = tema(3, &alldata.rt_price_1d_vec, &filtered_data).await?;
    // let tema_10 = tema(10, &alldata.rt_price_1d_vec, &filtered_data).await?;
    // let server_epoch = get_server_epoch().await;
    // for (symbol, values) in &mut filtered_data {
    //     if let (Some(tema5_vec), Some(tema10_vec)) = (tema_3.get(symbol), tema_10.get(symbol)) {
    //         if tema5_vec.len() > 2
    //             && tema10_vec.len() > 2
    //             && tema5_vec.last().unwrap().close_time == tema10_vec.last().unwrap().close_time
    //             && tema5_vec.last().unwrap().close_time > server_epoch
    //             && tema10_vec.last().unwrap().close_time > server_epoch
    //         {
    //             if tema5_vec.last().unwrap().tema_value > tema10_vec.last().unwrap().tema_value {
    //             } else {
    //                 keys_to_remove.insert(symbol.clone());
    //             }
    //         } else {
    //             keys_to_remove.insert(symbol.clone());
    //         }
    //     } else {
    //         keys_to_remove.insert(symbol.clone());
    //     }
    // }
    // remove_keys(&mut filtered_data, keys_to_remove).await;

    // Wiliams %R(200) < -60.0
    // Wiliams %R(50) < -60.0
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let mut wprs200 = wiliams_percent_r(200, &alldata.rt_price_30m_vec, &filtered_data).await?;
    let mut wprs50 = wiliams_percent_r(50, &alldata.rt_price_30m_vec, &filtered_data).await?;
    let server_epoch = get_server_epoch().await;
    for (symbol, values) in &mut filtered_data {
        let mut do_buy = false;
        if let (Some(wpr200_vec), Some(wpr50_vec)) = (wprs200.get(symbol), wprs50.get(symbol)) {
            if wpr200_vec.len() > 15
                && wpr50_vec.len() > 15
                && wpr200_vec.last().unwrap().close_time > server_epoch
                && wpr200_vec.last().unwrap().r_value < -60.0
                && wpr50_vec.last().unwrap().close_time > server_epoch
                && wpr50_vec.last().unwrap().r_value < -60.0
            {
                do_buy = true;
            } 
        }

        if do_buy == false {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    // current Tema(300) < current Tema(200) < current Tema(100)
    // previous Tema(300) < previous Tema(100)
    // previous Tema(200) < previous Tema(100)
    // previous Tema(300) > previous Tema(200)
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let tema_100 = tema(100, &alldata.rt_price_30m_vec, &filtered_data).await?;
    let tema_200 = tema(200, &alldata.rt_price_30m_vec, &filtered_data).await?;
    let tema_300 = tema(300, &alldata.rt_price_30m_vec, &filtered_data).await?;
    let server_epoch = get_server_epoch().await;
    for (symbol, values) in &mut filtered_data {
        let mut do_buy = false;
        if let (Some(tema100_vec), Some(tema200_vec), Some(tema300_vec)) = (
            tema_100.get(symbol),
            tema_200.get(symbol),
            tema_300.get(symbol),
        ) {
            if (tema100_vec.len() > 15 && tema200_vec.len() > 15 && tema300_vec.len() > 15)
                && tema100_vec.last().unwrap().close_time == tema200_vec.last().unwrap().close_time
                && tema200_vec.last().unwrap().close_time == tema300_vec.last().unwrap().close_time
                && tema100_vec.last().unwrap().close_time > server_epoch
            {
                if tema100_vec.last().unwrap().tema_value > tema300_vec.last().unwrap().tema_value
                    && tema200_vec.last().unwrap().tema_value
                        > tema300_vec.last().unwrap().tema_value
                    && tema200_vec.last().unwrap().tema_value
                        < tema100_vec.last().unwrap().tema_value
                    && tema100_vec[tema100_vec.len() - 2].tema_value
                        > tema300_vec[tema300_vec.len() - 2].tema_value
                    && tema200_vec[tema200_vec.len() - 2].tema_value
                        < tema300_vec[tema300_vec.len() - 2].tema_value
                    && tema200_vec[tema200_vec.len() - 2].tema_value
                        < tema100_vec[tema100_vec.len() - 2].tema_value
                    && tema100_vec[tema100_vec.len() - 3].tema_value
                        > tema300_vec[tema300_vec.len() - 3].tema_value
                    && tema200_vec[tema200_vec.len() - 3].tema_value
                        < tema300_vec[tema300_vec.len() - 3].tema_value
                    && tema200_vec[tema200_vec.len() - 3].tema_value
                        < tema100_vec[tema100_vec.len() - 3].tema_value
                {
                    do_buy = true;
                } 
            }
        } 

        if do_buy == false {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    // supertrend(ATR period 10, multiplier: 3.0, 30m close price)
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let server_epoch = get_server_epoch().await;
    let supertrend_30m_map =
        supertrend(10, 3.0, true, &alldata.rt_price_30m_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        let mut do_buy = false;
        if let (Some(supertrend_vec), Some(rt_price_vec)) = (
            supertrend_30m_map.get(symbol),
            alldata.rt_price_30m_vec.get(symbol),
        ) {
            if supertrend_vec.last().unwrap().close_time == rt_price_vec.last().unwrap().close_time
                && rt_price_vec.last().unwrap().close_time > server_epoch
            {
                // input stoploss, target_price
                let band_value: Decimal = rust_decimal::prelude::FromPrimitive::from_f64(
                    supertrend_vec.last().unwrap().band_value,
                )
                .unwrap();
                let open_price: Decimal = rust_decimal::prelude::FromPrimitive::from_f64(
                    rt_price_vec.last().unwrap().open_price,
                )
                .unwrap();
                let current_price: Decimal = rust_decimal::prelude::FromPrimitive::from_f64(
                    rt_price_vec.last().unwrap().close_price,
                )
                .unwrap();
                if supertrend_vec.last().unwrap().area == SuperTrendArea::UP
                    && band_value < current_price
                    && band_value < open_price
                {
                    values.current_price = current_price;
                    values.closetime = rt_price_vec.last().unwrap().close_time;
                    values.stoploss = band_value;
                    values.target_price = decimal_add(
                        decimal_mul(decimal_sub(current_price, values.stoploss), dec!(10.0)),
                        current_price,
                    );
                    do_buy = true;
                } else if supertrend_vec.last().unwrap().area == SuperTrendArea::DOWN
                    && band_value > current_price
                    && band_value > open_price
                {
                    values.current_price = current_price;
                    values.closetime = rt_price_vec.last().unwrap().close_time;
                    values.stoploss = decimal_sub(open_price, decimal_sub(band_value, open_price));
                    values.target_price = decimal_add(
                        decimal_mul(decimal_sub(open_price, values.stoploss), dec!(10.0)),
                        current_price,
                    );
                    do_buy = true;
                }
            }
        }

        if do_buy == false {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    // current ADX(15, 15) < 25
    // let mut keys_to_remove: HashSet<String> = HashSet::new();
    // let adx_vec = adx(15, 15, &alldata.rt_price_30m_vec, &filtered_data).await?;
    // for (symbol, values) in &mut filtered_data {
    //     if let Some(adx_vec) = adx_vec.get(symbol) {
    //         if let Some(last_idx) = adx_vec.iter().position(|elem| elem.close_time == values.closetime) {
    //             if adx_vec.len() > 10 &&
    //             adx_vec[last_idx].adx < 25.0 {
    //             } else {
    //                 keys_to_remove.insert(symbol.clone());
    //             }
    //         } else {
    //             keys_to_remove.insert(symbol.clone());
    //         }
    //     } else {
    //         keys_to_remove.insert(symbol.clone());
    //     }
    // }
    // remove_keys(&mut filtered_data, keys_to_remove).await;

    // StochRSI (RSI_len: 200, StochRSI_len: 200, K: 3, D: 3) K_current < 70, K_prev < 70, K_prev_1 < 70
    // let mut keys_to_remove: HashSet<String> = HashSet::new();
    // let stoch_rsis = stoch_rsi(200, 200, 3, 3, &alldata.rt_price_30m_vec, &filtered_data).await?;
    // for (symbol, values) in &mut filtered_data {
    //     if stoch_rsis.contains_key(symbol) {
    //         let stoch_rsi_vec = stoch_rsis.get(symbol).unwrap();
    //         let search_result = stoch_rsi_vec
    //             .iter()
    //             .position(|x| x.close_time == values.closetime);
    //         if stoch_rsi_vec.len() > 10
    //             && search_result.is_some_and(|a| {
    //                     stoch_rsi_vec[a].k < 70.0
    //                     && stoch_rsi_vec[a - 1].k < 70.0
    //                     && stoch_rsi_vec[a - 2].k < 70.0
    //             })
    //         {
    //         } else {
    //             keys_to_remove.insert(symbol.clone());
    //         }
    //     } else {
    //         keys_to_remove.insert(symbol.clone());
    //     }
    // }
    // remove_keys(&mut filtered_data, keys_to_remove).await;

    // Heatmap volume: filtering close price with Extra High is over the previous candle from 30 previous candles
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let heatmap_volumes = heatmap_volume(
        30,
        30,
        4.0,
        2.5,
        1.0,
        -0.5,
        &filtered_data,
        &alldata.rt_price_30m_vec,
    )
    .await?;
    for (symbol, values) in &mut filtered_data {
        if let Some(heatmap_volume_vec) = heatmap_volumes.get(symbol) {
            if heatmap_volume_vec.len() > 50 {
                let heatmap_volume_trunc = heatmap_volume_vec
                    .get(heatmap_volume_vec.len() - 31..heatmap_volume_vec.len() - 1)
                    .unwrap();
                let windows = heatmap_volume_trunc.windows(2);
                for slice in windows {
                    if slice[1].heatmap_level == HeatMapLevel::ExtraHigh {
                        if let (prev_candle_idx, current_candle_idx) = (
                            (&alldata
                                .rt_price_30m_vec
                                .get(symbol)
                                .unwrap()
                                .iter()
                                .position(|x| x.close_time == slice[0].close_time))
                                .unwrap(),
                            (&alldata
                                .rt_price_30m_vec
                                .get(symbol)
                                .unwrap()
                                .iter()
                                .position(|x| x.close_time == slice[1].close_time))
                                .unwrap(),
                        ) {
                            let prev_candle =
                                &alldata.rt_price_30m_vec.get(symbol).unwrap()[prev_candle_idx];
                            let current_candle =
                                &alldata.rt_price_30m_vec.get(symbol).unwrap()[current_candle_idx];
                            if current_candle.close_price > prev_candle.close_price
                                || current_candle.close_price > prev_candle.open_price
                                || current_candle.close_price > prev_candle.high_price
                                || current_candle.close_price > prev_candle.low_price
                            {
                                keys_to_remove.insert(symbol.clone());
                            }
                        }
                    }
                }
            }
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    // limit buy price: 0.25 * abs(이전 5 개 중 최대값 제거 한 opclo 값 평균 - 현재 open 값) + 현재 open 값 > current_price
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let server_epoch = get_server_epoch().await;
    for (symbol, values) in &mut filtered_data {
        let mut do_buy = false;
        if let Some(rt_price_vec) = alldata.rt_price_30m_vec.get(symbol) {
            if rt_price_vec.last().unwrap().close_time > server_epoch && rt_price_vec.len() >= 6 {
                let mut opclo_vec: Vec<f64> = Vec::new();
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 2].opclo_price);
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 3].opclo_price);
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 4].opclo_price);
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 5].opclo_price);
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 6].opclo_price);
                let max_idx = opclo_vec.iter().position(|&x| {
                    x == *opclo_vec
                        .iter()
                        .max_by(|&a, &b| a.partial_cmp(b).unwrap())
                        .unwrap()
                });
                opclo_vec.remove(max_idx.unwrap());

                let mut mean = 0.0;
                for element in &opclo_vec {
                    mean += element;
                }
                mean /= opclo_vec.len() as f64;
                let current_price = rt_price_vec.last().unwrap().close_price;
                let difference = (mean - rt_price_vec.last().unwrap().open_price).abs();

                if current_price < rt_price_vec.last().unwrap().open_price + (0.5 * difference) {
                    do_buy = true;
                } 
            }
        }

        if do_buy == false {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    let final_filtered_data = duplicate_filter(8, &filtered_data).await?;

    if !final_filtered_data.is_empty() {
        insert_pre_suggested_coins(8, false, &final_filtered_data).await;
    }

    Ok(())
}

pub async fn list_up_for_sell(
    all_data: &AllData,
    exchange_info_map: &HashMap<String, ExchangeInfo>,
    trade_fee_map: &HashMap<String, TradeFee>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let filled_buy_orders = select_filled_buy_orders(8).await?;

    if !filled_buy_orders.is_empty() {
        let client = ClientBuilder::new()
            .timeout(tokio::time::Duration::from_millis(5000))
            .build()
            .unwrap();
        let mut supertrend_vec: Vec<SupertrendData> = Vec::new();
        let server_epoch = get_server_epoch().await;
        let mut filtered_symbols: HashMap<String, FilteredDataValue> = HashMap::new();
        for element in &filled_buy_orders {
            filtered_symbols.insert(element.symbol.clone(), FilteredDataValue::new());
        }
        let supertrend_30m =
            supertrend(10, 3.0, true, &all_data.rt_price_30m_vec, &filtered_symbols).await?;
        let tema_300 = tema(300, &all_data.rt_price_30m_vec, &filtered_symbols).await?;
        let tema_200 = tema(200, &all_data.rt_price_30m_vec, &filtered_symbols).await?;
        let tema_100 = tema(100, &all_data.rt_price_30m_vec, &filtered_symbols).await?;
        for element in filled_buy_orders {
            let mut is_sell = false;
            let mut is_overturned = false;
            if element.used_usdt >= dec!(10.0) {
                if let (Some(tema300_vec), Some(tema200_vec), Some(tema100_vec)) = (
                    tema_300.get(&element.symbol),
                    tema_200.get(&element.symbol),
                    tema_100.get(&element.symbol),
                ) {
                    if tema200_vec.len() > 2
                        && tema100_vec.len() > 2
                        && tema300_vec.len() > 2
                        && tema200_vec.last().unwrap().close_time
                            == tema100_vec.last().unwrap().close_time
                        && tema300_vec.last().unwrap().close_time
                            == tema100_vec.last().unwrap().close_time
                        && tema300_vec.last().unwrap().close_time > server_epoch
                        && tema200_vec.last().unwrap().close_time > server_epoch
                        && tema100_vec.last().unwrap().close_time > server_epoch
                        && ((tema200_vec.last().unwrap().tema_value
                            > tema100_vec.last().unwrap().tema_value
                            && tema200_vec[tema200_vec.len() - 2].tema_value
                                < tema100_vec[tema100_vec.len() - 2].tema_value)
                            || (tema200_vec.last().unwrap().tema_value
                                > tema300_vec.last().unwrap().tema_value
                                && tema200_vec[tema200_vec.len() - 2].tema_value
                                    < tema300_vec[tema300_vec.len() - 2].tema_value))
                    {
                        is_overturned = true;
                    }
                }

                if let (Some(exchange_info), Some(tradefee), Some(supertrend_vec)) = (
                    exchange_info_map.get(&element.symbol),
                    trade_fee_map.get(&element.symbol),
                    supertrend_30m.get(&element.symbol),
                ) {
                    // update stoploss
                    let band_value: Decimal = rust_decimal::prelude::FromPrimitive::from_f64(
                        supertrend_vec.last().unwrap().band_value,
                    )
                    .unwrap();
                    if supertrend_vec.last().unwrap().area == SuperTrendArea::UP
                        && band_value > element.stoploss
                    {
                        let update_table_name = String::from("buy_ordered_coin_list");
                        let update_value = vec![(String::from("stoploss"), band_value.to_string())];
                        let update_condition = vec![(String::from("id"), element.id.to_string())];
                        update_record3(&update_table_name, &update_value, &update_condition)
                            .await
                            .unwrap();
                    }

                    let lot_step_size = exchange_info.stepsize;
                    let quote_commission_precision = exchange_info.quote_commission_precision;

                    // TODO: BNB 코인이 있으면
                    // let base_qty_to_be_ordered =
                    //     element.base_qty_ordered.round_dp_with_strategy(
                    //         lot_step_size.normalize().scale(),
                    //         RoundingStrategy::ToZero,
                    //     );
                    // TODO: BNB 코인이 없으면
                    let base_qty_to_be_ordered =
                        element.base_qty_fee_adjusted.round_dp_with_strategy(
                            lot_step_size.normalize().scale(),
                            RoundingStrategy::ToZero,
                        );
                    let target_profit_percent = decimal_mul(
                        decimal_div(
                            decimal_sub(element.target_price, element.buy_price),
                            element.buy_price,
                        ),
                        dec!(100),
                    )
                    .to_f64()
                    .unwrap();
                    if !element.current_price.is_zero() {
                        if element.current_price <= element.stoploss {
                            is_sell = true;
                        } else if element.current_price >= element.target_price {
                            is_sell = true;
                        } else if server_epoch - element.transact_time >= (1_800_000) * 5
                            && is_overturned == true
                        {
                            is_sell = true;
                        }

                        let minimum_candles = 5;
                        let maximum_candles = 240;
                        for count_candles in minimum_candles..=maximum_candles {
                            if count_candles < maximum_candles
                                && server_epoch - element.transact_time
                                    > (1_800_000) * count_candles
                                && (target_profit_percent != 0.0
                                    && target_profit_percent.is_sign_positive()
                                    && target_profit_percent
                                        * ((maximum_candles - count_candles) as f64
                                            / (maximum_candles - minimum_candles + 1) as f64)
                                        <= element.pure_profit_percent)
                            {
                                is_sell = true;
                                break;
                            } else {
                                break;
                            }
                        }

                        if server_epoch - element.transact_time >= (1_800_000) * maximum_candles {
                            // time up selling
                            is_sell = true;
                        }

                        // TODO: sell_count가 1일 때 적용하기
                        // else if (supertrend_vec
                        //     .last()
                        //     .unwrap()
                        //     .signal
                        //     .as_ref()
                        //     .is_some_and(|x| x.contains("SELL"))
                        //     || supertrend_vec.last().unwrap().area.contains("DOWN"))
                        //     && (supertrend_vec.last().unwrap().close_time > element.close_time)
                        // {
                        //     println!(
                        //         "SELL signal selling {} {:.2}",
                        //         element.symbol, element.pure_profit_percent
                        //     );
                        //     limit_order_sell(
                        //         &element,
                        //         element.current_price,
                        //         base_qty_to_be_ordered,
                        //         &client,
                        //         &exchange_info_vec,
                        //         &trade_fee_vec,
                        //     )
                        //     .await;
                        // }
                        if is_sell == true {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_map,
                                &trade_fee_map,
                            )
                            .await;
                        }
                    }
                }
            }
        }
    }

    Ok(())
}
