// withHooks
// noPage
import { LibEditbox } from 'esoftplay/cache/lib/editbox/import';

import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import { useTimeout } from 'esoftplay/timeout';

import React, { useEffect, useMemo, useRef } from 'react';
import { Text, View } from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';

export interface MarketCheckout_itemProps {
  bill: number,
  bill_qty: number,
  merchant: any,
  products: any,
  shipping_address: any,
  onChageDisabled: (disabled: boolean) => void,
  onChangeShipping: (id: number, data: any) => void
  changeNotes: (idx: number, cart_id: number, qty: number, notes: string) => void
}

function getLowestPrice(shipping: any[]) {
  let out: any = {}
  let minPrice = 999999999
  shipping.map((row) => {
    if (row.price < minPrice) {
      minPrice = row.price
      out = row
    }
  })
  return out
}

let idx = 0
function buildArrayShipping(shipping: any[]): any[] {
  let arr: any = []
  shipping && Object.values(shipping).forEach((item: any) => {
    item && Array.isArray(item.list) && item.list.forEach((row: any) => {
      let out: any = {}
      if (Number(row.shipping_cost) > 0) {
        idx++
        out.id = idx
        out.code = item.code
        out.courier_id = item.id
        out.cod = row.cod
        out.cod_fee = Number(row.cod_fee)
        out.cod_fee_insurance = Number(row.cod_fee_insurance)
        out.insurance = row.insurance
        out.insurance_fee = Number(row.insurance_fee)
        out.insurance_req = row.insurance_req
        out.estimate = row.estimate_day
        out.service = row.service
        out.service_code = row.service_code
        out.price = Number(row.shipping_cost)
        arr.push(out)
      }
    });
  })
  return arr
}

function renderEstimateTime(estimate: string) {
  let est = estimate.toLowerCase()
  let _est = ''
  if (est.includes(' hari')) {
    _est = '(' + est.replace(' hari', '') + ' Hari)'
  } else if (est.includes(' jam')) {
    _est = '(' + est.replace(' jam', '') + ' Jam)'
  } else {
    _est = est
  }
  return _est
}

export default function m(props: MarketCheckout_itemProps): any {
  const { bill, bill_qty, merchant, products } = props
  let shippingArray = useRef<any[]>([]).current
  shippingArray = useMemo(() => buildArrayShipping(merchant.shipping), [merchant])
  const [shipping, setShipping] = useSafeState(getLowestPrice(shippingArray))
  const [hasDisabled, setHasDisabled] = useSafeState(false)
  const [insurance, setInsurance] = useSafeState(shipping?.insurance_req == 1 ? true : false)
  const timeout = useTimeout()

  let newProduct = Object.values(products).map((variant: any) => Object.values(variant))
  const newProducts = newProduct.reduce((acc, val) => acc.concat(val), []).map((val: any) => ({ ...val }))

  useEffect(() => {
    props.onChageDisabled(false)
    setShipping(getLowestPrice(shippingArray))
  }, [merchant])

  useEffect(() => {
    timeout(() => {
      props.onChangeShipping(
        merchant.id,
        {
          merchant_id: merchant.id,
          courier_id: shipping.courier_id,
          code: shipping.code,
          service_code: shipping.service_code,
          price: shipping.price,
          cod: shipping.cod,
          cod_fee: shipping.cod_fee,
          cod_fee_insurance: insurance ? shipping.cod_fee_insurance : 0,
          insurance: insurance ? 1 : 0,
          insurance_fee: insurance ? shipping.insurance_fee : 0
        }
      )
    }, 100);
  }, [shipping, insurance, hasDisabled])


  // esp.log(/* "shipping", shipping, merchant, */ "shippingArray", shippingArray);
  return (
    <>
      <View style={styleId_Z27zEN} />
      <View>
        <View style={styleId_Z20r5tY}>
          <LibPicture source={{ uri: merchant?.image }} style={styleId_1asTLy} resizeMode="cover" />
          <View style={styleId_ZkwSed}>
            <Text allowFontScaling={false} style={styleId_Z1dSilI}>{merchant?.title}</Text>
            <View style={styleId_Z2kirXg}>
              <LibIcon name="map-marker" size={12} color="#d1d1d1" />
              <Text allowFontScaling={false} style={styleId_Z163Hi1}>{merchant?.location_name}</Text>
            </View>
          </View>
        </View>
        {
          // Object.values(products).map((product: any) => (
          newProducts.map((product: any, i: number) => {
            const isDisabled = !product?.couriers?.includes(shipping?.code?.toLowerCase())
            if (isDisabled) {
              props.onChageDisabled(isDisabled)
            }
            return (
              <>
                <View key={i} style={styleId_1xsTFo}>
                  <LibPicture source={{ uri: product?.image }} style={styleId_2wNvzO} resizeMode="cover" />
                  <View style={{ marginLeft: 15, flex: 2 }}>
                    <Text allowFontScaling={false} numberOfLines={2} style={[styleId_Z17LdUb, { opacity: isDisabled ? 0.4 : 1 }]}>{product?.title}</Text>
                    {
                      product?.price_name != '' &&
                      <View style={[styleId_17srzJ, { opacity: isDisabled ? 0.4 : 1 }]} >
                        <LibTextstyle text={product?.price_name} textStyle="caption2" style={styleId_1rgcuB} />
                      </View>
                    }
                    <View style={[styleId_1fmvBo, { opacity: isDisabled ? 0.4 : 1 }]} >
                      <Text allowFontScaling={false} style={styleId_Z77xH9}>{product?.qty + 'x '}</Text>
                      {
                        Number(product?.sale) != Number(product?.prices) &&
                        <Text allowFontScaling={false} style={styleId_DvXE}>{LibUtils.money(product?.prices)}</Text>
                      }
                      <Text allowFontScaling={false} style={styleId_Z77xH9}> {LibUtils.money(product?.sale)}</Text>
                    </View>
                    {
                      isDisabled &&
                      <Text allowFontScaling={false} style={styleId_22Wwds}>{esp.lang("market/checkout_item", "courier_unavailable")}</Text>
                    }
                    {/* <Text allowFontScaling={false} style={{ marginTop: 4, fontFamily: "Arial", fontSize: 10, fontWeight: "normal", fontStyle: "normal", lineHeight: 13, letterSpacing: 0, textAlign: "left", color: "#707070" }}>Total 1 barang (900 gr)</Text> */}
                    <TouchableOpacity
                      onPress={() => { LibEditbox.show('Catatan', product?.notes, 'default', (notes) => { props?.changeNotes?.(product?.id, product?.cart_id, product?.qty, notes) }) }}
                      style={styleId_1ewN2U} >
                      <LibIcon.AntDesign name='edit' size={12} color={'#999'} />
                      <LibTextstyle textStyle='caption2' text={product?.notes || esp.lang("market/checkout_item", "empty_notes")} style={styleId_Z18npNm} />
                    </TouchableOpacity>
                  </View>
                </View>
              </>
            )
          })
        }

        {
          shipping?.code != undefined ?
            <TouchableOpacity
              onPress={() => LibNavigation.navigateForResult('market/checkout_shipping', { data: shippingArray, selected_id: shipping.id }, 45).then((s) => {
                props.onChageDisabled(false)
                setInsurance(s.insurance_req == 1 ? true : false)
                setShipping(s);
              })}
              style={styleId_Z1lB6YD}>
              <View style={styleId_ZkwSed}>
                <Text allowFontScaling={false} style={styleId_Z2jIMhh}>{shipping?.code?.toUpperCase?.() + ' ' + shipping?.service_code + ' ' + renderEstimateTime(shipping?.estimate)}</Text>
                <Text allowFontScaling={false} style={styleId_Z1RRPJ6}>{LibUtils.money(shipping?.price || 0)}</Text>
              </View>
              <LibIcon name="chevron-right" />
            </TouchableOpacity>
            :
            merchant?.shipping ?
              <TouchableOpacity disabled style={styleId_Z2vNsd1}>
                <Text allowFontScaling={false} style={styleId_Z1hxtm6}>{esp.lang("market/checkout_item", "courier_not_found")}</Text>
              </TouchableOpacity>
              :
              <TouchableOpacity disabled style={styleId_Z2vNsd1}>
                <Text allowFontScaling={false} style={styleId_1S6TkT}>{esp.lang("market/checkout_item", "empty_address")}</Text>
              </TouchableOpacity>
        }

        <View style={styleId_ZOXS44}>
          <Text allowFontScaling={false} style={styleId_IauMW}>{esp.lang("market/checkout_item", "sub_total")}</Text>
          <Text allowFontScaling={false} style={styleId_IauMW}>{LibUtils.money(Number(bill) + Number(shipping?.price || 0))}</Text>
        </View>

        {
          shipping?.insurance == 1 &&
          <View style={styleId_oXq00}>
            <Text allowFontScaling={false} style={styleId_IauMW}>{shipping?.insurance_req == 1 ? esp.lang("market/checkout_item", "insurance_require") : esp.lang("market/checkout_item", "insurance")}</Text>
            <TouchableOpacity disabled={!!shipping?.insurance_req} onPress={() => { setInsurance(!insurance) }} >
              {
                shipping?.insurance_req &&
                <LibIcon name={'checkbox-marked-outline'} />
                ||
                <LibIcon name={insurance ? 'checkbox-marked-outline' : 'checkbox-blank-outline'} />
              }
            </TouchableOpacity>
          </View>
        }
      </View>
    </>
  )
}
const styleId_Z27zEN: any = { marginTop: 15, height: 8, flex: 1, backgroundColor: '#F5F5F5' }
const styleId_Z20r5tY: any = { marginTop: 15, marginLeft: 20, marginRight: 20, flexDirection: 'row', alignContent: 'center', alignItems: 'center' }
const styleId_1asTLy: any = { marginLeft: 5, width: 20, height: 20 }
const styleId_ZkwSed: any = { marginLeft: 15 }
const styleId_Z1dSilI: any = { fontFamily: "Arial", fontSize: 10, fontWeight: "bold", fontStyle: "normal", lineHeight: 13, letterSpacing: 0, textAlign: "left", color: "#03192a" }
const styleId_Z2kirXg: any = { flexDirection: 'row', marginTop: 4, alignContent: 'center', alignItems: 'center' }
const styleId_Z163Hi1: any = { fontFamily: "Arial", fontSize: 8, fontWeight: "normal", fontStyle: "normal", lineHeight: 16, letterSpacing: 0, textAlign: "center", color: "#d1d1d1" }
const styleId_1xsTFo: any = { marginTop: 15, marginLeft: 20, marginRight: 20, flexDirection: 'row', alignContent: 'center', alignItems: 'center' }
const styleId_2wNvzO: any = { marginLeft: 5, width: 50, height: 50, borderRadius: 4 }
const styleId_Z17LdUb: any = { fontFamily: "Arial", fontSize: 10, fontWeight: "normal", fontStyle: "normal", lineHeight: 13, letterSpacing: 0, textAlign: "left", color: "#707070", flexWrap: 'wrap' }
const styleId_17srzJ: any = { flexDirection: 'row', flexWrap: 'wrap' }
const styleId_1rgcuB: any = { color: "#999", backgroundColor: '#f1f2f3', paddingHorizontal: 3, paddingVertical: 2, borderRadius: 3 }
const styleId_1fmvBo: any = { flexDirection: 'row', alignItems: 'center' }
const styleId_Z77xH9: any = { marginTop: 4, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", lineHeight: 16, letterSpacing: 0, textAlign: "left", color: "#03192a" }
const styleId_DvXE: any = { marginTop: 4, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", lineHeight: 16, letterSpacing: 0, textAlign: "left", color: "#999", textDecorationLine: 'line-through' }
const styleId_22Wwds: any = { fontFamily: "Arial", fontSize: 8, fontWeight: "normal", fontStyle: "normal", lineHeight: 16, letterSpacing: 0, color: LibStyle.colorRed }
const styleId_1ewN2U: any = { flexDirection: 'row', alignItems: 'center', marginTop: 10 }
const styleId_Z18npNm: any = { color: '#888', marginLeft: 10 }
const styleId_Z1lB6YD: any = { alignContent: 'center', alignItems: 'center', padding: 7, marginLeft: 25, marginRight: 25, margin: 15, marginBottom: 0, flexDirection: 'row', justifyContent: 'space-between', height: 40, borderRadius: 18, backgroundColor: "#fff", borderStyle: "solid", borderWidth: 1, borderColor: "#724225" }
const styleId_Z2jIMhh: any = { fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", lineHeight: 13, letterSpacing: 0, textAlign: "left", color: "#724225" }
const styleId_Z1RRPJ6: any = { fontFamily: "Arial", fontSize: 10, fontWeight: "bold", fontStyle: "normal", lineHeight: 13, letterSpacing: 0, textAlign: "left", color: "#a5a5a5" }
const styleId_Z2vNsd1: any = { alignContent: 'center', alignItems: 'center', marginTop: 15, marginLeft: 25, marginRight: 25, flexDirection: 'row', justifyContent: 'space-between', height: 40, borderRadius: 18, backgroundColor: "#fff", borderStyle: "solid", borderWidth: 1, borderColor: "#a5a5a5" }
const styleId_Z1hxtm6: any = { marginLeft: 25, fontFamily: "Arial", fontSize: 10, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "center", color: "#a5a5a5" }
const styleId_1S6TkT: any = { marginLeft: 25, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", lineHeight: 13, letterSpacing: 0, textAlign: "left", color: "#a5a5a5" }
const styleId_ZOXS44: any = { marginTop: 25, marginLeft: 25, marginRight: 25, flexDirection: 'row', justifyContent: 'space-between' }
const styleId_IauMW: any = { fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", lineHeight: 13, letterSpacing: 0, textAlign: "left", color: "#03192a" }
const styleId_oXq00: any = { marginTop: 25, marginLeft: 25, marginRight: 25, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }