// withHooks
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';


import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibList } from 'esoftplay/cache/lib/list/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { MarketButton } from 'esoftplay/cache/market/button/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketPromotion_product_settingArgs } from 'esoftplay/cache/market/promotion_product_setting/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';

import React from 'react';
import { Text, TouchableOpacity, View } from 'react-native';

export interface MarketPromo_product_item {
  currency: string,
  description: string,
  discount: string,
  discount_title: string,
  id: string,
  image: string,
  location_name: string,
  merchant_name: string,
  price: string,
  price_max: string,
  rating: string,
  rating_count: string,
  rating_value: string,
  sale: string,
  sale_max: string,
  title: string,
  url: string,
  wishlist: string,
  stock_current: string,
  stock_promo: string
}

export interface MarketPromoItem {
  discount_max: string,
  discount_min: string,
  end_datetime: string,
  id: string,
  merchant_product: string,
  price_max: string,
  price_min: string,
  product_cat: string,
  product_list: string,
  start_datetime: string,
  title: string,
}

export interface MarketPromotion_product_selectedArgs {
  promo_id: string,
  promo: MarketPromoItem,
  products: MarketPromo_product_item[],
  product_cat_id: string
}
export interface MarketPromotion_product_selectedProps {

}
export default function m(props: MarketPromotion_product_selectedProps): any {
  const { products, promo, promo_id, product_cat_id } = LibNavigation.getArgsAll<MarketPromotion_product_selectedArgs>(props)
  const [productArray, setProductArray, getProductArray] = useSafeState<MarketPromo_product_item[]>(products)

  esp.log(promo, productArray, 'promoss');

  function submitProduct() {

    let _prod = getProductArray().map((item: any) => {
      return {
        product_id: item?.id,
        promo_stock: item?.stock_promo,//stok promo
        promo_discount: item?.discount, //diskon 10
        promo_sale: item?.sale_promo, //harga promo
        promo_req_id: item?.promo_req_id || 0, //request_id
        product_cat: product_cat_id //category
      }
    })

    let post = {
      promo_list_id: promo.id,
      products: JSON.stringify(_prod)
    }

    LibProgress.show(esp.lang("market/promotion_product_selected", "reg_wait"))
    new LibCurl('shop/merchant_promo_reg', post,
      (res, msg) => {
        esp.log(res, msg)
        LibProgress.hide()
        LibDialog.info(esp.lang("market/promotion_product_selected", "reg_ok"), msg)
        LibNavigation.reset()
        LibNavigation.navigate('market/account_merchant')
      }, (err) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("market/promotion_product_selected", "reg_failed"), err?.message)
      }, 1
    )
  }

  function deleteProduct(index: number) {
    LibDialog.warningConfirm(esp.lang("market/promotion_product_selected", "delete_title"), esp.lang("market/promotion_product_selected", "delete_msg"), esp.lang("market/promotion_product_selected", "delete_confirm"), () => {
      setProductArray((t) => LibObject.splice(t, index, 1)())
    }, esp.lang("market/promotion_product_selected", "delete_cancel"), () => { })
  }

  function dialogConfirm() {
    LibDialog.custom(
      <View style={{ backgroundColor: 'white', alignItems: 'center' }} >
        <LibPicture source={esp.assets('market/dialog_flash_sale.png')} style={{ width: 150, height: 150 }} resizeMode='contain' />
        <Text allowFontScaling={false} style={{ paddingHorizontal: 10, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", lineHeight: 16, letterSpacing: 0, textAlign: "center", color: "#03192a" }} >{esp.lang("market/promotion_product_selected", "confirm_add")}</Text>

        <View style={{ flexDirection: "row", justifyContent: "space-between", marginTop: 20 }} >
          <MarketButton text={esp.lang("market/promotion_product_selected", "cancel")} colorBackground={'#a5a5a5'} textStyle={{ fontSize: 12, color: 'white' }} buttonStyle={{ borderRadius: 20, marginRight: 5 }} onPress={() => LibDialog.hide()} />
          <MarketButton text={esp.lang("market/promotion_product_selected", "yes")} colorBackground={MarketStyle.colorPrimaryMarket} textStyle={{ fontSize: 12, color: 'white' }} buttonStyle={{ borderRadius: 20, marginLeft: 5 }} onPress={() => { }} />
        </View>
      </View >
    )
  }

  return (
    <View style={{ flex: 1 }} >
      <MarketHeader title={esp.lang("market/promotion_product_selected", "header_title")} onlyBack />
      <LibList
        data={productArray}
        renderItem={(item: MarketPromo_product_item, i: number) => {
          return (
            <>
              <View style={{ margin: 5, marginHorizontal: 15, borderRadius: 10, padding: 10, backgroundColor: 'white' }} >
                <View style={{ flexDirection: "row", }} >
                  <LibPicture source={{ uri: item.image }} style={{ height: 60, width: 60, backgroundColor: '#f1f2f3', borderRadius: 5 }} resizeMode="cover"
                  />
                  <View style={{ flex: 1, paddingHorizontal: 10 }}>
                    <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode={'tail'} style={{ fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0 }} >{item?.title}</Text>
                    <Text allowFontScaling={false} style={{ marginTop: 5, fontSize: 16, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: '#000' }} >{LibUtils.money(item?.price, item?.currency)}</Text>
                  </View>
                </View>
                <View style={{ flexDirection: "row", marginTop: 10 }} >
                  <MarketButton text={item?.stock_promo ? esp.lang("market/promotion_product_selected", "change_setting") : esp.lang("market/promotion_product_selected", "setting")}
                    textStyle={{ fontSize: 14 }}
                    onPress={() => {
                      LibNavigation.navigateForResult<MarketPromotion_product_settingArgs>('market/promotion_product_setting', { item: item, setting: { ...promo } }).
                        then((x) => {
                          let product = productArray
                          let _product = product.filter((item: MarketPromo_product_item) => item.id == x.id).map((item2: MarketPromo_product_item) => {
                            return ({
                              ...item2,
                              ...x
                            })
                          })
                          let indexOf = product.map((item: MarketPromo_product_item) => item.id).indexOf(x.id)
                          setProductArray(LibObject.splice(productArray, indexOf, 1, ..._product)())
                        })
                    }}
                    icon={item?.stock_promo ? 'check' : 'cog-outline'}
                    iconSize={18}
                    buttonStyle={{ flex: 1, marginRight: 10 }}
                    color={item?.stock_promo ? MarketStyle.colorGreen : '#707070'}
                    colorBorder={item?.stock_promo ? MarketStyle.colorGreen : '#707070'}
                    colorBackground="white" />
                  <TouchableOpacity onPress={() => { deleteProduct(i) }} style={[{ justifyContent: 'center', paddingHorizontal: 5, alignItems: "center", borderRadius: 5, backgroundColor: 'white' }, LibStyle.elevation(3)]} >
                    <LibIcon name={"delete"} />
                  </TouchableOpacity>
                </View>
              </View>
              <View style={{ borderBottomWidth: 0.5, marginHorizontal: 15, borderBottomColor: '#a5a5a5' }} />
            </>
          )
        }}
      />
      <MarketButton
        onPress={() => {
          if (productArray.length > 0) {
            if (!productArray.some((item: any) => !item.stock_promo)) {
              submitProduct()
            } else {
              LibDialog.warning(esp.lang("market/promotion_product_selected", "set_title"), esp.lang("market/promotion_product_selected", "set_msg"))
            }
          }
        }}
        text={esp.lang("market/promotion_product_selected", "btn_register")}
        textStyle={{ color: 'white' }}
        colorBackground={(productArray.length < 1 || productArray.some((item: any) => !item.stock_promo)) ? '#d1d1d1' : MarketStyle.colorPrimaryMarket}
        buttonStyle={{ margin: 10, borderRadius: 20 }}
      />
    </View>
  )
}