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


import { LibInput } from 'esoftplay/cache/lib/input/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibToastProperty } from 'esoftplay/cache/lib/toast/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 React, { useEffect, useRef } from 'react';
import { Platform, ScrollView, Text, View } from 'react-native';


interface ItemSetting {
  discount_max: number,
  discount_min: number,
}

export interface MarketPromotion_product_settingArgs {
  item: any,
  setting: ItemSetting
}
export interface MarketPromotion_product_settingProps {

}

interface ItemData {
  id: string,
  title: string,
  sale: string,
  currency: string,
  stock_promo: number,
  stock_current: string,
  sale_promo: number,
  discount: string
}

export default function m(props: MarketPromotion_product_settingProps): any {
  const { item, setting } = LibNavigation.getArgsAll<MarketPromotion_product_settingArgs>(props)
  const [data, setData] = useSafeState<ItemData>({ id: item.id, title: item.title, sale: item.sale, currency: item.currency, stock_current: item.stocks || item?.promo?.promo_stock, stock_promo: 0, sale_promo: 0, discount: '' })
  const stocks = item.stocks != 0 ? item.stocks : item?.promo?.promo_stock != 0 ? item?.promo?.promo_stock : 0

  let inputPromoStock = useRef<LibInput>(null)
  let inputPromoPrice = useRef<LibInput>(null)

  let inputDiscount = useRef<LibInput>(null)


  const maxPrice = item.sale - ((setting.discount_min / 100) * item.sale)
  const minPrice = item.sale - ((setting.discount_max / 100) * item.sale)

  const [errorStok, setErrorStok] = useSafeState('')
  const [errorPrice, setErrorPrice] = useSafeState('')
  const [errorDisc, setErrorDisc] = useSafeState('')
  const [discountToPost, setDiscountToPost] = useSafeState(0)

  useEffect(() => {
    return () => LibNavigation.cancelBackResult(LibNavigation.getResultKey(props))
  }, [])

  function checkInput() {
    let promoStock = inputPromoStock.current!.getText()
    let promoPrice = inputPromoPrice.current!.getText()
    let discount = inputDiscount.current!.getText()

    if (promoPrice == '') {
      LibToastProperty.show(esp.lang("market/promotion_product_setting", "price_empty"))
      inputPromoPrice.current!.setError('eror')
      inputPromoPrice.current!.focus()
      return
    }
    if (promoStock == '') {
      LibToastProperty.show(esp.lang("market/promotion_product_setting", "empty_product"))
      inputPromoStock.current!.focus()
      return
    }
    if (parseInt(promoStock) > parseInt(stocks)) {
      LibToastProperty.show(esp.lang("market/promotion_product_setting", "stock_promo"))
      inputPromoStock.current!.focus()
      return
    }
    if (parseInt(promoPrice) > parseInt(item.sale)) {
      LibToastProperty.show(esp.lang("market/promotion_product_setting", "price_promo"))
      inputPromoPrice.current!.focus()
      return
    }
    if (discount == '') {
      LibToastProperty.show(esp.lang("market/promotion_product_setting", "empty_disc"))
      inputDiscount.current!.focus()
      return
    }
    if (parseInt(discount) > setting.discount_max) {
      LibToastProperty.show(esp.lang("market/promotion_product_setting", "max_disc", String(setting.discount_max)))
      inputDiscount.current!.focus()
      return
    }
    if (parseInt(discount) < setting.discount_min) {
      LibToastProperty.show(esp.lang("market/promotion_product_setting", "min_disc", String(setting.discount_min)))
      inputDiscount.current!.focus()
      return
    }

    LibNavigation.sendBackResult({ ...data, stock_promo: promoStock, sale_promo: promoPrice, discount: discountToPost }, LibNavigation.getResultKey(props))
  }

  function countDiscountPercentage() {
    let _disc = ((Number(item.sale) - Number(inputPromoPrice?.current?.getText())) / item.sale) * 100
    let _discount = Math.floor(_disc) || 0
    setErrorDisc('')
    setDiscountToPost(_disc)
    inputDiscount?.current?.setText(_discount.toString())
  }

  function countDiscount() {
    let _disc = Number(inputDiscount?.current?.getText()) * 0.01 * item.sale
    let _discount = Number(item.sale) - _disc
    setErrorPrice('')
    inputPromoPrice?.current?.setText(_discount.toString())
  }

  return (
    <View style={{ flex: 1 }} >
      <MarketHeader title={esp.lang("market/promotion_product_setting", "header_title")} onlyBack />
      <ScrollView>

        <View style={{ marginHorizontal: 20, marginTop: 20 }} >
          <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", lineHeight: 14, letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/promotion_product_setting", "promo_stok")}</Text>
          <LibInput
            ref={inputPromoStock}
            base
            allowFontScaling={false}
            onChangeText={(x) => {
              if (errorStok != '') {
                setErrorStok('')
              }
              if (parseInt(inputPromoStock.current!.getText()) > parseInt(stocks)) {
                setErrorStok(esp.lang("market/promotion_product_setting", "stok_promo_high"))
              }
            }}
            placeholder={esp.lang("market/promotion_product_setting", "placeholder_stok")}
            keyboardType='numeric'
            defaultValue={item?.stock_promo}
            mask={"###.###.###.###.###"}
            maskFrom="end"
            style={{ fontFamily: 'Arial', fontSize: 14, paddingVertical: Platform.OS == 'ios' ? 10 : 5, borderBottomWidth: 0.5, borderBottomColor: errorStok ? 'red' : '#a5a5a5' }}
          />
          {
            errorStok ?
              <Text allowFontScaling={false} style={{ paddingTop: 5, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", lineHeight: 17, letterSpacing: 0, textAlign: "left", color: "red" }} >{errorStok}</Text>
              :
              <Text allowFontScaling={false} style={{ paddingTop: 5, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", lineHeight: 17, letterSpacing: 0, textAlign: "left", color: "#707070" }} >{esp.lang("market/promotion_product_setting", "stock_current", LibUtils.number(stocks))}</Text>
          }
        </View>

        <View style={{ marginHorizontal: 20, marginTop: 20 }} >
          <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", lineHeight: 14, letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/promotion_product_setting", "price_before")}</Text>
          <LibInput
            base
            allowFontScaling={false}
            onChangeText={(x) => { }}
            keyboardType='numeric'
            editable={false}
            defaultValue={LibUtils.money(item.sale, item.currency)}
            style={{ color: '#757575', fontFamily: 'Arial', fontSize: 14, paddingVertical: Platform.OS == 'ios' ? 10 : 5, borderBottomWidth: 0.5, borderBottomColor: '#a5a5a5' }}
          />
        </View>

        <View style={{ marginHorizontal: 20, marginTop: 20 }} >
          <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", lineHeight: 14, letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/promotion_product_setting", "price_promo1")}</Text>
          <LibInput
            ref={inputPromoPrice}
            base
            allowFontScaling={false}
            onChangeText={(x) => {
              countDiscountPercentage()
              if (errorPrice != '') {
                setErrorPrice('')
              }
              if (parseInt(x) < minPrice || parseInt(x) > maxPrice) {
                setErrorPrice(esp.lang("market/promotion_product_setting", "price_range", LibUtils.money(minPrice), LibUtils.money(maxPrice)))
              }
            }}
            keyboardType='numeric'
            mask={'###.###.###.###.###'}
            maskFrom="end"
            defaultValue={item?.sale_promo}
            placeholder={esp.lang("market/promotion_product_setting", "placeholder_price_promo")}
            style={{ color: '#757575', fontFamily: 'Arial', fontSize: 14, paddingVertical: Platform.OS == 'ios' ? 10 : 5, borderBottomWidth: 0.5, borderBottomColor: errorPrice ? 'red' : '#a5a5a5' }}
          />
          <Text allowFontScaling={false} style={{ paddingTop: 5, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", lineHeight: 17, letterSpacing: 0, textAlign: "left", color: errorPrice != '' ? 'red' : "#707070" }} >{esp.lang("market/promotion_product_setting", "price_range1", LibUtils.money(minPrice), LibUtils.money(maxPrice))}</Text>
        </View>

        <View style={{ marginHorizontal: 20, marginTop: 20 }} >
          <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", lineHeight: 14, letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/promotion_product_setting", "promo_disc")}</Text>
          <View style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: Platform.OS == 'ios' ? 10 : 5, borderBottomWidth: 0.5, borderBottomColor: errorDisc ? 'red' : '#a5a5a5' }} >
            <LibInput
              ref={inputDiscount}
              base
              allowFontScaling={false}
              onChangeText={(x) => {
                countDiscount()
                if (errorDisc != '') {
                  setErrorDisc('')
                }
                if (parseInt(x) < Number(setting.discount_min) || parseInt(x) > Number(setting.discount_max)) {
                  setErrorDisc(esp.lang("market/promotion_product_setting", "discount_range", String(setting.discount_min), String(setting.discount_max)))
                }
              }}
              defaultValue={item?.discount}
              keyboardType='numeric'
              placeholder={'0'}
              mask={'###'}
              style={{ color: '#757575', fontFamily: 'Arial', fontSize: 14, flex: 1 }}
            />
            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", lineHeight: 17, letterSpacing: 0, color: "#707070" }} >{'%'}</Text>
          </View>
          <Text allowFontScaling={false} style={{ paddingTop: 5, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", lineHeight: 17, letterSpacing: 0, textAlign: "left", color: errorDisc != '' ? 'red' : "#707070" }} >{esp.lang("market/promotion_product_setting", "discount_range1", String(setting.discount_min), String(setting.discount_max))}</Text>
        </View>

      </ScrollView>
      <MarketButton onPress={() => {
        checkInput()
      }} text={esp.lang("market/promotion_product_setting", "btn_save")} buttonStyle={{ margin: 10, borderRadius: 20 }} textStyle={{ color: 'white' }} />
    </View>
  )
}