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


import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibInput } from 'esoftplay/cache/lib/input/import';
import { LibKeyboard_avoid } from 'esoftplay/cache/lib/keyboard_avoid/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { MarketAds_cost_keyword_item } from 'esoftplay/cache/market/ads_cost_keyword_item/import';
import { MarketAds_cost_optionArgs } from 'esoftplay/cache/market/ads_cost_option/import';
import { MarketAds_grup_detailArgs } from 'esoftplay/cache/market/ads_grup_detail/import';
import { MarketAds_homeProperty } from 'esoftplay/cache/market/ads_home/import';
import { MarketAds_keyword_editArgs } from 'esoftplay/cache/market/ads_keyword_edit/import';
import { MarketAds_periode_optionArgs } from 'esoftplay/cache/market/ads_periode_option/import';
import { MarketAds_product_listArgs } from 'esoftplay/cache/market/ads_product_list/import';
import { MarketAds_product_preview } from 'esoftplay/cache/market/ads_product_preview/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 { MarketStyle } from 'esoftplay/cache/market/style/import';
import { MarketToggle } from 'esoftplay/cache/market/toggle/import';
import { UseForm } from 'esoftplay/cache/use/form/import';

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


export interface MarketAds_grup_editArgs {
  url: any
}
export interface MarketAds_grup_editProps {

}
export default function m(props: MarketAds_grup_editProps): any {
  const { url } = LibNavigation.getArgsAll<any>(props)
  const [form, setForm, reForm, delForm, batchForm] = UseForm<any>('market/ads_register',)
  const [dailyOption, setDailyOption, getDailyOption] = useSafeState(false)
  const [msg, setMsg] = useSafeState()
  const advertConfig = MarketAds_homeProperty.state().get()

  useEffect(() => {
    new LibCurl(url, null,
      (res, msg) => {
        batchForm({
          ...res,
          products: res.item,
          keywords: res.keyword,
          periode: {
            start_date: res.start_date,
            end_date: res.end_date
          }
        })
        setDailyOption(res.price_daily > 0)
        setMsg(msg)
      }, (msg) => {
        LibDialog.warning(esp.lang("market/ads_grup_edit", "daily_failed"), msg?.message)
      }, 1
    )
  }, [])


  function doEdit() {
    const product = form.products.map((item: any) => ({
      product_id: item.product_id,
      active: 1
    }))
    const keyword = form.keywords.map((item: any) => (
      {
        keyword_id: item?.keyword_id,
        active: item.active || 1,
        price: item?.price
      }
    ))

    let post = {
      type: 1,
      title: form?.title,
      price: form?.price,
      price_limit: form?.price_limit || '',
      price_daily: getDailyOption() ? form?.price_daily : 0,
      products: JSON.stringify(product),
      keywords: JSON.stringify(keyword),
      start_date: form?.periode?.start_date || '',
      end_date: form?.periode?.end_date || '',
    }

    LibProgress.show(esp.lang("market/ads_grup_edit", "edit_waiting"))
    new LibCurl('advert/ads_list_edit/' + form?.id, post,
      (res, msg) => {
        delForm()
        LibProgress.hide()
        LibDialog.info(esp.lang("market/ads_grup_edit", "edit_ok"), msg)
        LibNavigation.backToRoot()
        LibNavigation.navigate('market/ads')
        LibNavigation.navigate<MarketAds_grup_detailArgs>('market/ads_grup_detail', { url: url })
      }, (msg) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("market/ads_grup_edit", "edit_failed"), msg?.message)
      }, 1
    )
  }

  function changePeriode() {
    LibNavigation.navigateForResult<MarketAds_periode_optionArgs>('market/ads_periode_option', { startDate: form?.periode?.start_date, endDate: form?.periode?.end_date }, 1103).then(setForm('periode'))
  }

  function changeCost() {
    LibNavigation.navigateForResult<MarketAds_cost_optionArgs>('market/ads_cost_option', { defValue: form?.price_limit }, 1102).then(setForm('price_limit'))
  }

  function renderKeywords(item: any, i: number) {
    return (
      <MarketAds_cost_keyword_item
        price_min={advertConfig?.ads_product?.price_min}
        price_suggest={advertConfig?.ads_product?.price_suggest}
        keyword={item?.keyword_title} price={item?.price} {...item} key={i} onChangePrice={(p) => {
          const ch = LibObject.set(form?.keywords, p)(i, 'price')
          setForm('keywords')(ch)
        }}
        onDelete={() => {
          const del = LibObject.splice(form?.keywords, i, 1)()
          setForm('keywords')(del)
        }}
      />
    )
  }

  function renderProducts(item: any, i: number) {
    return (
      <MarketAds_product_preview key={i} {...item} image={item?.product_image} title={item?.product_name} onDelete={() => {
        const del = LibObject.splice(form.products, i, 1)()
        setForm('products')(del)
      }} />
    )
  }

  let validPrice = Number(form?.price) >= Number(advertConfig?.ads_product?.price_min)
  let valid = form?.price > 0 && form?.title && form?.keywords?.length > 0 && form?.products?.length > 0 && (dailyOption ? (form?.price_daily != '' ? true : false) : true)

  return (
    <View style={styleId_Z2AMgN} >
      <MarketHeader title={esp.lang("market/ads_grup_edit", "header_title")} onlyBack style={styleId_Z2mwuu4} />

      {
        !msg ? <LibLoading /> :

          <LibKeyboard_avoid style={styleId_ZcMJmd}>
            <ScrollView>

              <View style={styleId_iKvd6} >
                <Text allowFontScaling={false} style={styleId_2nkSWt} >{esp.lang("market/ads_grup_edit", "group_name")}</Text>
                <View style={styleId_ZeIvK3} >
                  <LibInput
                    base
                    onChangeText={setForm('title')}
                    placeholder={esp.lang("market/ads_grup_edit", "group_name_placeholder")}
                    defaultValue={form?.title}
                    placeholderTextColor={MarketStyle.colorPrimaryMarket}
                    style={styleId_ZEQ4kQ} />
                </View>
              </View>

              <View style={styleId_21aMHC} >
                <Text allowFontScaling={false} style={styleId_2nkSWt} >{esp.lang("market/ads_grup_edit", "base_cost")}</Text>
                <View style={[styleId_1JEwIS, { borderBottomColor: validPrice ? '#f1f1f1' : LibStyle.colorRed }]} >
                  <Text allowFontScaling={false} style={styleId_Z1VxP4W} >{esp.lang("market/ads_grup_edit", "base_cost_prefix")}</Text>
                  <LibInput
                    base
                    onChangeText={setForm('price')}
                    placeholder={'0'}
                    defaultValue={String(form?.price)}
                    maskFrom="end"
                    mask={'###.###.###.###.###'}
                    keyboardType={'numeric'}
                    placeholderTextColor={MarketStyle.colorPrimaryMarket}
                    style={styleId_Z237861} />
                </View>
                {
                  validPrice &&
                  <View style={styleId_1RwedJ} >
                    <Text allowFontScaling={false} style={styleId_f1j5v} >{esp.lang("market/ads_grup_edit", "price_suggest")}</Text>
                    <Text allowFontScaling={false} style={styleId_Z10M8g8} >{LibUtils.money(advertConfig?.ads_product?.price_suggest)}</Text>
                  </View>
                }
                {
                  !validPrice &&
                  <View style={styleId_1RwedJ} >
                    <Text allowFontScaling={false} style={styleId_1a6wep} >{esp.lang("market/ads_grup_edit", "price_min")}</Text>
                    <Text allowFontScaling={false} style={styleId_1a6wep} >{LibUtils.money(advertConfig?.ads_product?.price_min)}</Text>
                  </View>
                }
              </View>

              <View style={styleId_ZnsRTT}>
                <Text allowFontScaling={false} style={styleId_Z2twfgW} >{esp.lang("market/ads_grup_edit", "keyword_price")}</Text>
                <View style={styleId_1RPbeD}>
                  <Text allowFontScaling={false} style={styleId_ZKUaRU} >{esp.lang("market/ads_grup_edit", "select_keyword", form?.keywords?.length)}</Text>
                  <TouchableOpacity onPress={() => {
                    LibNavigation.navigateForResult<MarketAds_keyword_editArgs>('market/ads_keyword_edit', { cat_ids: form?.products?.map((x: any) => x.product_cat_id).join(',') }).then(setForm('keywords'))
                  }} >
                    <LibIcon name='plus-circle-outline' color='#4a4a4a' />
                  </TouchableOpacity>
                </View>
                {
                  LibUtils.checkUndefined(form, 'keywords.0') && form?.keywords?.map(renderKeywords)
                }
              </View>

              <View style={styleId_ZnsRTT}>
                <Text allowFontScaling={false} style={styleId_Z2twfgW} >Produk</Text>
                <View style={styleId_1RPbeD}>
                  <Text allowFontScaling={false} style={styleId_ZKUaRU} >{esp.lang("market/ads_grup_edit", "select_product", form?.products?.length)}</Text>
                  <TouchableOpacity onPress={() => {
                    LibNavigation.navigateForResult<MarketAds_product_listArgs>('market/ads_product_list', { from: 'market/ads_grup_edit' }).then(setForm('products'))
                  }} >
                    <LibIcon name='plus-circle-outline' color='#4a4a4a' />
                  </TouchableOpacity>
                </View>
                {
                  LibUtils.checkUndefined(form, 'products.0') && form.products.map(renderProducts)
                }
              </View>

              <View style={styleId_Z1mEUzj} >
                <View style={styleId_Z2boJRP}>
                  <Text allowFontScaling={false} style={styleId_2szJz3} >{esp.lang("market/ads_grup_edit", "ads_periode")}</Text>
                  <TouchableOpacity onPress={() => { changePeriode() }} >
                    <LibIcon name='pencil' color='#4a4a4a' />
                  </TouchableOpacity>
                </View>
                <View style={styleId_Z27iQsf}>
                  {
                    form?.periode?.start_date != '0000-00-00' ?
                      <Text allowFontScaling={false} style={styleId_Z1y3LM8} >{esp.lang("market/ads_grup_edit", "until", form?.periode?.start_date, form?.periode?.end_date)}</Text>
                      :
                      <Text allowFontScaling={false} style={styleId_Z1y3LM8} >{esp.lang("market/ads_grup_edit", "unlimited_periode")}</Text>
                  }
                </View>
              </View>

              <View style={styleId_Z1mEUzj} >
                <View style={styleId_Z2uqeP7}>
                  <View style={styleId_ZcMJmd} >
                    <Text allowFontScaling={false} style={styleId_1mDRxC} >{esp.lang("market/ads_grup_edit", "daily_price")}</Text>
                    <Text allowFontScaling={false} style={styleId_Z2jfMeb} >{esp.lang("market/ads_grup_edit", "daily_price_msg")}</Text>
                  </View>
                  <MarketToggle onChangeValue={() => { setDailyOption(!dailyOption); setForm('price_daily')('') }} type='success' value={dailyOption} />
                </View>
                {
                  dailyOption &&
                  <MarketInput_square
                    prefix={esp.lang("market/ads_grup_edit", "daily_prefix")}
                    defaultValue={form?.price_daily}
                    suffix={esp.lang("market/ads_grup_edit", "daily_suffix")}
                    onChangeText={setForm('price_daily')}
                    containerStyle={styleId_2tlMHb}
                    style={styleId_Z9z4Qm}
                  />
                }
              </View>

              <View style={styleId_Z1mEUzj} >
                <View style={styleId_Z2boJRP}>
                  <Text allowFontScaling={false} style={styleId_2szJz3} >{esp.lang("market/ads_grup_edit", "total_cost")}</Text>
                  <TouchableOpacity onPress={() => { changeCost() }} >
                    <LibIcon name='pencil' color='#4a4a4a' />
                  </TouchableOpacity>
                </View>
                <View style={{ marginHorizontal: 15 }}>
                  {
                    form?.price_limit != 0 ?
                      <Text allowFontScaling={false} style={styleId_Z1y3LM8} >{LibUtils.money(form?.price_limit)}</Text>
                      :
                      <Text allowFontScaling={false} style={styleId_Z1y3LM8} >{esp.lang("market/ads_grup_edit", "unlimited_cost")}</Text>
                  }
                </View>
              </View>

              <View pointerEvents={valid ? 'auto' : 'none'} style={styleId_Z2aL6Dd}>
                <MarketButton
                  colorBackground={valid ? undefined : '#aaa'}
                  text={esp.lang("market/ads_grup_edit", "btn_edit")}
                  onPress={() => {
                    doEdit()
                  }}
                />
              </View>

            </ScrollView>
          </LibKeyboard_avoid>
      }
    </View>
  )
}
const styleId_Z2AMgN: any = { flex: 1, backgroundColor: '#f9f9f9' }
const styleId_Z2mwuu4: any = { backgroundColor: 'white' }
const styleId_ZcMJmd: any = { flex: 1 }
const styleId_iKvd6: any = { backgroundColor: 'white', paddingBottom: 15 }
const styleId_2nkSWt: any = { fontFamily: 'Arial', marginLeft: 15, marginTop: 15, fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: '#4a4a4a' }
const styleId_ZeIvK3: any = { flexDirection: "row", alignItems: "center", borderBottomWidth: 1, borderBottomColor: '#f1f1f1', paddingHorizontal: 10, marginHorizontal: 15, marginTop: 10 }
const styleId_ZEQ4kQ: any = { flex: 1, paddingVertical: Platform.OS == 'ios' ? 10 : 4, fontFamily: 'Arial', fontSize: 14, fontWeight: 'bold', color: MarketStyle.colorPrimaryMarket }
const styleId_21aMHC: any = { backgroundColor: 'white', paddingBottom: 15, marginTop: 10 }
const styleId_1JEwIS: any = { flexDirection: "row", alignItems: "center", borderBottomWidth: 1, paddingHorizontal: 10, marginHorizontal: 15, marginTop: 10 }
const styleId_Z1VxP4W: any = { marginRight: 10, fontSize: 14, fontStyle: "normal", letterSpacing: 0, color: MarketStyle.colorPrimaryMarket }
const styleId_Z237861: any = { flex: 1, paddingVertical: Platform.OS == 'ios' ? 10 : 4, fontFamily: 'Arial', fontSize: 24, fontWeight: 'bold', color: MarketStyle.colorPrimaryMarket }
const styleId_1RwedJ: any = { flexDirection: 'row', alignItems: 'center', marginHorizontal: 15, marginTop: 10 }
const styleId_f1j5v: any = { fontSize: 12, fontStyle: "normal", letterSpacing: 0 }
const styleId_Z10M8g8: any = { fontSize: 12, fontStyle: "normal", letterSpacing: 0, fontWeight: 'bold' }
const styleId_1a6wep: any = { fontSize: 12, fontStyle: "normal", letterSpacing: 0, color: LibStyle.colorRed }
const styleId_ZnsRTT: any = { backgroundColor: 'white', marginTop: 10, paddingBottom: 15 }
const styleId_Z2twfgW: any = { marginLeft: 15, marginTop: 15, fontSize: 14, fontFamily: 'Arial', fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: '#4a4a4a' }
const styleId_1RPbeD: any = { marginHorizontal: 15, flexDirection: 'row', alignItems: 'center', marginTop: 15 }
const styleId_ZKUaRU: any = { flex: 1, fontSize: 14, fontFamily: 'Arial', fontStyle: "normal", letterSpacing: 0 }
const styleId_Z1mEUzj: any = { backgroundColor: 'white', marginTop: 10, paddingVertical: 15 }
const styleId_Z2boJRP: any = { flexDirection: 'row', alignItems: 'center', marginHorizontal: 15 }
const styleId_2szJz3: any = { flex: 1, fontSize: 14, fontFamily: 'Arial', fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: '#4a4a4a' }
const styleId_Z27iQsf: any = { marginHorizontal: 15 }
const styleId_Z1y3LM8: any = { marginTop: 10, fontSize: 14, fontFamily: 'Arial', fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, lineHeight: 18, color: MarketStyle.colorPrimaryMarket }
const styleId_Z2uqeP7: any = { marginHorizontal: 15, flexDirection: 'row', alignItems: 'baseline' }
const styleId_1mDRxC: any = { fontSize: 14, fontFamily: 'Arial', fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: '#4a4a4a' }
const styleId_Z2jfMeb: any = { marginTop: 10, fontSize: 13, fontFamily: 'Arial', fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, lineHeight: 18, color: '#949494' }
const styleId_2tlMHb: any = { marginTop: 10 }
const styleId_Z9z4Qm: any = { margin: 0 }
const styleId_Z2aL6Dd: any = { padding: 15, backgroundColor: 'white', marginTop: 10 }