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


import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibLazy } from 'esoftplay/cache/lib/lazy/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/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 { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketInput_square } from 'esoftplay/cache/market/input_square/import';
import { MarketKeep } from 'esoftplay/cache/market/keep/import';
import { MarketProduct_variant_itemData, MarketProduct_variant_itemProperty } from 'esoftplay/cache/market/product_variant_item/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';

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

export interface MarketProduct_variant_priceProps {

}

export interface MarketProduct_variant_priceData {
  option_id_primary_name: string,
  option_id_primary_data: string,
  option_id_secondary_name: string,
  option_id_secondary_data: string,
  option_price: string,
  option_stocks: string,
  price_id: string
}


export function build(variantPrice: MarketProduct_variant_priceData): MarketProduct_variant_priceData {
  return variantPrice
}

function generatePrices(data: MarketProduct_variant_itemData[], oldData?: MarketProduct_variant_priceData[]): MarketProduct_variant_priceData[] {
  let out: MarketProduct_variant_priceData[] = []
  let names = MarketProduct_variant_itemProperty.getAllVariantName(data)
  let mainVariant = MarketProduct_variant_itemProperty.getAllVariantData(names[0], data)
  let secondVariant: string[] = []
  if (names.length == 2)
    secondVariant = LibUtils.uniqueArray(MarketProduct_variant_itemProperty.getAllVariantData(names[1], data))
  mainVariant.forEach((mVariant) => {
    if (secondVariant.length == 0)
      out.push({
        option_id_primary_name: names[0],
        option_id_primary_data: mVariant,
        option_id_secondary_name: "",
        option_id_secondary_data: "",
        option_price: "",
        option_stocks: '1',
        price_id: ""
      })
    secondVariant.forEach((sVariant) => {
      out.push({
        option_id_primary_name: names[0],
        option_id_primary_data: mVariant,
        option_id_secondary_name: names[1],
        option_id_secondary_data: sVariant,
        option_price: "",
        option_stocks: '1',
        price_id: ""
      })
    })
  })
  return out
}

function setAllPricesQty(data: MarketProduct_variant_priceData[], price: string, stocks: string) {
  let out: MarketProduct_variant_priceData[] = []
  out = data.map((item) => {
    if (stocks == undefined || stocks == null || stocks == "")
      return ({
        ...item,
        option_price: price,
      })

    if (price == undefined || price == null || price == "")
      return ({
        ...item,
        option_stocks: stocks
      })

    return ({
      ...item,
      option_price: price,
      option_stocks: stocks
    })
  })
  return out
}

export function removeDuplicatesByItemData(data: any[]): any[] {
  let cdata: any[] = []
  let item_dt: any = []
  data.forEach((x: any) => {
    if (!item_dt.includes(x.data)) {
      item_dt.push(x.data)
      cdata.push(x)
    }
  });
  return cdata
}

export default function m(props: MarketProduct_variant_priceProps): any {
  const inputPrice = useRef<MarketInput_square>(null)
  const inputStock = useRef<MarketInput_square>(null)
  const { price_option, options } = LibNavigation.getArgsAll<any>(props)
  const inputGlobalRef = useRef<LibSlidingup>(null)
  const [prices, setPrices, getPrices] = useSafeState<MarketProduct_variant_priceData[]>(generatePrices(options))
  const inputPrices = new Array(prices.length).fill(useRef<MarketInput_square>(null))
  const inputStocks = new Array(prices.length).fill(useRef<MarketInput_square>(null))
  const [global] = MarketKeep<any>({})
  const [counter, setCounter] = useSafeState(0)


  useEffect(() => {
    let newPrices = prices
    prices.forEach((price, i) => {
      price_option && price_option.forEach((old_price: any) => {
        if (price.option_id_primary_data == old_price.option_id_primary_data) {
          if (price.option_id_secondary_data == old_price.option_id_secondary_data) {
            newPrices = LibObject.set(newPrices, old_price.option_price)(i, 'option_price')
            newPrices = LibObject.set(newPrices, old_price.option_stocks)(i, 'option_stocks')
          }
        }
      })
    })
    esp.log(newPrices);
    setPrices(newPrices)
    return () => {
      LibNavigation.cancelBackResult(LibNavigation.getResultKey(props))
    }
  }, [])

  return (
    <LibLazy>
      <MarketHeader
        leftIcon={{ name: "close", onPress: () => { LibNavigation.back() } }}
        title={esp.lang("market/product_variant_price", "header_title")}
      />
      <ScrollView >
        <TouchableOpacity
          onPress={() => inputGlobalRef.current?.show()}
          style={{ flexDirection: 'row', margin: 17, alignItems: 'center' }} >
          <View style={{ flex: 1, marginRight: 10 }} >
            <LibTextstyle
              text={esp.lang("market/product_variant_price", "price_stok")}
              textStyle='callout'
              style={{ color: '#03192a' }}
            />
            <LibTextstyle
              text={esp.lang("market/product_variant_price", "set_price_stock")}
              textStyle='footnote'
              style={{ color: '#03192a' }}
            />
          </View>
          <LibIcon
            name="chevron-right"
            size={24}
            color={MarketStyle.colorPrimaryMarket} />
        </TouchableOpacity>

        <View style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: '#f5f5f5', paddingHorizontal: 17, padding: 15 }} >
          <Text allowFontScaling={false} style={{ flex: 2, fontFamily: "Arial", fontSize: 14, fontWeight: "normal", fontStyle: "normal", lineHeight: 18, letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/product_variant_price", "variant")}</Text>
          <Text allowFontScaling={false} style={{ flex: 2, fontFamily: "Arial", fontSize: 14, fontWeight: "normal", fontStyle: "normal", lineHeight: 18, letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/product_variant_price", "price")}</Text>
          <Text allowFontScaling={false} style={{ flex: 2, fontFamily: "Arial", fontSize: 14, fontWeight: "normal", fontStyle: "normal", lineHeight: 18, letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/product_variant_price", "stocks")}</Text>
        </View>
        {
          LibUtils.checkUndefined(prices, '0') && prices?.map?.((row, i) => {
            return (
              <View key={i + '-' + counter} style={{ flexDirection: 'row', alignItems: 'center', paddingLeft: 17 }} >
                <Text style={{ flex: 2, fontFamily: "Arial", fontSize: 14, fontWeight: "normal", fontStyle: "normal", lineHeight: 18, letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{row.option_id_primary_data + (row.option_id_secondary_data ? (' - ' + row.option_id_secondary_data) : '')}</Text>
                <MarketInput_square
                  ref={inputPrices[i]}
                  label=" "
                  // key={row.option_price}
                  containerStyle={{ flex: 2, marginTop: -10, paddingLeft: 17 }}
                  mask="###.###.###.###.###"
                  keyboardType="phone-pad"
                  defaultValue={String(row?.option_price)}
                  maskFrom="end"
                  prefix={esp.lang("market/product_variant_price", "prefix")}
                  onChangeText={(t) => { setPrices(LibObject.set(getPrices(), t)(i, 'option_price')) }} />
                <MarketInput_square
                  ref={inputStocks[i]}
                  // key={row?.option_stocks}
                  label=" "
                  suffix={esp.lang("market/product_variant_price", "suffix")}
                  keyboardType="phone-pad"
                  containerStyle={{ flex: 2, marginTop: -10, paddingLeft: 0 }}
                  defaultValue={String(row?.option_stocks) || '1'}
                  mask="###.###.###.###.###"
                  maskFrom="end"
                  onChangeText={(t) => { setPrices(LibObject.set(getPrices(), t)(i, 'option_stocks')) }} />
              </View>
            )
          })
        }
      </ScrollView>
      {
        options.length > 0 &&
        <View pointerEvents={prices.some((x) => x?.option_price?.length == 0 || x?.option_stocks?.length == 0) ? "none" : "auto"} style={{ paddingHorizontal: 17, marginTop: 5, marginBottom: 8 }} >
          <MarketButton
            textStyle={{ color: 'white' }}
            colorBackground={prices.some((x) => x?.option_price?.length == 0 || x?.option_stocks?.length == 0) ? "#aaa" : undefined}
            text={esp.lang("market/product_variant_price", "save_price_stok")}
            buttonStyle={{ borderRadius: 20 }}
            onPress={() => {
              LibNavigation.sendBackResult({ options: removeDuplicatesByItemData(options), price_option: getPrices() }, LibNavigation.getResultKey(props))
              if (LibNavigation.getResultKey(props) == 3214)
                LibNavigation.back()
            }}
          />
        </View>
      }
      <LibSlidingup ref={inputGlobalRef} >
        <View style={{ backgroundColor: 'white', borderTopLeftRadius: 15, borderTopRightRadius: 15 }} >
          <View style={{ flexDirection: 'row', alignItems: 'center', padding: 10 }} >
            <TouchableOpacity onPress={() => { inputGlobalRef.current?.hide() }} >
              <LibIcon name='close' />
            </TouchableOpacity>
            <Text allowFontScaling={false} style={{ marginLeft: 15, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/product_variant_price", "set_price")}</Text>
          </View>
          <View style={{ marginHorizontal: 20 }} >
            <MarketInput_square
              label=" "
              ref={inputPrice}
              mask="###.###.###.###.###"
              containerStyle={{ marginTop: -10 }}
              keyboardType="phone-pad"
              defaultValue={global?.price}
              maskFrom="end"
              prefix={esp.lang("market/product_variant_price", "global_prefix")}
              onChangeText={(x) => { global.price = x }} />
            <MarketInput_square
              label=" "
              ref={inputStock}
              containerStyle={{ marginTop: -20 }}
              prefix={esp.lang("market/product_variant_price", "global_stok")}
              suffix={esp.lang("market/product_variant_price", "global_stok_suffix")}
              maskFrom="end"
              mask="###.###.###.###.###"
              keyboardType="phone-pad"
              defaultValue={global?.stock}
              onChangeText={(x) => global.stock = x} />
          </View>
          <MarketButton text={esp.lang("market/product_variant_price", "btn_confirm")}
            colorBackground={MarketStyle.colorPrimaryMarket}
            textStyle={{ color: 'white' }}
            buttonStyle={{ marginBottom: 15, marginTop: 10, marginHorizontal: 24, borderRadius: 20 }}
            onPress={() => {
              setPrices(setAllPricesQty(getPrices(), global?.price, global?.stock))
              setCounter(counter + 1)
              inputGlobalRef.current?.hide()
            }} />
        </View>
      </LibSlidingup>
    </LibLazy>
  )
}