// 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 { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import { LibWebview } from 'esoftplay/cache/lib/webview/import';
import { MarketButton } from 'esoftplay/cache/market/button/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketInput_square } from 'esoftplay/cache/market/input_square/import';
import { MarketSlidingupProperty } from 'esoftplay/cache/market/slidingup/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';
import { MarketTime } from 'esoftplay/cache/market/time/import';
import esp from 'esoftplay/esp';

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

moment().locale('id')


export interface MarketMerchant_sending_methodArgs {
  order_id: string,
  shipping_label: string,
  shipping_code: string
  from?: string
}
export interface MarketMerchant_sending_methodProps {

}
export default function m(props: MarketMerchant_sending_methodProps): any {
  const { order_id, shipping_label, shipping_code, from } = LibNavigation.getArgsAll<any>(props)
  const resiInput = useRef<MarketInput_square>(null)
  const timeSliding = useRef<LibSlidingup>(null)
  const [data, setData] = useSafeState<any>()
  const [selected, setSelected] = useSafeState<any>({})
  const [date, setDate] = useSafeState<any>(moment().localeFormat('YYYY-MM-DD'))
  const [time, setTime] = useSafeState<string>(moment().localeFormat('HH:mm'))

  useEffect(() => {
    checkSendingMethod(order_id)
  }, [])

  function showDatePicker() {
    MarketSlidingupProperty.add(
      <View style={{ backgroundColor: "white", paddingVertical: 15, paddingHorizontal: 17, borderTopRightRadius: 15, borderTopLeftRadius: 15 }} >
        <View style={{ backgroundColor: 'white', paddingBottom: 25, height: 230 }}>
          <LibDatepicker
            minDate={moment().localeFormat('YYYY-MM-DD')}
            maxDate={moment().add(1, 'days').localeFormat('YYYY-MM-DD')}
            onDateChange={(date) => {
              setDate(date)
              MarketSlidingupProperty.hide()
            }}
            selectedDate={date}
          />
        </View>
      </View>
    )
    MarketSlidingupProperty.show()
  }

  function checkSendingMethod(order_id: string) {
    new LibCurl('shop/order_merchant_detail_sending_method/' + order_id, null,
      (res, msg) => {
        setData(res)
      }, (msg) => {
        LibDialog.warning(esp.lang("market/merchant_sending_method", "check_failed"), msg?.message)
      }, 1
    )
  }

  function send() {
    if (selected.cashless == 0 && (resiInput.current?.getText() == '')) {
      Alert.alert(esp.lang("market/merchant_sending_method", "alert_title"), esp.lang("market/merchant_sending_method", "alert_msg"))
      return
    }

    const dateTime = date + ' ' + time
    let post = {
      method: selected.id,
      resi: resiInput?.current?.getText() || "",
      pickup_schedule: selected.pickup_schedule == 1 ? dateTime : ''
    }

    LibProgress.show(esp.lang("market/merchant_sending_method", "send_wait"))
    new LibCurl('shop/order_merchant_detail_sending/' + order_id, post,
      (res, msg) => {
        LibProgress.hide()
        LibDialog.info(esp.lang("market/merchant_sending_method", "send_ok"), res)
        if (shipping_code == 'gosend') {
          LibNavigation.back(2)
          LibNavigation.navigate('market/merchant_sending_method_find_driver', { order_id: order_id, shipping_code: shipping_code, shipping_label })
        } else if (from == 'market/merchant_resending') {
          LibNavigation.backToRoot()
          LibNavigation.navigate('market/order_detail_label_print', { url: shipping_label })
        } else {
          LibNavigation.backToRoot()
          LibNavigation.navigate('market/merchant_order', { status: 4 })
          LibNavigation.navigate('market/order_detail_label_print', { url: shipping_label })
        }
      }, (msg) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("market/merchant_sending_method", "send_failed"), msg?.message)
      }, 1
    )
  }

  return (
    <View style={{ flex: 1 }} >
      <MarketHeader
        leftIcon={{ name: "close", onPress: () => LibNavigation.back() }}
        title={esp.lang("market/merchant_sending_method", "header_title")}
      />

      {
        !data ? <LibLoading /> :
          <>
            <ScrollView >
              {
                data.map((item: any, i: number) => (
                  <View key={i} style={{ marginHorizontal: 20 }} >
                    <View style={{ borderBottomWidth: 0.5, borderBottomColor: '#e6e6e6', marginHorizontal: -20, paddingBottom: 15, paddingTop: 10, backgroundColor: item.id == selected.id ? '#e6e6e6' : 'white' }} >
                      <TouchableOpacity onPress={() => { setSelected(item) }} style={{ flexDirection: 'row', marginHorizontal: 20 }} >
                        <LibPicture source={{ uri: item.img }} style={{ width: 40, height: 40 }} />
                        <View style={{ flex: 1, marginLeft: 15 }} >
                          <Text allowFontScaling={false} style={{ fontFamily: 'Arial', fontSize: 14 }}>{item.title}</Text>
                          <Text allowFontScaling={false} style={{ fontFamily: 'Arial', fontSize: 12, marginTop: 5 }}>{item.info}</Text>
                        </View>
                        <LibIcon name={item.id == selected.id ? 'checkbox-marked-circle-outline' : 'checkbox-blank-circle-outline'} color={item.id == selected.id ? MarketStyle.colorGreen : '#d1d1d1'} size={24} />
                      </TouchableOpacity>
                    </View>
                    {
                      item.id == selected.id &&
                      <>
                        <LibWebview
                          source={{ html: item.instruction }}
                          onFinishLoad={() => { }}
                          style={{ marginTop: 10, marginHorizontal: -20 }} />
                        {
                          item.pickup_schedule == 1 &&
                          <View style={{ marginTop: -20 }} >
                            <View style={{ paddingVertical: 8, marginHorizontal: -20, borderBottomWidth: 0.5, borderBottomColor: '#e6e6e6', borderTopWidth: 0.5, borderTopColor: '#e6e6e6' }} >
                              <View style={{ flexDirection: 'row', alignItems: 'center', marginHorizontal: 20 }} >
                                <Text allowFontScaling={false} style={{ flex: 1, fontFamily: 'Arial', fontSize: 14 }}>{esp.lang("market/merchant_sending_method", "pickup_date")}</Text>
                                <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }} onPress={() => { showDatePicker() }} >
                                  <Text allowFontScaling={false} style={{ fontFamily: 'Arial', fontSize: 14 }}>{date}</Text>
                                  <LibIcon name='chevron-right' />
                                </TouchableOpacity>
                              </View>
                            </View>
                            <View style={{ paddingVertical: 8, marginHorizontal: -20, borderBottomWidth: 0.5, borderBottomColor: '#e6e6e6' }} >
                              <View style={{ flexDirection: 'row', alignItems: 'center', marginHorizontal: 20 }} >
                                <Text allowFontScaling={false} style={{ flex: 1, fontFamily: 'Arial', fontSize: 14 }}>{esp.lang("market/merchant_sending_method", "pickup_time")}</Text>
                                <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }} onPress={() => { timeSliding.current?.show() }} >
                                  <Text allowFontScaling={false} style={{ fontFamily: 'Arial', fontSize: 14 }}>{time == '' ? esp.lang("market/merchant_sending_method", "select_time") : time}</Text>
                                  <LibIcon name='chevron-right' />
                                </TouchableOpacity>
                              </View>
                            </View>
                          </View>
                        }
                        {
                          item.cashless == 0 &&
                          <View style={{ marginTop: -20, marginHorizontal: -15 }} >
                            <MarketInput_square
                              ref={resiInput}
                              placeholder={esp.lang("market/merchant_sending_method", "input_waybill")}
                              autoCapitalize={"characters"}
                              style={{ fontSize: 24, textAlign: 'center' }}
                              multiline
                              onChangeText={(x) => { }} />
                            <Text allowFontScaling={false} style={{ marginHorizontal: 18, fontFamily: 'Arial', fontSize: 12 }} >{esp.lang("market/merchant_sending_method", "order_info")}</Text>
                          </View>
                        }
                      </>
                    }
                    <View style={{ borderBottomWidth: 0.5, borderBottomColor: '#e6e6e6', marginHorizontal: -20, paddingBottom: 15 }} >
                      <Text allowFontScaling={false} style={{ fontFamily: 'Arial', fontSize: 12, marginTop: 15, marginHorizontal: 20 }}>{item.description}</Text>
                    </View>
                  </View>
                ))
              }
            </ScrollView>
            {
              selected.id &&
              <MarketButton textStyle={{ color: "white" }} text={esp.lang("market/merchant_sending_method", "btn_confirm")} onPress={() => {
                send()
              }}
                buttonStyle={{ marginHorizontal: 10, marginBottom: 15, marginTop: 10 }}
              />
            }
          </>
      }
      <LibSlidingup ref={timeSliding} >
        <View style={{ backgroundColor: "white", paddingVertical: 15, paddingHorizontal: 17, borderTopRightRadius: 15, borderTopLeftRadius: 15 }} >
          <View style={{ backgroundColor: 'white', paddingBottom: 25, height: 230 }}>
            <MarketTime
              onTimeChange={(time) => {
                setTime(time)
                timeSliding.current?.hide()
              }}
            />
          </View>
        </View>
      </LibSlidingup>
    </View>
  )
}