// 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 { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibScroll } from 'esoftplay/cache/lib/scroll/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { MarketAds_content_input } from 'esoftplay/cache/market/ads_content_input/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_store_keyword_item } from 'esoftplay/cache/market/ads_store_keyword_item/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';
import { MarketAds_product_form } from './ads_product_group';


export interface MarketAds_store_editArgs {
  url: string
}
export interface MarketAds_store_editProps {

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

  const [tab, setTab] = useSafeState<any>(0)

  let _tabs = [
    {
      id: 1,
      title: esp.lang("market/ads_store_edit", "ads_content")
    },
    {
      id: 2,
      title: esp.lang("market/ads_store_edit", "ads_cost")
    },
    {
      id: 3,
      title: esp.lang("market/ads_store_edit", "other")
    }
  ]


  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_store_edit", "daily_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 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: 1,
        price_view: item?.price_view || 12000,
        price_view_each: item?.price_view_each || 1000
      }
    ))

    let post = {
      type: 2,
      title: form?.title,
      price_limit: form?.price_limit || '',
      price_daily: form?.price_daily || '',
      products: JSON.stringify(product),
      keywords: JSON.stringify(keyword),
      start_date: form?.periode?.start_date || '',
      end_date: form?.periode?.end_date || '',
      price_view: form?.price_view || '',
      price_view_each: form.price_view_each || 1000,
      description: form.description || ''
    }

    esp.log(post);

    LibProgress.show(esp.lang("market/ads_store_edit", "edit_wait"))
    new LibCurl('advert/ads_list_edit/' + form?.id, post,
      (res, msg) => {
        delForm()
        LibProgress.hide()
        LibDialog.info(esp.lang("market/ads_store_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_store_edit", "edit_failed"), msg?.message)
      }, 1
    )
  }

  let validPrice = Number(form?.price_view) >= Number(advertConfig?.ads_merchant?.price_view_min)

  return (
    <View style={styleId_Z2AMgN} >
      <MarketHeader title={esp.lang("market/ads_store_edit", "header_title")} onlyBack style={styleId_Z2mwuu4} />
      <LibScroll stickyHeaderIndices={[0]} >
        <ScrollView horizontal showsHorizontalScrollIndicator={false}>
          <View style={styleId_Z1gA9vX} >
            {
              _tabs.map((item: any, i: number) => {
                return (
                  <TouchableOpacity key={i} onPress={() => {
                    setTab(i)
                  }}>
                    <View style={styleId_Z2kI1Fm}>
                      <Text allowFontScaling={false} style={{
                        fontFamily: "Arial", fontSize: tab == i ? 14 : 13,
                        fontWeight: tab == i ? "bold" : "normal",
                        fontStyle: "normal", letterSpacing: 0, textAlign: "center",
                        color: tab == i ? MarketStyle.colorPrimaryMarket : "#c5c5c5"
                      }}>{item.title}</Text>
                    </View>
                    <View style={{ width: '100%', height: 2, backgroundColor: tab == i ? MarketStyle.colorPrimaryMarket : "#fff" }} />
                  </TouchableOpacity>
                )
              })
            }
          </View>
        </ScrollView>

        {
          tab == 0 ?
            <MarketAds_content_input />
            : tab == 1 ?
              <>
                <View style={styleId_ac2Pw} >
                  <Text allowFontScaling={false} style={styleId_Z10AQqI} >{esp.lang("market/ads_store_edit", "ads_cost_other")}</Text>
                  <Text allowFontScaling={false} style={styleId_Z9OFYV} >{esp.lang("market/ads_store_edit", "ads_cost_other_msg")}</Text>
                  <View style={styleId_1blyFK} >
                    <Text allowFontScaling={false} style={styleId_Z1VxP4W} >Rp.</Text>
                    <LibInput
                      base
                      onChangeText={setForm('price_view')}
                      placeholder={'0'}
                      defaultValue={form.price_view || ''}
                      maskFrom="end"
                      mask={'###.###.###.###.###'}
                      keyboardType={'numeric'}
                      placeholderTextColor={MarketStyle.colorPrimaryMarket}
                      style={styleId_Z237861} />
                    <Text allowFontScaling={false} style={styleId_1IjgdV} >{esp.lang("market/ads_store_edit", "view", advertConfig?.ads_merchant?.price_view_each || 1000)}</Text>
                  </View>
                  {
                    validPrice &&
                    <View style={styleId_1ewN2U} >
                      <Text allowFontScaling={false} style={styleId_f1j5v} >{esp.lang("market/ads_store_edit", "recomendation")}</Text>
                      <Text allowFontScaling={false} style={styleId_Z10M8g8} >{LibUtils.money(advertConfig?.ads_merchant?.price_view_suggest)}</Text>
                    </View>
                  }
                  {
                    !validPrice &&
                    <View style={styleId_1ewN2U} >
                      <Text allowFontScaling={false} style={styleId_1a6wep} >{esp.lang("market/ads_store_edit", "minimum_cost")}</Text>
                      <Text allowFontScaling={false} style={styleId_1a6wep} >{LibUtils.money(advertConfig?.ads_merchant?.price_view_min)}</Text>
                    </View>
                  }
                </View>

                <View style={styleId_Z1CjJ0U} >
                  <Text allowFontScaling={false} style={styleId_Z10AQqI} >{esp.lang("market/ads_store_edit", "click_cost")}</Text>
                  <Text allowFontScaling={false} style={styleId_Z9OFYV} >{esp.lang("market/ads_store_edit", "click_cost_msg")}</Text>
                  <View style={styleId_ZRsUcC} >
                    <Text allowFontScaling={false} style={styleId_16tWzX} >{form?.keywords?.length || 0} Kata Kunci</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'))
                    }} style={styleId_1fmvBo} >
                      <LibIcon name='plus-circle' size={18} style={styleId_wxwT1} />
                      <Text allowFontScaling={false} style={styleId_16tWzX} >{esp.lang("market/ads_store_edit", "add_keyword")}</Text>
                    </TouchableOpacity>
                  </View>

                  {
                    LibUtils.checkUndefined(form, 'keywords.0') && form?.keywords?.map((item: any, i: number) => (
                      <MarketAds_store_keyword_item key={i} {...item}
                        price_view_each={advertConfig?.ads_merchant?.price_view_each}
                        price_view_min={advertConfig?.ads_merchant?.price_view_min}
                        price_view_suggest={advertConfig?.ads_merchant?.price_view_suggest}
                        price_view={item?.price_view || '12000'}
                        onDelete={() => {
                          const del = LibObject.splice(form?.keywords, i, 1)()
                          setForm('keywords')(del)
                        }}
                        onChangePrice={(p) => {
                          const ch = LibObject.set(form?.keywords, p)(i, 'price_view')
                          setForm('keywords')(ch)
                        }}
                        style={styleId_1oSw9x}
                      />
                    ))
                  }

                </View>
              </>
              : tab == 2 ?
                <>
                  <View style={styleId_iKvd6} >
                    <Text allowFontScaling={false} style={styleId_2nkSWt} >{esp.lang("market/ads_store_edit", "ads_name")}</Text>
                    <View style={styleId_ZeIvK3} >
                      <LibInput
                        base
                        onChangeText={setForm('title')}
                        placeholder={esp.lang("market/ads_store_edit", "ads_name_placeholder")}
                        defaultValue={form?.title}
                        placeholderTextColor={MarketStyle.colorPrimaryMarket}
                        style={styleId_ZEQ4kQ} />
                    </View>
                  </View>
                  <View style={styleId_Z1mEUzj} >
                    <View style={styleId_Z2boJRP}>
                      <Text allowFontScaling={false} style={styleId_2szJz3} >{esp.lang("market/ads_store_edit", "ads_periode")}</Text>
                      <TouchableOpacity onPress={() => { changePeriode() }} >
                        <LibIcon name='pencil' color='#4a4a4a' />
                      </TouchableOpacity>
                    </View>
                    <View style={{ marginHorizontal: 15 }}>
                      {
                        form?.periode?.start_date != '0000-00-00' ?
                          <Text allowFontScaling={false} style={styleId_Z1y3LM8} >{esp.lang("market/ads_store_edit", "ads_periode_date", form?.periode?.start_date, form?.periode?.end_date)}</Text>
                          :
                          <Text allowFontScaling={false} style={styleId_Z1y3LM8} >{esp.lang("market/ads_store_edit", "ads_periode_unlimited")}</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_store_edit", "ads_daily_cost")}</Text>
                        <Text allowFontScaling={false} style={styleId_Z2jfMeb} >{esp.lang("market/ads_store_edit", "ads_daily_cost_msg")}</Text>
                      </View>
                      <MarketToggle onChangeValue={() => { setDailyOption(!getDailyOption()); setForm('price_daily')('') }} type='success' value={dailyOption} />
                    </View>
                    {
                      dailyOption &&
                      <MarketInput_square
                        prefix={esp.lang("market/ads_store_edit", "daily_prefix")}
                        suffix={esp.lang("market/ads_store_edit", "daily_suffix")}
                        onChangeText={setForm('price_daily')}
                        containerStyle={styleId_2tlMHb}
                        style={styleId_Z9z4Qm}
                      />
                    }
                  </View>

                  <View style={styleId_Z1cCwDB} >
                    <View style={styleId_Z2boJRP}>
                      <Text allowFontScaling={false} style={styleId_2szJz3} >{esp.lang("market/ads_store_edit", "cost_allocation")}</Text>
                      <TouchableOpacity onPress={() => { changeCost() }} >
                        <LibIcon name='pencil' color='#4a4a4a' />
                      </TouchableOpacity>
                    </View>
                    <View style={styleId_Z27iQsf}>
                      {
                        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_store_edit", "cost_unlimited")}</Text>
                      }
                    </View>
                  </View>
                </>
                : null
        }

        <View />
      </LibScroll>
      <View pointerEvents={validPrice ? 'auto' : 'none'} style={styleId_n9VEf}>
        <MarketButton
          colorBackground={!validPrice ? '#aaa' : undefined}
          text={esp.lang("market/ads_store_edit", "btn_save")}
          onPress={() => { doEdit() }}
        />
      </View>
    </View>
  )
}
const styleId_Z2AMgN: any = { flex: 1, backgroundColor: '#f9f9f9' }
const styleId_Z2mwuu4: any = { backgroundColor: 'white' }
const styleId_Z1gA9vX: any = { height: 45, marginBottom: 2, flexDirection: 'row', backgroundColor: '#fff', ...LibStyle.elevation(1) }
const styleId_Z2kI1Fm: any = { height: 42, alignItems: 'center', overflow: 'visible', justifyContent: 'center', backgroundColor: '#fff', paddingHorizontal: 20 }
const styleId_ac2Pw: any = { backgroundColor: 'white', paddingBottom: 15, paddingHorizontal: 15 }
const styleId_Z10AQqI: any = { fontFamily: 'Arial', marginTop: 15, fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: '#4a4a4a' }
const styleId_Z9OFYV: any = { marginTop: 5, fontSize: 13, fontFamily: 'Arial', fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, lineHeight: 18, color: '#949494' }
const styleId_1blyFK: any = { flexDirection: "row", alignItems: "center", borderBottomWidth: 1, borderBottomColor: '#f1f1f1', paddingHorizontal: 10, 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_1IjgdV: any = { fontSize: 12, fontStyle: "normal", letterSpacing: 0, color: '#949494' }
const styleId_1ewN2U: any = { flexDirection: 'row', alignItems: 'center', 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_Z1CjJ0U: any = { backgroundColor: 'white', paddingBottom: 15, paddingHorizontal: 15, marginTop: 10 }
const styleId_ZRsUcC: any = { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginTop: 15, marginBottom: 10 }
const styleId_16tWzX: any = { fontFamily: 'Arial', fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: '#4a4a4a' }
const styleId_1fmvBo: any = { flexDirection: 'row', alignItems: 'center' }
const styleId_wxwT1: any = { marginRight: 5 }
const styleId_1oSw9x: any = { marginHorizontal: 5 }
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_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_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_ZcMJmd: any = { flex: 1 }
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_Z1cCwDB: any = { backgroundColor: 'white', marginTop: 10, paddingVertical: 15, paddingBottom: 20 }
const styleId_Z27iQsf: any = { marginHorizontal: 15 }
const styleId_n9VEf: any = { margin: 15, backgroundColor: 'white' }