// withHooks
// noPage
import { applyStyle } from 'esoftplay';

import { LibIcon } from 'esoftplay/cache/lib/icon/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 { MarketButton } from 'esoftplay/cache/market/button/import';
import { MarketCartProperty } from 'esoftplay/cache/market/cart/import';
import { MarketCart_offlineProperty } from 'esoftplay/cache/market/cart_offline/import';
import { MarketSection_menu } from 'esoftplay/cache/market/section_menu/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';
import { UserClass } from 'esoftplay/cache/user/class/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';

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


export interface MarketProduct_detail_variantProps {
  product_id: string,
  price: string,
  sale: string,
  image: string,
  currency: string,
  min_order: number,
  options: any[],
  price_option: any[],
  name: string,
  merchant_id: string,
  stocks: number,
  merchant_name: string
  onPressDone?: () => void
  buttonText?: string
  buyNow?: boolean
  advert_id?: string,
  advert_keyword?: string
}

export default function m(props: MarketProduct_detail_variantProps): any {
  const [qty, setQty] = useSafeState(Math.min(props.min_order || 1))
  const user = UserClass.state().get()
  const [selected, setSelected] = useSafeState<any>({})
  const [primary, setPrimary] = useSafeState(props.options.filter((x) => x.is_primary == 1))
  const [secondary, setSecondary] = useSafeState(props.options.filter((x) => x.is_primary == 0))
  const [valid, setValid] = useSafeState(false)

  useEffect(() => {
    let out = true
    if (primary.length > 0) {
      out = out && selected.primary
      if (secondary.length > 0) {
        out = out && selected.secondary
        if (selected) {
          out = out && selected.option_stocks > 0
        }
        if (qty > selected.option_stocks) {
          setQty(selected.option_stocks)
        }
      }
    } else if (Number(props.stocks) < Number(props.min_order)) {
      out = false
    }
    setValid(out)
  }, [secondary, primary, selected])


  return (
    <View style={{ backgroundColor: 'white', paddingVertical: 10 }} >
      <View style={{ flexDirection: 'row', alignItems: 'flex-end', paddingBottom: 10, paddingHorizontal: 17, }} >
        <LibPicture source={{ uri: selected?.image || props.image }} style={{ height: 60, width: 60, resizeMode: 'cover', borderRadius: 4 }} />
        <View style={{ marginLeft: 10 }} >
          {
            valid &&
            <LibTextstyle textStyle='footnote' text={esp.lang("market/product_detail_variant", "stocks", LibUtils.number(selected?.option_stocks || props.stocks))} style={{ color: '#707070' }} />
          }
          <View style={{ flexDirection: 'row' }}>
            {
              props.sale != props.price &&
              <LibTextstyle textStyle='headline' text={LibUtils.money(selected?.option_price || props.price, props.currency) + ' '} style={{ textDecorationLine: 'line-through', textDecorationStyle: 'solid', color: '#d1d1d1' }} />
            }
            <LibTextstyle textStyle='headline' text={LibUtils.money(selected?.option_price || props.sale, props.currency)} style={{}} />
          </View>
        </View>
      </View>
      {
        primary.length > 0 &&
        <>
          <MarketSection_menu title={primary[0].name} smooth />
          <ScrollView showsVerticalScrollIndicator={false} style={{ maxHeight: 150 }}  >
            <View style={{ flexDirection: 'row', flexWrap: 'wrap', marginHorizontal: 17 }} >
              {primary.map((x, i) => (
                <TouchableOpacity key={i}
                  onPress={() => {
                    let price = props.price_option.filter((c) => secondary.length > 0 ? (c.option_id_primary_data == x.data && c.option_id_secondary_data == selected.secondary) : c.option_id_primary_data == x.data)
                    if (Array.isArray(price))
                      price = price[0]
                    setSelected({ ...selected, primary: x.data, image: x.image || props.image, ...price })
                  }}
                  style={{ backgroundColor: selected.primary == x.data ? MarketStyle.colorPrimaryMarket : '#f9f9f9', margin: 10, marginLeft: 0, paddingVertical: 6, paddingHorizontal: 10, borderRadius: 4 }} >
                  <LibTextstyle textStyle="footnote" text={x.data} style={{ color: selected.primary == x.data ? "white" : '#03192a' }} />
                </TouchableOpacity>
              ))}
            </View>
          </ScrollView>
        </>
      }
      {
        secondary.length > 0 &&
        <>
          <MarketSection_menu title={secondary[0].name} smooth />
          <ScrollView showsVerticalScrollIndicator={false} style={{ maxHeight: 150 }}  >
            <View style={{ flexDirection: 'row', flexWrap: 'wrap', marginHorizontal: 17 }} >
              {secondary.map((x, i) => (
                <TouchableOpacity key={i}
                  onPress={() => {
                    let price = props.price_option.filter((c) => c.option_id_primary_data == selected.primary && c.option_id_secondary_data == x.data)
                    if (Array.isArray(price))
                      price = price[0]
                    setSelected({ ...selected, secondary: x.data, ...price })
                  }}
                  style={{ backgroundColor: selected.secondary == x.data ? MarketStyle.colorPrimaryMarket : '#f9f9f9', margin: 10, marginLeft: 0, paddingVertical: 6, paddingHorizontal: 10, borderRadius: 4 }} >
                  <LibTextstyle textStyle="footnote" text={x.data} style={{ color: selected.secondary == x.data ? "white" : '#03192a' }} />
                </TouchableOpacity>
              ))}
            </View>
          </ScrollView>
        </>
      }
      <View pointerEvents={!valid ? "none" : "auto"} >
        {
          selected && selected.option_stocks == 0 &&
          <View style={applyStyle({ alignItems: 'center', alignSelf: 'center', marginHorizontal: 17, marginVertical: 10 })} >
            <LibTextstyle textStyle="footnote" text={esp.lang("market/product_detail_variant", "empty")} style={{ color: LibStyle.colorRed }} />
          </View>
        }
        {
          Number(props.stocks) < Number(props.min_order) &&
          <View style={applyStyle({ alignItems: 'center', alignSelf: 'center', marginHorizontal: 17, marginVertical: 10 })} >
            <LibTextstyle textStyle="footnote" text={esp.lang("market/product_detail_variant", "min_order", LibUtils.number(props.min_order))} style={{ color: LibStyle.colorRed }} />
          </View>
        }
        {
          valid &&
          <View style={applyStyle({ flexDirection: 'row', alignItems: 'center', marginTop: 5, alignSelf: 'center', marginHorizontal: 17, marginVertical: 10 })} >
            <TouchableOpacity
              style={{ borderRadius: 10, height: 20, width: 20, borderWidth: 1, borderColor: valid ? MarketStyle.colorPrimaryMarket : "#f1f1f1" }}
              onPress={() => { setQty(qty <= (Number(props.min_order) || 1) ? Number(props.min_order) : Number(qty) - 1) }} hitSlop={applyStyle({ top: 10, left: 10, right: 10, bottom: 10 })} >
              <LibIcon name='minus' color={valid ? MarketStyle.colorPrimaryMarket : "#f1f1f1"} size={18} />
            </TouchableOpacity>
            {/* <TouchableOpacity onPress={() => { }} > */}
            <View style={applyStyle({ paddingHorizontal: 10, margin: 1, padding: 2, borderRadius: 2, alignItems: 'center', backgroundColor: "white" })} >
              <LibTextstyle text={LibUtils.number(qty)} textStyle="caption1" />
            </View>
            {/* </TouchableOpacity> */}
            <TouchableOpacity
              style={{ borderRadius: 10, height: 20, width: 20, borderWidth: 1, borderColor: valid ? MarketStyle.colorPrimaryMarket : "#f1f1f1" }}
              onPress={() => { setQty(qty < (selected.option_stocks || Number(props.stocks)) ? Number(qty) + 1 : (selected.option_stocks || Number(props.stocks))) }}
              hitSlop={applyStyle({ top: 10, left: 10, right: 10, bottom: 10 })} >
              <LibIcon name='plus' color={valid ? MarketStyle.colorPrimaryMarket : "#f1f1f1"} size={18} />
            </TouchableOpacity>
          </View>
        }
        {
          props.buyNow ?
            <MarketButton
              colorBackground={!valid ? "#aaa" : undefined}
              buttonStyle={{ marginTop: 10, marginHorizontal: 17 }} color={"white"} text={props.buttonText || esp.lang("market/product_detail_variant", "buy_now")} onPress={() => {
                MarketCartProperty.buyNow(props.product_id, qty, '', selected.price_id || 0, props.advert_id, props.advert_keyword)
                props.onPressDone && props.onPressDone()
              }} />
            :
            <MarketButton
              colorBackground={!valid ? "#aaa" : undefined}
              buttonStyle={{ marginTop: 10, marginHorizontal: 17 }} color={"white"} text={props.buttonText || esp.lang("market/product_detail_variant", "add_to_cart")} onPress={() => {
                user ?
                  MarketCartProperty.add(props.product_id, qty, '', selected.price_id || 0, props.advert_id, props.advert_keyword)
                  :
                  MarketCart_offlineProperty.addTo({
                    id: props.product_id,
                    image: selected.image,
                    merchant_id: props.merchant_id,
                    name: props.name,
                    merchant_name: props.merchant_name,
                    notes: '',
                    price: selected.option_price || props.price,
                    price_id: selected.price_id || 0,
                    qty: qty,
                    qty_max: (selected.option_stocks || props.stocks)
                  })
                props.onPressDone && props.onPressDone()
              }} />
        }
      </View>
    </View>
  )
}