// 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 { LibLazy } from 'esoftplay/cache/lib/lazy/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibScroll } from 'esoftplay/cache/lib/scroll/import';
import { LibSkeleton } from 'esoftplay/cache/lib/skeleton/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import { LibStatusbar } from 'esoftplay/cache/lib/statusbar/import';
import { LibStyle } from 'esoftplay/cache/lib/style/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 { MarketDisplay } from 'esoftplay/cache/market/display/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketMerchant_detail_product } from 'esoftplay/cache/market/merchant_detail_product/import';
import { MarketMerchant_labelProperty } from 'esoftplay/cache/market/merchant_label/import';
import { MarketMerchant_label_addProps } from 'esoftplay/cache/market/merchant_label_add/import';
import { MarketMerchant_label_productArgs } from 'esoftplay/cache/market/merchant_label_product/import';
import { MarketNotice } from 'esoftplay/cache/market/notice/import';
import { MarketStore_detail } from 'esoftplay/cache/market/store_detail/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';
import { UserClass } from 'esoftplay/cache/user/class/import';

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

export interface MarketMerchant_detailArgs {
  url: string,
  tabIndex?: number
}

export interface MarketMerchant_detailProps {
}

export default function m(props: MarketMerchant_detailProps): any {
  const { url, tabIndex } = LibNavigation.getArgsAll<MarketMerchant_detailArgs>(props)
  const user = UserClass.state().get()
  const [merchant, setMerchant] = useSafeState<any>()
  const [productList, setProductList] = useSafeState<any>()
  const [indexData, setIndexData] = useSafeState(tabIndex || 2)
  const [error, setError] = useSafeState('')
  const bgHeight = 180
  const sliding = useRef<LibSlidingup>(null)
  const [item, setItem] = useSafeState<any>()
  const [label, setLabel] = MarketMerchant_labelProperty.state().useState()

  useEffect(() => {
    MarketMerchant_labelProperty.list()
    load()
  }, [])

  function load() {
    new LibCurl(url, null,
      (res) => {
        setMerchant(res)
        getProduct(res.id)
      },
      (err) => {
        esp.log(err);
      }, 1)
  }

  function getProduct(merchant_id: string) {
    new LibCurl("shop/product_list?merchant_id=" + merchant_id + "&page=0&limit=4", null,
      (res) => {
        setProductList(res.list)
      }, (msg) => {
        setError(msg?.message)
      }, 1
    )
  }

  function Item(props: any) {
    return (
      <TouchableOpacity onPress={props.onPress}
        activeOpacity={1} style={{ alignItems: "center", paddingBottom: 10, borderBottomWidth: 4, borderBottomColor: indexData == props.id ? MarketStyle.colorPrimaryMarket : "#f5f5f5", flex: 1 }} >
        <LibIcon name={props.icon} size={25} color={indexData == props.id ? MarketStyle.colorPrimaryMarket : "#03192a"} />
        <Text allowFontScaling={false} style={{ marginTop: 5, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0 }} >{props.title}</Text>
      </TouchableOpacity>
    )
  }

  function followMerchant(follow: 0 | 1) {
    let url = follow == 1 ? 'shop/merchant_favorite_remove' : 'shop/merchant_favorite_add'
    new LibCurl(url, { merchant_id: merchant.id },
      (res, msg) => {
        setMerchant((t: any) => LibObject.set(t, follow == 0 ? 1 : 0)('followed'))
      }, (err) => {
        LibToastProperty.show(err?.message)
      }, 1
    )
  }

  const ActiveView = [MarketStore_detail, MarketDisplay, MarketMerchant_detail_product][indexData]

  if (!merchant) {
    return (
      <View style={{ flex: 1, backgroundColor: 'white' }} >
        <LibSkeleton>
          <LibStatusbar style="dark" />
          <View style={{ paddingTop: LibStyle.STATUSBAR_HEIGHT, borderBottomColor: "#ddd", flexDirection: "row", alignItems: "center" }} >
            <Pressable onPress={() => LibNavigation.back()} style={{ alignItems: "center", justifyContent: "center", height: 50, width: 50 }} >
              <LibIcon name="arrow-left" />
            </Pressable>
            <View style={{ flex: 1, marginLeft: 10 }} >
              <View style={{ width: '30%', height: 20, backgroundColor: 'white', borderRadius: 10 }} />
              <View style={{ marginTop: 5, width: '40%', height: 15, backgroundColor: 'white', borderRadius: 10 }} />
            </View>
          </View>
          <View style={{ borderRadius: 41, height: 84, width: 84, alignSelf: 'center', marginTop: 30, backgroundColor: 'white' }} />
          <View style={{ borderWidth: 1, borderRadius: 5, marginHorizontal: 16, padding: 15, alignItems: 'center', paddingTop: 45, marginTop: -35 }} >
            <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 10 }} >
              <View style={{ backgroundColor: 'white', width: 100, height: 20, borderRadius: 10 }} />
              <View style={{ width: 22, height: 22, borderRadius: 11, backgroundColor: 'white', marginLeft: 5 }} />
            </View>
            <View style={{ backgroundColor: 'white', width: '30%', height: 15, borderRadius: 7.5, marginBottom: 5 }} />
            <View style={{ backgroundColor: 'white', width: '60%', height: 15, borderRadius: 7.5, marginBottom: 5 }} />
            <View style={{ backgroundColor: 'white', width: '30%', height: 15, borderRadius: 7.5 }} />
          </View>
          <View style={{ flexDirection: 'row', alignItems: 'center', paddingTop: LibStyle.STATUSBAR_HEIGHT }}>
            <View style={{ alignItems: "center", paddingBottom: 10, borderBottomWidth: 4, flex: 1 }} >
              <LibIcon name="home" size={25} />
              <View style={{ marginTop: 5, width: '50%', height: 15, borderRadius: 10, backgroundColor: 'white' }} />
            </View>
            <View style={{ alignItems: "center", paddingBottom: 10, borderBottomWidth: 4, flex: 1 }} >
              <LibIcon name="format-list-bulleted" size={25} />
              <View style={{ marginTop: 5, width: '50%', height: 15, borderRadius: 10, backgroundColor: 'white' }} />
            </View>
            <View style={{ alignItems: "center", paddingBottom: 10, borderBottomWidth: 4, flex: 1 }} >
              <LibIcon name="package" size={25} />
              <View style={{ marginTop: 5, width: '50%', height: 15, borderRadius: 10, backgroundColor: 'white' }} />
            </View>
          </View>
          <View style={{ marginTop: 20, paddingVertical: 15, borderTopWidth: 0.5 }}>
            <View style={{ width: '30%', height: 20, borderRadius: 10, backgroundColor: 'white', marginHorizontal: 17, marginBottom: 5 }} />
            <View style={{ width: '40%', height: 20, borderRadius: 10, backgroundColor: 'white', marginHorizontal: 17 }} />
          </View>
          <View style={{ paddingVertical: 15, borderTopWidth: 0.5, borderBottomWidth: 0.5 }}>
            <View style={{ width: '30%', height: 20, borderRadius: 10, backgroundColor: 'white', marginHorizontal: 17, marginBottom: 5 }} />
            <View style={{ width: '40%', height: 20, borderRadius: 10, backgroundColor: 'white', marginHorizontal: 17 }} />
          </View>
        </LibSkeleton>
      </View>
    )
  }

  return (
    <LibLazy>
      <View style={{ flex: 1 }} >
        <LibScroll
          onRefresh={load}
          stickyHeaderIndices={[3]} >
          <View>
            <MarketHeader
              rightIcon={{
                name: 'share-variant', onPress: () => {
                  LibUtils.share(merchant.url_share)
                }
              }}
              title={user?.id == merchant?.user_id ? esp.lang("market/merchant_detail", "header_title") : merchant?.title} subtitle={user?.id == merchant?.user_id ? esp.lang("market/merchant_detail", "header_subtitle_mine") : esp.lang("market/merchant_detail", "header_subtitle")} onlyBack style={{ borderBottomWidth: undefined, zIndex: 1 }} />

            <LibPicture source={esp.assets('market/slider_section.png')} resizeMode="cover" style={{ marginTop: -(66 + LibStyle.STATUSBAR_HEIGHT), height: bgHeight, width: LibStyle.width, backgroundColor: MarketStyle.colorPrimaryMarket }} />
          </View>
          <View style={[{ marginBottom: 1, backgroundColor: "white", marginHorizontal: 17, padding: 15, alignItems: "center", marginTop: -30, borderRadius: 5 }, LibStyle.elevation(1)]} >
            <View style={{ flexDirection: 'row' }} >
              <View style={{ flex: 1 }} />
              <LibPicture source={{ uri: merchant?.image }} style={{ marginTop: -55, height: 80, width: 80, borderRadius: 40, borderWidth: 3, borderColor: "white" }} />
              <View style={{ flex: 1 }} >
                {
                  (user?.id != merchant?.user_id) ?
                    <TouchableOpacity onPress={() => { followMerchant(merchant.followed) }} hitSlop={{ top: 5, bottom: 5, right: 5, left: 5 }} style={{ marginLeft: 20, flexDirection: 'row', alignItems: 'center', borderRadius: 5, paddingHorizontal: 10, paddingVertical: 5, backgroundColor: LibUtils.hexToRgba(MarketStyle.colorPrimaryMarket, 0.2) }} >
                      <LibIcon name={merchant.followed == 1 ? "close" : "plus"} size={16} />
                      <Text>{esp.lang("market/merchant_detail", "text_favorite")}</Text>
                    </TouchableOpacity>
                    : null
                }
              </View>
            </View>
            <View style={{ flexDirection: "row", alignItems: "center", paddingVertical: 5, justifyContent: "center" }} >
              <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#03192a" }} >{merchant?.title}</Text>
              {
                user?.id == merchant?.user_id &&
                <TouchableOpacity onPress={() => { LibNavigation.navigate('market/merchant_edit') }} style={{ marginLeft: 5 }} >
                  <LibIcon name="pencil-outline" size={16} />
                </TouchableOpacity>
              }
            </View>
            {
              user?.id == merchant?.user_id ?
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", textAlign: "center", fontSize: 10, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, lineHeight: 18, color: "#d1d1d1" }} >{merchant?.address + "\n" + merchant?.location_name + ' ' + merchant?.zipcode}</Text>
                :
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", textAlign: "center", fontSize: 10, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, lineHeight: 18, color: "#d1d1d1" }} >{merchant?.location_name}</Text>
            }
            {
              user?.id == merchant?.user_id &&
              <View style={{ flexDirection: "row", alignItems: "center", paddingTop: 3 }} >
                <LibIcon name="cellphone" color="#d1d1d1" size={12} />
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 10, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#d1d1d1" }} >{merchant?.phone}</Text>
              </View>
            }
          </View>
          <View>
            {
              user?.id == merchant?.user_id ?
                <>
                  {
                    LibUtils.checkUndefined(merchant, 'alert.0') && merchant?.alert?.map((item: any, i: number) => (
                      <MarketNotice key={i} mode={item.type} text={item.message} canPress={item.module != '' && item.url != ''} onPress={() => {
                        if (item?.module != '') {
                          LibNavigation.navigate(item?.module, { url: item?.url })
                        }
                      }} />
                    ))
                  }
                </>
                :
                <>
                  {
                    LibUtils.checkUndefined(merchant, 'info.0') && merchant?.info?.map((item: any, i: number) => (
                      <MarketNotice key={i} mode={item.type} text={item.message} canPress={item.module != '' && item.url != ''} onPress={() => {
                        if (item?.module != '') {
                          LibNavigation.navigate(item?.module, { url: item?.url })
                        }
                      }} />
                    ))
                  }
                </>
            }
          </View>
          <View style={{ flexDirection: "row", backgroundColor: "white", paddingTop: LibStyle.STATUSBAR_HEIGHT }} >
            <Item onPress={() => { setIndexData(0) }} id={0} icon={'home'} title={esp.lang("market/merchant_detail", "text_merchant")} />
            {
              user?.id == merchant?.user_id &&
              <Item onPress={() => { setIndexData(1) }} id={1} icon={'format-list-bulleted'} title={esp.lang("market/merchant_detail", "text_display")} />
            }
            <Item onPress={() => { setIndexData(2) }} id={2} icon={'package'} title={esp.lang("market/merchant_detail", "text_product")} />
          </View>
          <View style={{ flex: 1 }} >
            <ActiveView merchant={merchant} vouchers={merchant?.vouchers} onPressOption={(x: any) => {
              setItem(x)
              sliding.current?.show()
            }} />
          </View>
        </LibScroll>
        {
          (indexData == 0 && user?.id == merchant?.user_id) ?
            <>
              {
                esp.isDebug('') ?
                  <View style={{ flexDirection: "row", justifyContent: "space-between", marginVertical: 5 }} >
                    <View style={{ width: LibStyle.width * 0.5 }}>
                      <MarketButton
                        textStyle={{ color: "white" }}
                        onPress={() => LibToastProperty.show(esp.lang("market/merchant_detail", "feature_not_available"))}
                        text={esp.lang("market/merchant_detail", "text_upgrade")}
                        buttonStyle={{ borderRadius: 20, marginRight: 5, marginLeft: 10 }} />
                    </View>
                    <View style={{ width: LibStyle.width * 0.5 }}>
                      <MarketButton
                        textStyle={{ color: "white" }}
                        onPress={() => { LibNavigation.navigate('market/merchant_edit') }}
                        text={esp.lang("market/merchant_detail", "text_edit")}
                        buttonStyle={{ borderRadius: 20, marginLeft: 5, marginRight: 10 }} />
                    </View>
                  </View>
                  :
                  <MarketButton
                    textStyle={{ color: "white" }}
                    onPress={() => { LibNavigation.navigate('market/merchant_edit') }}
                    text={esp.lang("market/merchant_detail", "text_edit1")}
                    buttonStyle={{ borderRadius: 20, marginHorizontal: 15, marginVertical: 10 }} />
              }
            </>
            :
            (indexData == 1 && user?.id == merchant?.user_id && LibUtils.checkUndefined(label, '0')) ?
              <MarketButton onPress={() => { LibNavigation.navigate('market/merchant_label_add') }} text={esp.lang("market/merchant_detail", "add_display")} textStyle={{ color: "#f1f1f1" }} buttonStyle={{ borderRadius: 20, marginHorizontal: 15, marginVertical: 10 }} />
              :
              (indexData == 2 && user?.id == merchant?.user_id && LibUtils.checkUndefined(productList, '0')) ?
                <MarketButton onPress={() => { LibNavigation.navigate('market/product_add') }} text={esp.lang("market/merchant_detail", "add_product")} textStyle={{ color: "#f1f1f1" }} buttonStyle={{ borderRadius: 20, marginHorizontal: 15, marginVertical: 10 }} />
                :
                null
        }
        <LibSlidingup ref={sliding} >
          <View style={{ backgroundColor: 'white', borderTopLeftRadius: 15, borderTopRightRadius: 15 }} >
            <View style={{ flexDirection: 'row', alignItems: 'center', padding: 10 }} >
              <TouchableOpacity onPress={() => sliding.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" }} >{item?.title}</Text>
            </View>
            <View style={{ marginHorizontal: 10 }} >
              <TouchableOpacity onPress={() => {
                sliding.current?.hide()
                LibNavigation.navigate<MarketMerchant_label_productArgs>('market/merchant_label_product', { ...item })
              }} style={{ flexDirection: 'row', alignItems: 'center', padding: 10 }} >
                <LibIcon name="plus-thick" color={MarketStyle.colorPrimaryMarket} style={{ marginRight: 15 }} />
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 11, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/merchant_detail", "slide_add_product")}</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => {
                sliding.current?.hide()
                LibNavigation.navigate<MarketMerchant_label_addProps>('market/merchant_label_add', { ...item })
              }} style={{ flexDirection: 'row', alignItems: 'center', padding: 10 }} >
                <LibIcon name="square-edit-outline" color={MarketStyle.colorPrimaryMarket} style={{ marginRight: 15 }} />
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 11, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/merchant_detail", "edit_display")}</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => {
                sliding.current?.hide()
                LibDialog.warningConfirm(esp.lang("market/merchant_detail", "del_title", item?.title), esp.lang("market/merchant_detail", "del_msg"), esp.lang("market/merchant_detail", "dell_ok"), () => {
                  MarketMerchant_labelProperty.del(item.id, MarketMerchant_labelProperty.list)
                }, esp.lang("market/merchant_detail", "dell_cancel"), () => { })
              }} style={{ flexDirection: 'row', alignItems: 'center', padding: 10 }} >
                <LibIcon name="delete" color={MarketStyle.colorPrimaryMarket} style={{ marginRight: 15 }} />
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 11, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "left", color: "#03192a" }} >{esp.lang("market/merchant_detail", "delete_display")}</Text>
              </TouchableOpacity>
            </View>
          </View>
        </LibSlidingup>
      </View>
    </LibLazy>
  )
}