// 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 { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibScroll } from 'esoftplay/cache/lib/scroll/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 { MarketEmpty } from 'esoftplay/cache/market/empty/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketInput_square } from 'esoftplay/cache/market/input_square/import';
import { MarketMerchant_profileProperty } from 'esoftplay/cache/market/merchant_profile/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';
import { MarketToggle } from 'esoftplay/cache/market/toggle/import';
import esp from 'esoftplay/esp';

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

moment().locale('id')

export interface MarketMerchant_closeProps {

}

export interface Item extends MarketMerchant_closeProps {
  id: string,
  sale_id: string,
  merchant_id: string,
  invoice_merchant: string,
  created: string,
  price: string,
  total: string,
  updated: string,
  status: string,
  status_title: string,
  url_detail: string,
}

function Item(props: Item) {
  return (
    <TouchableOpacity activeOpacity={1} onPress={() => { LibNavigation.navigate('market/order_detail', { url: props.url_detail }) }} style={[{ borderRadius: 4, backgroundColor: "#fff", padding: 15, marginBottom: 8 }, LibStyle.elevation(2)]}>
      <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
        <Text allowFontScaling={false} style={{ fontFamily: "SFProText", fontSize: 10, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4b4b4b" }} >{props.invoice_merchant}</Text>
        <Text allowFontScaling={false} style={{ fontFamily: "SFProText", fontSize: 10, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4b4b4b" }} >{moment(props.updated).localeFormat('DD/MM/YYYY HH:mm')}</Text>
      </View>
      <View style={{ flexDirection: 'row', marginTop: 10 }} >
        <Text allowFontScaling={false} style={{ fontFamily: "SFProText", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4b4b4b" }} >{esp.lang("market/merchant_close", "total_order")}</Text>
        <Text allowFontScaling={false} style={{ fontFamily: "SFProText", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4b4b4b" }} >{LibUtils.money(props.total)}</Text>
      </View>
      <View style={{ flexDirection: 'row', marginTop: 5 }} >
        <View style={{ padding: 5, paddingHorizontal: 15, borderRadius: 15, backgroundColor: '#fff3cd' }} >
          <Text allowFontScaling={false} style={{ fontFamily: "SFProText", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4b4b4b" }} >{props.status_title}</Text>
        </View>
      </View>
    </TouchableOpacity>
  )
}

export default function m(props: MarketMerchant_closeProps): any {
  const [isClose, setIsClose] = useSafeState(false)
  const [data, setData] = MarketMerchant_profileProperty.profileState().useState()
  const [text, setText] = useSafeState("")
  const [orderDependents, setOrderDependents] = useSafeState<any>()

  const [selectOpt, setSelectOpt] = useSafeState(1)
  const [openAt, setOpenAt] = useSafeState()
  const [closeAt, setCloseAt] = useSafeState()

  const slidingSetOpenAt = useRef<LibSlidingup>(null)
  const slidingSetCloseAt = useRef<LibSlidingup>(null)

  let opt = [
    {
      id: 1,
      title: esp.lang("market/merchant_close", "open_merchant"),
      open_at: 0,
      close_at: 0
    },
    {
      id: 3,
      title: esp.lang("market/merchant_close", "close_now"),
      open_at: 1,
      close_at: 0
    },
    {
      id: 2,
      title: esp.lang("market/merchant_close", "close_later"),
      open_at: 1,
      close_at: 1
    },
  ]

  useEffect(() => {
    getOrderDependents()
    MarketMerchant_profileProperty.update(data => {
      setData(data)
      setIsClose(data.status != 1)
      setText(data?.closed_notes || '')
      setSelectOpt(data.closed_status)
      setOpenAt(data.opened_at != '0' ? data.opened_at : moment().add(1, 'days').localeFormat('YYYY-MM-DD'))
      setCloseAt(data.closed_at != '0' ? data.closed_at : moment().add(1, 'days').localeFormat('YYYY-MM-DD'))
    })
  }, [])

  function getOrderDependents() {
    new LibCurl('shop/order_merchant_dependent', null,
      (res, msg) => {
        setOrderDependents(res)
      }, () => { }, 1)
  }

  function doClose() {
    if (esp.isDebug("") && orderDependents?.list?.length > 0) {
      Keyboard.dismiss()
      LibToastProperty.show(esp.lang("market/merchant_close", "order_available"))
      return
    }
    if (text.trim() == '') {
      Keyboard.dismiss()
      LibToastProperty.show(esp.lang("market/merchant_close", "empty_msg"))
      return
    }
    LibDialog.warningConfirm(esp.lang("market/merchant_close", "close_title"), esp.lang("market/merchant_close", "close_msg"), esp.lang("market/merchant_close", "close_confirm"), () => {
      LibProgress.show()
      new LibCurl("shop/merchant_close", { notes: text },
        (res, msg) => {
          LibProgress.hide()
          setIsClose(true)
          MarketMerchant_profileProperty.update(setData)
        },
        (msg) => {
          LibProgress.hide()
        }, 1
      )
    }, esp.lang("market/merchant_close", "close_cancel"), () => { })
  }

  function doOpen() {
    LibProgress.show()
    new LibCurl("shop/merchant_open", null,
      (res, msg) => {
        LibDialog.info(esp.lang("market/merchant_close", "open_ok"), res)
        LibProgress.hide()
        setIsClose(false)
        MarketMerchant_profileProperty.update(setData)
      },
      (msg) => {
        LibProgress.hide()
      }, 1
    )
  }

  function closeMerchant() {

    if (selectOpt != 1) {
      let post = {
        notes: text,
        opened_at: openAt,
        closed_at: closeAt
      }

      if (selectOpt == 3) {
        delete post.closed_at
      }

      LibDialog.warningConfirm(esp.lang("market/merchant_close", "merchant_close_title"), esp.lang("market/merchant_close", "merchant_close_msg"), esp.lang("market/merchant_close", "merchant_close_confirm"), () => {
        LibProgress.show()
        new LibCurl("shop/merchant_close", post,
          (res, msg) => {
            LibProgress.hide()
            LibDialog.info(esp.lang("market/merchant_close", "merchant_close_ok"), msg)
            MarketMerchant_profileProperty.update(setData)
            setText(data?.closed_notes || '')
            setOpenAt(data.opened_at != '0' ? data.opened_at : moment().add(1, 'days').localeFormat('YYYY-MM-DD'))
            setCloseAt(data.closed_at != '0' ? data.closed_at : moment().add(1, 'days').localeFormat('YYYY-MM-DD'))
          },
          (msg) => {
            LibProgress.hide()
          }, 1
        )
      }, esp.lang("market/merchant_close", "merchant_close_cancel"), () => { })

    } else {
      doOpen()
    }


  }

  function cancelAll() {
    LibDialog.warningConfirm(esp.lang("market/merchant_close", "cancel_title"), esp.lang("market/merchant_close", "cancel_msg"), esp.lang("market/merchant_close", "cancel_confirm"),
      () => {
        LibProgress.show(esp.lang("market/merchant_close", "cancel_wait"))
        new LibCurl('shop/order_merchant_dependent_cancel', null,
          (res, msg) => {
            LibProgress.hide()
            getOrderDependents()
            MarketMerchant_profileProperty.update(data => {
              setData(data)
              setIsClose(data.status != 1)
            })
          }, (msg) => {
            LibProgress.hide()
            LibToastProperty.show(msg?.message)
          }, 1)
      }, esp.lang("market/merchant_close", "cancel_cancel"), () => {

      })
  }

  return (
    <View style={{ flex: 1 }} >
      <MarketHeader
        onlyBack
        title={esp.lang("market/merchant_close", "header_title")}
        subtitle={esp.lang("market/merchant_close", "header_subtitle")} />
      {
        !data ?
          <LibLoading /> :
          typeof data == 'string' ?
            <MarketEmpty msg={data} />
            :
            <>
              <LibScroll>
                {
                  esp.isDebug("") && orderDependents?.list?.length > 0 &&
                  <>
                    <View style={{ flexDirection: 'row', backgroundColor: '#FEFBEB', borderColor: "#FFCC29", borderRadius: 1, borderWidth: 1, borderStyle: 'dashed', alignContent: 'center', alignItems: 'center', flex: 1, padding: 12, paddingHorizontal: 15 }}>
                      <Text allowFontScaling={false} style={{ flex: 1, fontFamily: "Arial", fontSize: 12, fontStyle: "normal", letterSpacing: 0 }} >{esp.lang("market/merchant_close", "close_info")}</Text>
                      {
                        orderDependents?.is_cancelable == 1 &&
                        <TouchableOpacity onPress={cancelAll} style={{ marginLeft: 10, padding: 10, backgroundColor: LibStyle.colorRed, borderRadius: 25, paddingVertical: 5 }}>
                          <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: "#fff" }}>{esp.lang("market/merchant_close", "cancel_all")}</Text>
                        </TouchableOpacity>
                      }
                    </View>
                    <View style={{ paddingHorizontal: 17, borderBottomWidth: 1, borderBottomColor: "#eee", paddingBottom: 10 }}>
                      <Text allowFontScaling={false} style={{ marginVertical: 10, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: "#34495e" }}>{esp.lang("market/merchant_close", "order_in_progress")}</Text>
                      {
                        orderDependents?.list?.map((item: any, i: number) => {
                          return (
                            <Item key={i} {...item} />
                          )
                        })
                      }
                      {
                        orderDependents?.list?.length == 5 &&
                        <TouchableOpacity onPress={() => { LibNavigation.navigate('market/merchant_order_dependent', { url: orderDependents?.url_list }) }}>
                          <View style={{ marginVertical: 8, justifyContent: 'center', alignSelf: 'center', width: 104, height: 23, borderRadius: 11.5, backgroundColor: "#fff", borderStyle: "solid", borderWidth: 1, borderColor: "#e1e1e1" }}>
                            <Text allowFontScaling={false} style={{ alignSelf: 'center', textAlign: 'center', fontFamily: "Arial", fontSize: 11, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#9b9b9b" }}>{esp.lang("market/merchant_close", "show_all")}</Text>
                          </View>
                        </TouchableOpacity>
                      }
                    </View>
                  </>
                }

                <View style={{ marginHorizontal: 17, marginVertical: 10 }} >
                  <LibTextstyle text={esp.lang("market/merchant_close", "close_merchant")} textStyle="body" />
                  <LibTextstyle
                    textStyle="caption1"
                    style={{ color: "#888", marginTop: 5 }}
                    text={esp.lang("market/merchant_close", "merchant_close_info")} />
                </View>
                {
                  esp.isDebug("") && opt.map((x: any, i: number) => {
                    return (
                      <View key={i} style={{ paddingHorizontal: 17 }} >
                        <TouchableOpacity onPress={() => {
                          setSelectOpt(x.id)
                        }} style={{ flexDirection: 'row', alignItems: 'center', marginTop: 5 }} >
                          <LibIcon name={x.id == selectOpt ? 'radiobox-marked' : 'radiobox-blank'} style={{ marginRight: 10 }} color={'#707070'} />
                          <Text>{x.title}</Text>
                        </TouchableOpacity>
                        {
                          x.id == selectOpt &&
                          <>
                            {
                              x.close_at == 1 &&
                              <View style={{ flexDirection: 'row', alignItems: 'center', marginVertical: 5, marginLeft: 30, backgroundColor: 'white', padding: 10, borderRadius: 6, ...LibStyle.elevation(2) }} >
                                <LibIcon name='calendar-range-outline' size={30} color={MarketStyle.colorPrimaryMarket} />
                                <TouchableOpacity onPress={() => { slidingSetCloseAt?.current?.show() }} style={{ marginLeft: 10, flex: 1 }} >
                                  <LibTextstyle
                                    style={{ color: "#888" }}
                                    textStyle="caption2"
                                    text={esp.lang("market/merchant_close", "close_date")} />
                                  <Text allowFontScaling={false} style={{ marginTop: 5, fontFamily: 'Arial', fontSize: 14 }} >{moment(closeAt).localeFormat('dddd, DD MMMM YYYY')}</Text>
                                </TouchableOpacity>
                                <LibIcon name='chevron-right-circle-outline' color={MarketStyle.colorPrimaryMarket} />
                              </View>

                            }
                            {
                              x.open_at == 1 &&
                              <View style={{ flexDirection: 'row', alignItems: 'center', marginVertical: 5, marginLeft: 30, backgroundColor: 'white', padding: 10, borderRadius: 6, ...LibStyle.elevation(2) }} >
                                <LibIcon name='calendar-range-outline' size={30} color={MarketStyle.colorPrimaryMarket} />
                                <TouchableOpacity onPress={() => { slidingSetOpenAt?.current?.show() }} style={{ marginLeft: 10, flex: 1 }} >
                                  <LibTextstyle
                                    style={{ color: "#888" }}
                                    textStyle="caption2"
                                    text={esp.lang("market/merchant_close", "open_date")} />
                                  <Text allowFontScaling={false} style={{ marginTop: 5, fontFamily: 'Arial', fontSize: 14 }} >{moment(openAt).localeFormat('dddd, DD MMMM YYYY')}</Text>
                                </TouchableOpacity>
                                <LibIcon name='chevron-right-circle-outline' color={MarketStyle.colorPrimaryMarket} />
                              </View>
                            }
                          </>
                        }
                      </View>
                    )
                  })
                }
                <View style={{ marginTop: 20, marginBottom: 10, height: 1, backgroundColor: '#eee' }} />

                {
                  esp.isDebug("") && selectOpt != 1 &&
                  <>
                    <MarketInput_square
                      onChangeText={setText}
                      label={esp.lang("market/merchant_close", "msg_close_merchant")}
                      defaultValue={data?.closed_notes}
                      containerStyle={{ marginTop: 10, opacity: isClose ? 0.2 : 1 }}
                      style={{ height: 100, textAlignVertical: "top" }}
                      multiline
                      placeholder={esp.lang("market/merchant_close", "msg_close_merchant_info")}
                    />
                    <LibTextstyle
                      style={{ paddingHorizontal: 17, color: "#888" }}
                      textStyle="caption2"
                      text={esp.lang("market/merchant_close", "msg_close_merchant_info1")} />
                  </>
                }
                {
                  !esp.isDebug("") &&
                  <>
                    <MarketInput_square
                      onChangeText={setText}
                      label={esp.lang("market/merchant_close", "label_close_merchant")}
                      editable={!isClose}
                      defaultValue={data?.closed_notes}
                      containerStyle={{ marginTop: 10, opacity: isClose ? 0.2 : 1 }}
                      style={{ height: 100, textAlignVertical: "top" }}
                      multiline
                      placeholder={esp.lang("market/merchant_close", "placeholder_close_merchant")}
                    />
                    <LibTextstyle
                      style={{ paddingHorizontal: 17, color: "#888" }}
                      textStyle="caption2"
                      text={esp.lang("market/merchant_close", "msg_close_merchant_info2")} />
                  </>
                }
                {
                  !esp.isDebug("") &&
                  <TouchableOpacity
                    onPress={() => isClose ? doOpen() : doClose()}
                    style={{ paddingHorizontal: 17, paddingVertical: 10, flexDirection: "row", alignItems: "center", marginTop: 24, borderTopWidth: 1, borderTopColor: "#eee" }} >
                    <View style={{ flex: 1 }} >
                      <LibTextstyle text={esp.lang("market/merchant_close", "close")} textStyle="body" />
                      <LibTextstyle
                        textStyle="caption1"
                        style={{ color: "#888", marginTop: 5 }}
                        text={esp.lang("market/merchant_close", "info_for_buyer")} />
                    </View>
                    <MarketToggle type="danger" value={isClose} onChangeValue={() => isClose ? doOpen() : doClose()} />
                  </TouchableOpacity>
                }
              </LibScroll>
              {
                esp.isDebug("") &&
                <View pointerEvents={(text.trim() == '' && selectOpt != 1) ? 'none' : 'auto'} style={{ margin: 10, marginHorizontal: 15, backgroundColor: "white" }} >
                  <MarketButton onPress={() => { closeMerchant() }} text={esp.lang("market/merchant_close", "btn_save")} colorBackground={(text.trim() == '' && selectOpt != 1) ? '#aaa' : undefined} />
                </View>
              }
            </>
      }

      <LibSlidingup ref={slidingSetOpenAt}>
        <View style={{ backgroundColor: 'white', paddingBottom: 25, height: 230 }}>
          <LibDatepicker
            maxDate={moment().add(80, 'years').localeFormat('YYYY-MM-DD')}
            minDate={closeAt || moment().localeFormat('YYYY-MM-DD')}
            onDateChange={(date) => {
              setOpenAt(date)
              slidingSetOpenAt.current?.hide()
            }}
            selectedDate={openAt || moment().localeFormat('YYYY-MM-DD')}
          />

        </View>
      </LibSlidingup>

      <LibSlidingup ref={slidingSetCloseAt}>
        <View style={{ backgroundColor: 'white', paddingBottom: 25, height: 230 }}>
          <LibDatepicker
            maxDate={moment().add(80, 'years').localeFormat('YYYY-MM-DD')}
            minDate={moment().localeFormat('YYYY-MM-DD')}
            onDateChange={(date) => {
              setCloseAt(date)
              slidingSetCloseAt.current?.hide()
            }}
            selectedDate={closeAt || moment().localeFormat('YYYY-MM-DD')}
          />

        </View>
      </LibSlidingup>

    </View >
  )
}