// withHooks

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 { LibInfinite } from 'esoftplay/cache/lib/infinite/import';
import { LibInput } from 'esoftplay/cache/lib/input/import';
import { LibKeyboard_avoid } from 'esoftplay/cache/lib/keyboard_avoid/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/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 { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { MarketEmpty } from 'esoftplay/cache/market/empty/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketProduct_discuss_item } from 'esoftplay/cache/market/product_discuss_item/import';
import { MarketSlidingupProperty } from 'esoftplay/cache/market/slidingup/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';
import { UserClass } from 'esoftplay/cache/user/class/import';
import esp from 'esoftplay/esp';
import moment from 'esoftplay/moment';
import useSafeState from 'esoftplay/state';

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


export interface MarketProduct_discuss_reply_detailArgs {

}
export interface MarketProduct_discuss_reply_detailProps {

}
export default function m(props: MarketProduct_discuss_reply_detailProps): any {
  // fromPage : market/product_discuss
  const { url, data, fromPage } = LibNavigation.getArgsAll<any>(props)
  const user = UserClass.state().useSelector(s => s)
  let textMsg = useRef('').current
  const input = useRef<LibInput>(null)
  const [upData, setUpData, getUpData] = useSafeState<any>([])
  const [selectedProduct, setSelectedProduct, getSelectedProduct] = useSafeState<any>([])


  // esp.log(selectedProduct.map((item: any) => item.id).join(','), "selectedProduct");

  useEffect(() => {
    MarketSlidingupProperty.add(
      <View style={{ backgroundColor: "white", borderTopLeftRadius: 15, borderTopRightRadius: 15 }} >
        <View style={{ margin: 20 }}>
          <LibTextstyle textStyle="headline" text={esp.lang("market/product_discuss_reply_detail", "report")} style={{ marginTop: 10, marginBottom: 10 }} />
        </View>
      </View>
    )
  })

  function sendDiscuss() {
    if (textMsg == "") {
      LibToastProperty.show(esp.lang("market/product_discuss_reply_detail", "empty"))
      return null
    }

    let post = {
      product_id: data?.product_id,
      par_id: data?.id,
      message: textMsg,
      attach: getSelectedProduct().map((item: any) => item.id).join(',')
    }

    let newMsg = {
      "created": moment().localeFormat("YYYY-MM-DD hh:mm:ss"),
      "is_merchant": user?.merchant_id == data?.merchant_id ? 1 : 0,
      "message": textMsg,
      "par_id": data?.par_id,
      "topic_id": data?.topic_id,
      "user_id": user?.id,
      "user_image": user?.image,
      "user_name": user?.name,
      "attach": getSelectedProduct()
    }

    let _upData = [...getUpData()]
    _upData.push(newMsg)
    setUpData([..._upData])

    new LibCurl('shop/product_list_detail_discussion_post', post, (res, msg) => {

      // esp.log(res, msg, "res, msg");
      input.current?.setText('')
      setSelectedProduct([])
    }, (error) => {

      LibDialog.warning(esp.lang("market/product_discuss_reply_detail", "warn"), error?.message);
      esp.log(error);
    }, 1)
  }

  return (
    <LibKeyboard_avoid style={{ flex: 1, backgroundColor: '#fff' }}>
      <MarketHeader onlyBack title={esp.lang("market/product_discuss_reply_detail", "header")} />


      {/* item discuss */}
      <LibInfinite
        url={url}
        // isDebug={1}
        onDataChange={(data: any) => setUpData(data)}
        injectData={upData}
        refreshEnabled={false}
        ListHeaderComponent={
          <>
            {
              fromPage == "market/product_discuss" &&
              <>
                <View style={{ padding: 15, flexDirection: 'row', justifyContent: 'space-between' }}>
                  <View style={{ flexDirection: 'row' }}>
                    <LibPicture source={{ uri: data?.product_image }} style={{ height: 50, width: 50, borderRadius: 10 }} />
                    <View style={{ marginLeft: 10 }}>
                      <LibTextstyle textStyle="caption1" text={data?.product_name} style={{ fontSize: 16, fontWeight: "bold" }} />
                      {
                        data?.stock < 10 &&
                        <LibTextstyle textStyle="caption2" style={{ fontSize: 12, marginTop: 4, color: LibStyle.colorRed, fontWeight: 'bold' }} text={esp.lang("market/product_discuss_reply_detail", "stock_left", LibUtils.number(data?.stock))} />
                      }
                    </View>
                  </View>
                  <TouchableOpacity onPress={() => MarketSlidingupProperty.show()}>
                    <LibIcon.MaterialIcons name="more-vert" color="#c9c9c9" />
                  </TouchableOpacity>
                </View>
                <View style={{ height: 8, width: LibStyle.width, backgroundColor: MarketStyle.colorBgGrey }} />
              </>
            }
            <View style={{ padding: 15, borderBottomWidth: 1, borderBottomColor: "#eee" }}>
              <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
                <View style={{ flexDirection: 'row' }}>
                  <View style={{ height: 30, borderRadius: 15, width: 30, backgroundColor: "#f1f2f3", marginRight: 10, overflow: 'hidden' }} >
                    <LibPicture source={{ uri: data?.user_image }} style={{ width: 30, height: 30, borderRadius: 15 }} resizeMode="contain" />
                  </View>
                  <View>
                    <LibTextstyle textStyle="caption1" text={data?.user_name} style={{ fontWeight: "bold" }} />
                    <LibTextstyle textStyle="caption2" style={{ color: "#888" }} text={moment(data?.created).localeFormat("DD MMMM YYYY hh:mm")} />
                  </View>
                </View>
                <TouchableOpacity onPress={() => MarketSlidingupProperty.show()}>
                  <LibIcon.MaterialIcons name="more-vert" color="#c9c9c9" />
                </TouchableOpacity>
              </View>

              <Text allowFontScaling={false} style={{ flexWrap: 'wrap', marginTop: 10, marginRight: 10, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", lineHeight: 16, letterSpacing: 0, textAlign: "left", color: "#03192a" }}>{data?.message}</Text>
              {/* <LibTextstyle textStyle="caption2" style={{ color: "#888", marginTop: 8}} text={data?.message} /> */}

              <View style={{ marginTop: 10 }}>
                <Text allowFontScaling={false} style={{ fontSize: 10, color: "#c5c5c5" }}>Diskusi adalah tempat kamu bertanya dan kasih jawaban seputar produk. Tetap sopan dan jangan lupa baca S&K</Text>
              </View>

            </View>
            <Text allowFontScaling={false} style={{ margin: 10, marginRight: 10, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", lineHeight: 16, letterSpacing: 0, textAlign: "left", color: "#03192a" }}>{esp.lang("market/product_discuss_reply_detail", "answer", String(Number(Number(data?.total_replies) + 1)))}</Text>
          </>
        }
        errorView={(err: any) => (
          <MarketEmpty msg={err} />
        )}
        renderItem={(item) => {
          return (
            <MarketProduct_discuss_item data={item} isDetailReply={true} />
          )
        }}
      />

      {/* attach produk */}
      <View>
        <ScrollView horizontal>
          <View style={{ flexDirection: 'row' }}>
            {
              selectedProduct?.length > 0 && selectedProduct?.map((item: any, i: number) => {
                return (
                  <View key={i} style={{ marginTop: 10, marginHorizontal: 15, marginRight: 0, borderRadius: 5, backgroundColor: MarketStyle.colorBgGrey, paddingHorizontal: 10, width: LibStyle.width * 0.6 }} >
                    <TouchableOpacity activeOpacity={1} onPress={() => {
                      LibNavigation.navigate('market/product_detail', { url: item?.url })
                    }} >
                      <View style={{ flexDirection: 'row', paddingVertical: 10 }} >
                        <LibPicture source={{ uri: item?.image }} style={{ backgroundColor: '#d1d1d1', height: 40, width: 40, borderRadius: 4 }} />
                        <View style={{ flex: 1, marginLeft: 10, justifyContent: "space-around" }} >
                          <LibTextstyle textStyle='footnote' numberOfLines={1} text={item?.title} ellipsizeMode={'tail'} style={{ fontWeight: 'bold', fontSize: 14 }} />
                          <LibTextstyle textStyle='caption1' text={LibUtils.money(Number(item?.sale)) || ''} style={{ fontSize: 14 }} />
                        </View>
                      </View>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => {
                      selectedProduct.splice(i, 1);
                      setSelectedProduct([...selectedProduct]);
                    }} style={{ position: 'absolute', top: -8, right: -8 }} >
                      <LibIcon name={'close-circle'} color='#d1d1d1' />
                    </TouchableOpacity>
                  </View>
                )
              })
            }
          </View>
        </ScrollView>
      </View>

      <View style={{ flexDirection: 'row', padding: 10, alignContent: 'center', alignItems: 'center' }}>
        <View style={{ flexDirection: 'row', flex: 1, borderWidth: 1, borderColor: '#999', height: 36, borderRadius: 18, justifyContent: 'center' }} >
          <LibInput
            ref={input}
            base
            placeholder={esp.lang("market/product_discuss_reply_detail", "placeholder")}
            onChangeText={(x) => { textMsg = x }}
            multiline
            allowFontScaling={false}
            style={{ flex: 1, marginHorizontal: 10, marginTop: Platform.OS == "ios" ? 3 : 0 }}
          />
          <TouchableOpacity onPress={() => {
            LibNavigation.navigateForResult('market/product_discuss_product_list', { merchant_id: data?.merchant_id }).then((products: any) => {
              setSelectedProduct(products)
            })
          }} activeOpacity={1} style={{ alignItems: 'center', justifyContent: 'center', marginHorizontal: 10 }} >
            <LibIcon name="paperclip" size={20} color='#999' />
          </TouchableOpacity>
        </View>
        <TouchableOpacity onPress={() => {
          if (textMsg != '') {
            sendDiscuss()
            Keyboard.dismiss()
          } else {
            LibToastProperty.show("Silahkan isi pertanyaan")
          }
        }} activeOpacity={1} style={{ marginLeft: 5, alignItems: 'center', justifyContent: 'center' }} >
          <LibIcon name="send-circle" size={40} color={MarketStyle.colorPrimaryMarket} />
        </TouchableOpacity>
      </View>

    </LibKeyboard_avoid>
  )
}