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


import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/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 { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketInput_square } from 'esoftplay/cache/market/input_square/import';
import { MarketProduct_inputForm } from 'esoftplay/cache/market/product_input/import';
import { MarketSection_menu } from 'esoftplay/cache/market/section_menu/import';
import { UseForm } from 'esoftplay/cache/use/form/import';

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


export interface MarketProduct_grosirProps {

}

export interface MarketProduct_grosirData {
  qty_min: string,
  qty_max: string,
  price_unit: string,
}

export interface MarketProduct_grosirItem extends MarketProduct_grosirData {
  min_loc: boolean,
  limitPrice: number,
  onChangeMax: (max: string) => void,
  onChangeMin: (min: string) => void,
  onChangePrice: (price: string) => void,
  onDelete?: (min_qty: string) => void,
  onValid: (s: boolean) => void
}

function Item(props: MarketProduct_grosirItem) {
  const [errormin, setErrormin] = useSafeState(false)
  const [errormax, setErrormax] = useSafeState(false)
  const [errorprice, setErrorprice] = useSafeState(false)

  const inputMin = useRef<MarketInput_square>(null)
  const inputMax = useRef<MarketInput_square>(null)
  const inputPrice = useRef<MarketInput_square>(null)

  useEffect(() => {
    props.onValid(!errorprice && !errormin && !errormax)
  }, [errorprice, errormin, errormax])

  return (
    <View style={{ flexDirection: 'row', marginTop: 10, alignItems: "center", paddingRight: 10 }} >
      <MarketInput_square
        label={esp.lang("market/product_grosir", "qty_min")}
        ref={inputMin}
        mask="###.###.###.###.###"
        containerStyle={{ flex: 1 }}
        maskFrom="end"
        error={errormin}
        inactive={props.min_loc}
        editable={!props.min_loc}
        defaultValue={String(props.qty_min)}
        keyboardType="phone-pad"
        onChangeText={(t) => {
          setErrormin(false)
          props.onChangeMin(t)
        }} />
      <MarketInput_square
        label={esp.lang("market/product_grosir", "qty_max")}
        ref={inputMax}
        mask="###.###.###.###.###"
        containerStyle={{ flex: 1, marginLeft: -17 }}
        maskFrom="end"
        onBlur={() => {
          if (parseInt(inputMax.current?.getText() || '0') <= parseInt(inputMin.current?.getText() || '0')) {
            setErrormax(true)
          }
        }}
        error={errormax}
        defaultValue={String(props.qty_max)}
        keyboardType="phone-pad"
        onChangeText={(t) => {
          setErrormax(false)
          props.onChangeMax(t)
        }} />
      <MarketInput_square
        label={esp.lang("market/product_grosir", "price_pcs")}
        ref={inputPrice}
        mask="###.###.###.###.###"
        error={errorprice}
        containerStyle={{ flex: 2, marginLeft: -17 }}
        onBlur={() => {
          if (parseInt(inputPrice.current?.getText() || '0') >= props.limitPrice) {
            setErrorprice(true)
          }
        }}
        maskFrom="end"
        defaultValue={String(props.price_unit)}
        keyboardType="phone-pad"
        onChangeText={(t) => {
          setErrorprice(false)
          props.onChangePrice(t)
        }} />
      {
        props.onDelete &&
        <TouchableOpacity onPress={() => props.onDelete && props.onDelete(props.qty_min)} style={{ marginTop: 12 }} >
          <LibIcon name="minus-circle" size={19} color={LibStyle.colorRed} />
        </TouchableOpacity>
      }
    </View>
  )
}

export default function m(props: MarketProduct_grosirProps): any {
  const def = LibUtils.getArgs(props, 'data', [])
  const [data, setData] = useSafeState<MarketProduct_grosirData[]>(def)
  const [form, setForm, reForm, delForm, updForm] = UseForm<MarketProduct_inputForm>("market_product_input")
  const [counter, setCounter] = useSafeState(0)
  const [valid, setValid] = useSafeState(true)

  function isValid() {
    if (data.some((x) => x.qty_max == ''))
      return false
    if (data.some((x) => x.qty_min == ''))
      return false
    if (data.some((x) => x.price_unit == ''))
      return false
    return true
  }

  useEffect(() => {
    return () => LibNavigation.cancelBackResult(LibNavigation.getResultKey(props))
  }, [])

  return (
    <View style={{ flex: 1 }} >
      <MarketHeader
        leftIcon={{ name: "close", onPress: () => LibNavigation.back() }}
        title={esp.lang("market/product_grosir", "header_title")} />
      <ScrollView>
        <LibTextstyle textStyle="callout" text={esp.lang("market/product_grosir", "start_price", LibUtils.number(form?.price || 0))} style={{ padding: 10, textAlign: 'center' }} />
        <MarketSection_menu size="small" />
        <View key={counter} >
          {
            data.map((item, i) => (
              <Item
                {...item}
                key={i}
                onValid={setValid}
                limitPrice={parseInt((i == 0 ? form?.price : data[i - 1].price_unit) || '0')}
                min_loc={i != 0}
                onDelete={(qty_min) => {
                  let dt = data?.filter((x) => x.qty_min != qty_min)
                  setData(dt)
                  setCounter(counter + 1)
                }}
                onChangeMin={(x) => setData(LibObject.set(data, x)(i, 'qty_min'))}
                onChangeMax={(x) => setData(LibObject.set(data, x)(i, 'qty_max'))}
                onChangePrice={(x) => setData(LibObject.set(data, x)(i, 'price_unit'))}
              />
            ))
          }
        </View>
        <MarketButton
          text={esp.lang("market/product_grosir", "btn_add")}
          colorBackground={'white'}
          colorBorder={"#ddd"}
          buttonStyle={{ margin: 17 }}
          onPress={() => {
            const last_max_qty: string = LibUtils.checkUndefined(data, data.length - 1 + '.qty_max') ? data[data.length - 1].qty_max : '0'
            if (last_max_qty != '')
              setData(LibObject.push(data, { qty_min: parseInt(last_max_qty) + 1, qty_max: "", price_unit: "" })())
            else
              LibToastProperty.show(esp.lang("market/product_grosir", "empty_qty_max"))
          }} />
      </ScrollView>
      <View pointerEvents={!(isValid() && valid) ? "none" : "auto"} style={{ paddingHorizontal: 17, marginTop: 4, marginBottom: 8 }} >
        <MarketButton
          colorBackground={!(isValid() && valid) ? "#aaa" : undefined}
          text={esp.lang("market/product_grosir", "btn_save")} onPress={() => { LibNavigation.sendBackResult(data, LibNavigation.getResultKey(props)) }} />
      </View>
    </View>
  )
}