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


import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/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 { MarketSection_menu } from 'esoftplay/cache/market/section_menu/import';
import { MarketSlidingupProperty } from 'esoftplay/cache/market/slidingup/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';

import React, { useEffect } from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface MarketProduct_detail_shippingArgs {

}
export interface MarketProduct_detail_shippingProps {
  shipping: any[],
  product_id: string,
  location: any,
  onPress: () => void
}
export default function m(props: MarketProduct_detail_shippingProps): any {
  const [data, setData] = useSafeState<any[]>(props.shipping)
  const [minPrice, setMinPrice] = useSafeState(0)
  const [location, setLocation] = useSafeState(props.location)
  const shortName = location?.name?.split?.(',')[0] + ',' + location?.name?.split?.(',')[1]

  function getAllPrices(res: any): number[] {
    let prices: number[] = []
    res.forEach((item: any) => {
      item.list.forEach((item: any) => {
        if (item.shipping_cost > 0)
          prices.push(item.shipping_cost)
      })
    })
    return prices
  }

  useEffect(() => {
    if (location.id) {
      new LibCurl("shop/product_shipping", {
        id: props.product_id,
        destination_id: location.id,
        destination_latlong: location.latlong
      }, (res: any, msg) => {
        MarketSlidingupProperty.hide()
        LibProgress.hide()
        setMinPrice(Math.min(...getAllPrices(res)))
        setData(res)
      }, msg => {
        setMinPrice(0)
        setData([])
        LibProgress.hide()
        // LibToastProperty.show(msg)
      }, 1)
    } else {
      setMinPrice(Math.min(...getAllPrices(props.shipping)))
    }
  }, [location])

  useEffect(() => {
    MarketSlidingupProperty.add(
      <View style={{ backgroundColor: "white", paddingVertical: 10 }} >
        <LibTextstyle textStyle="headline" text={esp.lang("market/product_detail_shipping", "info")} style={{ textAlign: 'center', paddingBottom: 10 }} />
        <MarketSection_menu size="line" />
        <TouchableOpacity
          onPress={() => {
            MarketSlidingupProperty.hide()
            LibNavigation.navigateForResult('market/location').then((v) => {
              setLocation({ id: v.id, name: v.detail, latlong: v.latitude + ',' + v.longitude })
              LibProgress.show(esp.lang("market/product_detail_shipping", "waiting"))
            })
          }}
          style={{ paddingHorizontal: 17, paddingVertical: 10, flexDirection: "row", alignItems: 'center' }} >
          <LibTextstyle textStyle="footnote" text={esp.lang("market/product_detail_shipping", "send_to")} style={{ color: "#888" }} />
          <View style={{ flex: 1 }} />
          {
            location.id ?
              <LibTextstyle textStyle="footnote" text={shortName} style={{ marginRight: 10 }} />
              :
              <LibTextstyle textStyle="footnote" text={esp.lang("market/product_detail_shipping", "select_location")} style={{ marginRight: 10 }} />
          }
          <LibIcon.SimpleLineIcons name={'arrow-right'} size={12} color={MarketStyle.colorPrimaryMarket} />
        </TouchableOpacity>
        <MarketSection_menu size="small" />
        <ScrollView showsVerticalScrollIndicator={false} style={{ maxHeight: LibStyle.height * 0.6 }}>

          {
            LibUtils.checkUndefined(data, '0') && data.map((item: any, index: number) => {
              if (item.list.some((x: any) => x.shipping_cost > 0))
                return (
                  <View key={index} style={{ borderBottomWidth: 1, borderBottomColor: "#ececec", paddingHorizontal: 17, paddingVertical: 10 }} >
                    <LibTextstyle textStyle='footnote' text={item.code.toUpperCase()} style={{ alignSelf: 'flex-start', fontWeight: 'bold' }} />
                    {
                      item.list.map((item: any, idx: number) => {
                        if (item.shipping_cost <= 0)
                          return null
                        return (
                          <View key={item.service} style={{ flexDirection: "row", marginVertical: 10 }} >
                            <LibTextstyle textStyle="caption1" text={item.service} style={{ flex: 1, color: '#888' }} />
                            <LibTextstyle textStyle="caption1" text={item.estimate_day} style={{ color: '#888' }} />
                            <LibTextstyle textStyle="caption1" text={LibUtils.money(item.shipping_cost)} style={{ minWidth: 100, textAlign: 'right' }} />
                          </View>
                        )
                      })
                    }
                  </View>
                )
              else
                return null
            })
          }
        </ScrollView>
      </View>
    )
  }, [location, data])


  return (
    <View style={{ marginTop: 15 }}>
      <Text allowFontScaling={false} style={{ marginLeft: 25, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", lineHeight: 13, letterSpacing: 0, textAlign: "left", color: "#03192a" }}>{esp.lang("market/product_detail_shipping", "shipping")}</Text>
      <TouchableOpacity onPress={() => { MarketSlidingupProperty.show() }} style={{ alignContent: 'center', alignItems: 'center', marginLeft: 25, marginRight: 25, marginTop: 10, flexDirection: 'row', justifyContent: 'space-between' }}>
        {
          location.id ?
            <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode="tail" style={{ flex: 1, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", lineHeight: 15, letterSpacing: 0, textAlign: "left", color: "#707070" }}>{data.length == 0 ? esp.lang("market/product_detail_shipping", "show_estimate") : esp.lang("market/product_detail_shipping", "shipping_to", LibUtils.money(minPrice), shortName)}</Text>
            :
            <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode="tail" style={{ flex: 1, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", lineHeight: 15, letterSpacing: 0, textAlign: "left", color: "#707070" }}>{esp.lang("market/product_detail_shipping", "min", LibUtils.money(minPrice))}</Text>
        }
        <LibIcon name="chevron-right" />
      </TouchableOpacity>
    </View>
  )
}