// withHooks

import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDatepicker } from 'esoftplay/cache/lib/datepicker/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibInput } from 'esoftplay/cache/lib/input/import';
import { LibKeyboard_avoid } from 'esoftplay/cache/lib/keyboard_avoid/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/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 { MarketImage_picker } from 'esoftplay/cache/market/image_picker/import';
import { MarketInput_label } from 'esoftplay/cache/market/input_label/import';
import { MarketInput_select } from 'esoftplay/cache/market/input_select/import';
import { MarketInput_square } from 'esoftplay/cache/market/input_square/import';
import { MarketMerchant_voucher_inputProperty } from 'esoftplay/cache/market/merchant_voucher_input/import';
import { MarketSection_menu } from 'esoftplay/cache/market/section_menu/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';
import { MarketTime_picker } from 'esoftplay/cache/market/time_picker/import';
import { MarketToggle } from 'esoftplay/cache/market/toggle/import';
import esp from 'esoftplay/esp';

import useGlobalState, { useGlobalReturn } from 'esoftplay/global';
import moment from 'esoftplay/moment';
import useSafeState from 'esoftplay/state';
import React, { useEffect, useRef } from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface Marketmerchant_voucher_inputArgs {

}
export interface Marketmerchant_voucher_inputProps {

}

const _state = useGlobalState([])

export function state(): useGlobalReturn<any> {
  return _state
}

export default function m(props: Marketmerchant_voucher_inputProps): any {
  const { url, id } = LibNavigation.getArgsAll<any>(props)

  const dialogTypeVoucher = React.useRef<LibSlidingup>(null)
  const dialogDate = React.useRef<LibSlidingup>(null)
  const dialogTime = React.useRef<LibSlidingup>(null)
  const [date, setDate] = useSafeState<any>(moment().localeFormat("YYYY-MM-DD"))
  const [whatDate, setWhatDate] = useSafeState<string>('start')
  const [startDate, setStartDate, getStartDate] = useSafeState<string>('')
  const [endDate, setEndDate, getEndDate] = useSafeState<string>('')

  const [whatTime, setWhatTime] = useSafeState<string>('')
  const [startTime, setStartTime, getStartTime] = useSafeState<string>('')
  const [endTime, setEndTime, getEndTime] = useSafeState<string>('')
  const [voucherType, setVoucherType, getVoucherType] = useSafeState<any>()
  const [discType, setDiscType] = useSafeState<any>()
  const [showVoucher, setShowVoucher] = useSafeState<boolean>(true)
  const [selectedProduct, setSelectedProduct, getSelectedProduct] = MarketMerchant_voucher_inputProperty.state().useState()
  const [image, setImage] = useSafeState<any>()
  const [resultVoucher, setResultVoucher] = useSafeState<any>()

  const [msgRes, setMsg] = useSafeState<any>()
  const [msgError, setMsgError, getMsgError] = useSafeState<any>()

  const imagePicker = useRef<LibSlidingup>(null)
  const inputName = useRef<LibInput>(null)
  const inputDescription = useRef<LibInput>(null)
  const inputCode = useRef<LibInput>(null)
  const inputClaim = useRef<LibInput>(null)
  const inputMinOrder = useRef<LibInput>(null)

  let _voucherType = [
    {
      id: 1,
      title: esp.lang("market/merchant_voucher_input", "vc_merchant"),
      subtitle: esp.lang("market/merchant_voucher_input", "vc_merchant_info"),
    },
    {
      id: 2,
      title: esp.lang("market/merchant_voucher_input", "vc_product"),
      subtitle: esp.lang("market/merchant_voucher_input", "vc_product_info"),
    },
  ]

  useEffect(() => {
    if (url) {
      // direset dulu sebelum di isi
      setSelectedProduct([])
      LibProgress.show(esp.lang("market/merchant_voucher_input", "wait"))
      new LibCurl(url, null, (res, msg) => {
        setResultVoucher(res)
        esp.log(res, "load data voucher");
        // untuk ngisi default value
        if (res?.hasOwnProperty("product_ids")) {
          let producs = res?.product_ids?.map((item: any) => {
            return {
              'id': item
            }
          })
          setSelectedProduct(producs)
        } else {

        }

        if (res.use_product == "0") {
          let vouMerchant = {
            id: 1,
            title: esp.lang("market/merchant_voucher_input", "vc_merchant1")
          }
          setVoucherType(vouMerchant)
        } else {
          let vouProduct = {
            id: 2,
            title: esp.lang("market/merchant_voucher_input", "vc_merchant_2")
          }
          setVoucherType(vouProduct)
        }
        setImage(res.image)
        inputName.current!.setText(res.title)
        inputDescription.current!.setText(res.description)
        inputCode.current!.setText(res.code)
        setDate(moment(res.start_date).localeFormat("YYYY-MM-DD"))
        setStartDate(moment(res.start_date).localeFormat("YYYY-MM-DD"))
        setStartTime(moment(res.start_date).localeFormat('HH:mm'))

        setEndDate(moment(res.expired_date).localeFormat("YYYY-MM-DD"))
        setEndTime(moment(res.expired_date).localeFormat('HH:mm'))
        inputClaim.current!.setText(res.qty)

        let typeDisc = {
          title: res.amount_type == "1" ? esp.lang("market/merchant_voucher_input", "disc_nominal", LibUtils.money(res?.amount)) : esp.lang("market/merchant_voucher_input", "disc_percent", res?.amount) + "%",
          amount_type: res.amount_type,
          amount: res.amount,
          amount_max: res.amount_max
        }
        setDiscType(typeDisc)
        inputMinOrder.current!.setText(res.order_min)
        setShowVoucher(res.publish == 1 ? true : false)

        LibProgress.hide()
      }, (error) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("market/merchant_voucher_input", "failed_get"), error?.message)
        LibNavigation.back()
      }, 1)
    }
  }, [])

  function checkInput() {
    if (!getVoucherType()) {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_type"))
      return false
    }
    if (inputName.current!.getText() == "") {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_name"))
      return false
    }
    if (inputDescription.current!.getText() == "") {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_desc"))
      return false
    }
    if (inputCode.current!.getText() == "") {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_code"))
      return false
    }
    if (getMsgError()) {
      LibToastProperty.show(getMsgError())
      return false
    }
    if (getStartDate() == "") {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_start_date"))
      return false
    }
    if (getStartTime() == "") {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_start_time"))
      return false
    }
    if (getEndDate() == "") {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_end_date"))
      return false
    }
    if (getEndTime() == "") {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_end_time"))
      return false
    }

    if (getStartDate() == getEndDate()) {
      if (endTime <= startTime) {
        LibToastProperty.show(esp.lang("market/merchant_voucher_input", "notvalid_end_time"))
        return false
      }
    }

    if (inputClaim.current!.getText() == "") {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_quota"))
      return false
    }
    if (parseInt(inputClaim.current!.getText()) <= 0) {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "quota_not_valid"))
      return false
    }
    if (!discType) {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_type_disc"))
      return false
    }
    if (inputMinOrder.current!.getText() == "") {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_minimal"))
      return false
    }
    if (inputName.current!.getText() == "") {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_vc_name"))
      return false
    }
    if (getVoucherType()?.id == 2 && !getSelectedProduct()) {
      LibToastProperty.show(esp.lang("market/merchant_voucher_input", "empty_product"))
      return false
    }
    return true
  }

  function addVoucher() {
    let productIds = getSelectedProduct()?.map((it: any) => it.id)
    LibDialog.warningConfirm(esp.lang("market/merchant_voucher_input", "add_voucher_title"), esp.lang("market/merchant_voucher_input", "add_voucher_msg"), esp.lang("market/merchant_voucher_input", "add_voucher_confirm"), () => {
      let post: any = {
        image: image,
        title: inputName.current!.getText(),
        description: inputDescription.current!.getText(),
        qty: inputClaim.current!.getText(),
        amount_type: discType?.amount_type,
        amount: discType?.amount,
        amount_max: discType?.amount_max,
        order_min: inputMinOrder.current!.getText(),
        code: inputCode.current!.getText(),
        cat: 1,
        publish: showVoucher ? 1 : 0,
        start_date: startDate + " " + startTime,
        expired_date: endDate + " " + endTime
      }

      if (voucherType?.id == 2) {
        post['product_ids'] = JSON.stringify(productIds)
      }

      LibProgress.show(esp.lang("market/merchant_voucher_input", "add_voucher_wait"))
      new LibCurl('shop/merchant_voucher_add', post, (res, msg) => {
        esp.log(res, msg);
        LibProgress.hide()
        LibDialog.info(esp.lang("market/merchant_voucher_input", "add_voucher_ok"), msg)
        LibNavigation.back()
      }, (error) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("market/merchant_voucher_input", "add_voucher_failed"), error?.message)
        esp.log(error);
      }, 1)

    }, esp.lang("market/merchant_voucher_input", "add_voucher_cancel"), () => { })
  }

  function editVoucher() {
    let productIds = getSelectedProduct()?.map((it: any) => it.id)
    LibDialog.warningConfirm(esp.lang("market/merchant_voucher_input", "edit_voucher_title"), esp.lang("market/merchant_voucher_input", "edit_voucher_msg"), esp.lang("market/merchant_voucher_input", "edit_voucher_confirm"), () => {
      let post: any = {
        image: image,
        title: inputName.current!.getText(),
        description: inputDescription.current!.getText(),
        qty: inputClaim.current!.getText(),
        amount_type: discType?.amount_type,
        amount: discType?.amount,
        amount_max: discType?.amount_max,
        order_min: inputMinOrder.current!.getText(),
        code: inputCode.current!.getText(),
        cat: 1,
        publish: showVoucher ? 1 : 0,
        start_date: startDate + " " + startTime,
        expired_date: endDate + " " + endTime
      }

      if (voucherType?.id == 2) {
        post['product_ids'] = JSON.stringify(productIds)
      }

      LibProgress.show(esp.lang("market/merchant_voucher_input", "progres"))
      new LibCurl('shop/merchant_voucher_edit?id=' + id, post, (res, msg) => {
        esp.log(res, msg);
        LibProgress.hide()
        LibDialog.info(esp.lang("market/merchant_voucher_input", "edit_voucher_ok"), msg)
        LibNavigation.back()
      }, (error) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("market/merchant_voucher_input", "edit_voucher_failed"), error?.message)
        esp.log(error);
      }, 1)

    }, esp.lang("market/merchant_voucher_input", "edit_voucher_cancel"), () => { })
  }

  function checkCodeVoucher(code: string) {
    new LibCurl('shop/voucher_check?code=' + code.trim() + "&voucher_id=" + resultVoucher?.id, null, (res, msg) => {
      setMsg(msg)
      setMsgError(undefined)
    }, (error) => {
      setMsgError(error?.message)
      setMsg(undefined)
    }, 1)
  }

  return (
    <View style={{ flex: 1, backgroundColor: '#F5F5F5' }}>
      <MarketHeader title={url ? esp.lang("market/merchant_voucher_input", "header_edit") : esp.lang("market/merchant_voucher_input", "header_add")} onlyBack style={{ backgroundColor: '#fff' }} />
      <LibKeyboard_avoid style={{ flex: 1 }}>
        <ScrollView>
          <View style={{ backgroundColor: '#fff', paddingTop: 4 }}>
            <MarketInput_select onPress={() => { dialogTypeVoucher.current!.show() }} value={voucherType?.title} placeholder={esp.lang("market/merchant_voucher_input", "select_type")} />
          </View>
          <View style={{ backgroundColor: '#fff', marginTop: 10, paddingTop: 4, paddingBottom: 5 }}>

            <View style={{ marginHorizontal: 17, marginTop: 10 }}>
              <MarketInput_label label={esp.lang("market/merchant_voucher_input", "label_image")} />
              <View style={{ flexDirection: "row", flexWrap: "wrap", marginBottom: 5 }} >
                {
                  image ?
                    <TouchableOpacity key={image} onPress={() => { imagePicker.current!.show() }} >
                      <LibPicture source={{ uri: image }} style={{ height: (LibStyle.width - 34) / 3, width: LibStyle.width - 34, borderRadius: 10, marginRight: 10, marginTop: 10, backgroundColor: "#f1f2f3", borderColor: "#ddd", borderWidth: 1 }} />
                      <LibIcon name="close-circle" size={17} color={"#aaa"} style={{ position: "absolute", top: 15, right: 15, ...LibStyle.elevation(2) }} />
                    </TouchableOpacity>
                    :
                    <TouchableOpacity
                      onPress={() => { imagePicker.current!.show() }}
                      style={{ height: (LibStyle.width - 34) / 3, width: LibStyle.width - 34, borderRadius: 10, marginRight: 10, marginBottom: 10, marginTop: 10, backgroundColor: "#f1f2f3", borderColor: "#ddd", borderWidth: 1, justifyContent: "center", alignItems: "center" }} >
                      <LibIcon.SimpleLineIcons name="picture" color={"#aaa"} />
                    </TouchableOpacity>
                }
              </View>
            </View>

            <MarketInput_square
              _ref={inputName}
              onChangeText={() => { }}
              placeholder={esp.lang("market/merchant_voucher_input", "name")}
              label={esp.lang("market/merchant_voucher_input", "label_name")}
              mandatory
            />

            <MarketInput_square
              _ref={inputDescription}
              onChangeText={() => { }}
              multiline
              style={{ textAlignVertical: "top", height: 100 }}
              placeholder={esp.lang("market/merchant_voucher_input", "description")}
              label={esp.lang("market/merchant_voucher_input", "label_desc")}
              mandatory
            />

            <MarketInput_square
              _ref={inputCode}
              onChangeText={(t) => {
                LibUtils.debounce(() => {
                  checkCodeVoucher(t)
                }, 300)
              }}
              placeholder={esp.lang("market/merchant_voucher_input", "code")}
              autoCapitalize="characters"
              mandatory
              label={esp.lang("market/merchant_voucher_input", "label_code")} />
            {
              msgRes &&
              <View style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center', marginHorizontal: 17, marginBottom: 10 }}>
                <LibIcon name="check-circle" color={MarketStyle.colorGreen} size={16} />
                <Text allowFontScaling={false} style={{ marginLeft: 10, color: MarketStyle.colorGreen }}>{msgRes}</Text>
              </View>
            }
            {
              msgError &&
              <View style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center', marginHorizontal: 17, marginBottom: 10 }}>
                <LibIcon name="close-circle" color={LibStyle.colorRed} size={16} />
                <Text allowFontScaling={false} style={{ marginLeft: 10, color: LibStyle.colorRed }}>{msgError}</Text>
              </View>
            }

            <MarketInput_select
              value={startDate}
              onPress={() => {
                dialogDate.current!.show()
                dialogTime.current!.hide()
                setWhatDate("start")
              }} label={esp.lang("market/merchant_voucher_input", "label_date_start")} placeholder={esp.lang("market/merchant_voucher_input", "date_start")} mandatory />

            <MarketInput_select
              value={startTime}
              onPress={() => {
                dialogDate.current!.hide()
                dialogTime.current!.show()
                setWhatTime("start")
              }} label={esp.lang("market/merchant_voucher_input", "label_time_start")} placeholder={esp.lang("market/merchant_voucher_input", "time_start")} mandatory />

            <MarketInput_select
              value={endDate}
              onPress={() => {
                dialogDate.current!.show()
                dialogTime.current!.hide()
                setWhatDate("end")
              }} label={esp.lang("market/merchant_voucher_input", "label_date_end")} placeholder={esp.lang("market/merchant_voucher_input", "date_end")} mandatory />

            <MarketInput_select
              value={endTime}
              onPress={() => {
                dialogDate.current!.hide()
                dialogTime.current!.show()
                setWhatTime("end")
              }} label={esp.lang("market/merchant_voucher_input", "label_time_end")} placeholder={esp.lang("market/merchant_voucher_input", "time_end")} mandatory />


          </View>
          <View style={{ backgroundColor: '#fff', marginTop: 10, paddingTop: 4, paddingBottom: 5 }}>
            <MarketInput_square
              _ref={inputClaim}
              keyboardType="numeric"
              maxLength={5}
              mask="#####"
              onChangeText={() => { }}
              placeholder={esp.lang("market/merchant_voucher_input", "kuota")}
              label={esp.lang("market/merchant_voucher_input", "label_kuota")}
              mandatory
            />

            <MarketInput_select onPress={() => {
              LibNavigation.navigateForResult('market/merchant_voucher_type_disc', { disc: discType }).then((item: any) => {
                setDiscType(item)
              })
            }}
              mandatory label={esp.lang("market/merchant_voucher_input", "label_type")} placeholder={esp.lang("market/merchant_voucher_input", "type")} value={discType ? discType.title : ""} />

            <MarketInput_square _ref={inputMinOrder} mask={"###.###.###.###.###"} maskFrom="end" keyboardType={"phone-pad"} mandatory onChangeText={() => { }} placeholder={esp.lang("market/merchant_voucher_input", "min")} label={esp.lang("market/merchant_voucher_input", "label_min")} />

            <View style={{ margin: 15, flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
              <View style={{ flex: 1, marginRight: 10 }} >
                <MarketInput_label label={esp.lang("market/merchant_voucher_input", "show_voucher")} />
                <Text allowFontScaling={false} style={{ marginTop: 5, fontSize: 11, fontFamily: 'Arial', fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, lineHeight: 18, color: '#949494' }} >{esp.lang("market/merchant_voucher_input", "show_info")}</Text>
              </View>
              <MarketToggle onChangeValue={() => {
                setShowVoucher(showVoucher ? false : true)
              }} type="success" value={showVoucher} />
            </View>
            {
              voucherType?.id == 2 &&
              <MarketInput_select onPress={() => {
                LibNavigation.navigateForResult('market/merchant_voucher_product', { voucher_id: resultVoucher ? resultVoucher?.id : "0" }, 120).then((item: any) => {
                  setSelectedProduct(item)
                })
              }} label={esp.lang("market/merchant_voucher_input", "available")} mandatory placeholder={esp.lang("market/merchant_voucher_input", "select_product")} value={selectedProduct ? selectedProduct?.length + esp.lang("market/merchant_voucher_input", "product") : ""} />
            }

          </View>
        </ScrollView>
        <View style={{ padding: 10, backgroundColor: '#fff' }}>
          <MarketButton onPress={() => {
            if (checkInput()) {
              if (url) {
                editVoucher()
              } else {
                addVoucher()
              }
            }

          }} text={esp.lang("market/merchant_voucher_input", "btn_save")} />
        </View>

        <LibSlidingup ref={dialogTypeVoucher}>
          <View style={{ backgroundColor: '#fff', borderTopRightRadius: 20, borderTopLeftRadius: 20, paddingBottom: 35, paddingHorizontal: 19, }}>
            <Text allowFontScaling={false} style={{ marginTop: 26, marginBottom: 23, fontSize: 16, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, textAlign: "center", color: "#34495e" }}>{esp.lang("market/merchant_voucher_input", "select_type_voucher")}</Text>
            {
              _voucherType.map((item: any, i: number) => {
                return (
                  <TouchableOpacity key={i} onPress={() => {
                    setVoucherType(item)
                    dialogTypeVoucher.current!.hide()
                  }}
                    style={{ marginBottom: 10, alignItems: 'center', paddingLeft: 10, padding: 10, borderRadius: 5, alignContent: 'center', justifyContent: 'center', backgroundColor: '#f6f6f6' }} >
                    <Text allowFontScaling={false} style={{ fontSize: 16, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4b4b4b" }}>{item.title}</Text>
                    <Text allowFontScaling={false} style={{ marginTop: 4, fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#c9c9c9" }}>{item.subtitle}</Text>
                  </TouchableOpacity>
                )
              })
            }
          </View>
        </LibSlidingup>

        {/* dialog date */}
        <LibSlidingup ref={dialogDate}>
          <View style={{ backgroundColor: "white", paddingVertical: 10 }} >
            <LibTextstyle textStyle="headline" text={esp.lang("market/merchant_voucher_input", "select_date")} style={{ textAlign: 'center', paddingBottom: 10 }} />
            <MarketSection_menu size="line" />
            <View style={{ height: LibStyle.height / 4 }}>
              <LibDatepicker
                minDate={date}
                maxDate={moment().add(10, 'years').localeFormat('YYYY-MM-DD')}
                onDateChange={(dt: any) => {
                  if (whatDate == 'start') {
                    setDate(dt)
                    dialogDate.current!.hide()
                    setStartDate(moment(dt).localeFormat("YYYY-MM-DD"))
                  } else if (whatDate == 'end') {
                    setEndDate(moment(dt).localeFormat("YYYY-MM-DD"))
                    dialogDate.current!.hide()
                  }
                }}
                selectedDate={date}
              />
            </View>
          </View>
        </LibSlidingup>

        {/* show time picker */}
        {
          <LibSlidingup ref={dialogTime}>
            <View style={{ backgroundColor: "white", paddingVertical: 10 }} >
              <LibTextstyle textStyle="headline" text={esp.lang("market/merchant_voucher_input", "select_time")} style={{ textAlign: 'center', paddingBottom: 10 }} />
              <MarketSection_menu size="line" />
              <View style={{ height: LibStyle.height / 4 }}>
                <MarketTime_picker
                  onTimeChange={(time: any) => {
                    esp.log(time, "time");
                    if (whatTime == 'start') {
                      dialogTime.current!.hide()
                      setStartTime(time.substr(0, time.length - 3))
                    } else if (whatTime == 'end') {
                      dialogTime.current!.hide()
                      setEndTime(time.substr(0, time.length - 3))
                    }
                  }}
                  selectedTime='00:00:00'
                  type='hourMinute'
                />
              </View>
            </View>
          </LibSlidingup>
        }
        <MarketImage_picker
          _ref={imagePicker}
          option={{ crop: { ratio: "3:1", forceCrop: true, message: '' } }}
          onFinish={(x) => {
            setImage(x)
          }} />
      </LibKeyboard_avoid>
    </View>
  )
}