// withHooks
import { useEffect } from 'react';

import { applyStyle } from 'esoftplay';
import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventHtmltext } from 'esoftplay/cache/event/htmltext/import';
import { EventIndexProperty } from 'esoftplay/cache/event/index/import';
import { EventShare } from 'esoftplay/cache/event/share/import';
import { LibCarrousel } from 'esoftplay/cache/lib/carrousel/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/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 { LibVideoProperty } from 'esoftplay/cache/lib/video/import';
import { LibWebview } from 'esoftplay/cache/lib/webview/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import React from 'react';
import { Pressable, RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventArtist_detailv2Args {

}
export interface EventArtist_detailv2Props {

}
export default function m(props: EventArtist_detailv2Props): any {
  const { url, subscribed } = LibNavigation.getArgsAll(props)
  const [priceList, setPriceList] = useSafeState<any>()
  const [detailArtist, setDetailArtist] = useSafeState<any>()

  let showSchedule = React.useRef<LibSlidingup>(null)
  const [, setSelectedTicket, getSelectedTicket] = useSafeState<any[]>([])
  const [showAll, setShowAll] = useSafeState<any>({});
  const [qty, setQty] = useSafeState<any>(1)
  const [refreshing, setRefreshing] = useSafeState<boolean>(false);

  useEffect(() => {
    loadDataArtist()
  }, [])

  // esp.log({ priceList, detailArtist });

  function loadDataArtist(): void {
    new LibCurl(url, null, (res) => {
      esp.log({ res, url });
      setRefreshing(false)
      setDetailArtist(res)
      loadDataPrice(res?.url_price)
    }, (err) => {
      setRefreshing(false)
      LibToastProperty.show(err?.message)
      LibNavigation.back()
    }, 1)
  }

  function loadDataPrice(url: string) {
    new LibCurl(url, null, (res, msg) => {

      const updatedData = res?.map((item: any) => ({
        ...item,
        list: item?.list?.map((itemList: any) => ({
          ...itemList,
          index_id: item?.price_id + "-" + itemList?.ondate
        }))
      }));

      setPriceList(updatedData)
    }, (err) => {
      LibToastProperty.show(err?.message)
      LibNavigation.back()
    }, 1)
  }

  function loadDataPriceConfig(url: string) {
    let post = {
      price_ids: "1",
      event_id: 443
    }
    LibProgress.show("Mohon tunggu")
    new LibCurl(url, post, (res, msg) => {
      esp.log({ res, url });
      LibProgress.hide()
    }, (err) => {
      LibProgress.hide()
      LibToastProperty.show(err?.message)

    }, 1)
  }

  const maxDisplay = 3;
  const handleShowAll = (price_id: any) => {
    setShowAll((prevShowAll: any) => ({
      ...prevShowAll,
      [price_id]: !prevShowAll[price_id],
    }));
  };


  // function add(): void {
  //   let hasQuota = getSelectedTicket().quota > 0
  //   const min = hasQuota ? Number(getSelectedTicket()?.quota) - Number(getSelectedTicket()?.quota_used) : Number(getSelectedTicket()?.qty_max)
  //   if (qty < Math.min(min, Number(getSelectedTicket()?.qty_max))) {
  //     setQty(Number(qty) + 1)
  //   }
  // }

  // function min(): void {
  //   if (qty <= getSelectedTicket()?.qty_min) {
  //     setQty(Number(getSelectedTicket()?.qty_min))
  //   } else {
  //     setQty(qty == 1 ? 1 : qty - 1)
  //   }
  // }

  function onRefresh() {
    setRefreshing(true)
    loadDataArtist()
  }

  function selectTicket(priceTypeItem: any, ticket: any, isMultiple: number) {
    const selectedData = {
      ...ticket,
      qty: Number(priceTypeItem.qty_min),
      qty_min: Number(priceTypeItem?.qty_min),
      qty_max: Number(priceTypeItem?.qty_max),
      list_id: ticket.list_id,
      subtotal: Number(ticket.price) * Number(priceTypeItem.qty_min),
      type: priceTypeItem?.type,
      tax: priceTypeItem?.tax,
      term: priceTypeItem?.term,
      has_addition: priceTypeItem?.has_addition,
      image_map: priceTypeItem?.image_map,
      use_seat: priceTypeItem?.use_seat,
      adjacent_seats: priceTypeItem?.config?.seat_autopick,
      fee_amount: priceTypeItem?.fee_amount,
      fee_type: priceTypeItem?.fee_type,
      // event_id: availableResult?.id
    }

    setSelectedTicket((prev: any) => {
      const alreadySelected = prev.some((x: any) => x.list_id == ticket.list_id)

      // SINGLE
      if (isMultiple != 1) {

        // klik lagi = unselect
        if (alreadySelected) {
          return []
        }

        // replace semua
        return [selectedData]
      }

      // MULTIPLE
      // remove
      if (alreadySelected) {
        return prev.filter((x: any) => x.list_id != ticket.list_id)
      }

      // add
      return [...prev, selectedData]
    })
  }

  function getTicketStatusMessage(priceTypeItem: any, ticket: any) {
    const status = priceTypeItem.status != 1 ? priceTypeItem.status : ticket.status

    switch (status) {
      case 2:
        return "Segera Hadir"

      case 0:
        return "Habis terjual"

      default:
        return ""
    }
  }

  function renderItem(itemC: any, iC: any, item: any) {
    let ticketWithDate = item.price_date == 1 && item.use_code == 0
    let ticketSpecial = item.price_date == 0 && item.use_code == 0

    // let _selectedTicket = item.price_id == selectedTicket?.price_id && itemC?.index_id == selectedTicket?.list?.index_id
    let _selectedTicket = getSelectedTicket()?.find((x: any) => x.list_id == itemC.list_id)
    // const qty = _selectedTicket?.qty || 0
    let isMultiple = 1


    let colorDefault = _selectedTicket ? "#FFE9AD" : '#fff'
    let colorBackground = item?.status != 1 ? LibStyle.colorLightGrey : itemC?.status != 1 ? LibStyle.colorLightGrey : colorDefault
    let textOpacity = /* item?.status == 1 ? 1 : */ itemC?.status == 1 ? 1 : 0.3

    return (
      <TouchableOpacity
        onPress={() => {
          const isAvailable = item.status == 1 && itemC.status == 1

          if (!isAvailable) {
            LibToastProperty.show(getTicketStatusMessage(item, itemC))
            return
          }
          selectTicket(item, itemC, isMultiple)


        }} activeOpacity={itemC?.status == 1 ? 0 : 1} key={iC} style={{ flex: 1, flexDirection: 'row', backgroundColor: colorBackground, justifyContent: 'space-between', padding: 10, alignItems: 'center' }}>
        {
          itemC?.ondate == "0000-00-00" ?
            <LibPicture source={esp.assets('icons/ic_special2.png')} style={{ height: 42, width: 42 }} />
            :
            <>
              <View style={applyStyle({ marginLeft: 10, marginHorizontal: 20, width: 42, height: 42, borderRadius: 5, backgroundColor: "#fff", borderStyle: "solid", borderWidth: 1, borderColor: _selectedTicket ? "#3ea4dc" : '#999', alignContent: 'center', alignItems: 'center', justifyContent: 'center' })}>
                <Text allowFontScaling={false} style={applyStyle({ opacity: textOpacity, fontFamily: "Arial", fontSize: 20, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0.23, textAlign: "center", color: _selectedTicket ? "#3ea4dc" : '#999' })}>{LibUtils.moment(itemC?.ondate).localeFormat('DD')}</Text>
              </View>
              <View style={applyStyle({ flexDirection: 'column', flex: 1 })}>
                {
                  item?.status == 1 && itemC?.status != 1 &&
                  <View style={applyStyle({ flexDirection: 'row', marginBottom: 5 })}>
                    <View style={applyStyle({ alignContent: 'center', alignItems: 'center', justifyContent: 'center', marginTop: 5, borderWidth: 1, backgroundColor: itemC?.status == 0 ? LibStyle.colorRed : "#4cd964", borderColor: itemC?.status == 0 ? LibStyle.colorRed : "#4cd964", borderRadius: 5, padding: 3, opacity: 0.8 })}>
                      <Text allowFontScaling={false} style={applyStyle({ fontSize: 10, fontStyle: "normal", letterSpacing: 0, color:/*  itemC?.status == 2 ? "#000" :  */"#fff", fontWeight: 'bold' })}>{itemC?.status == 0 ? esp.lang("event/artist_detail", "sold_out") : esp.lang("event/artist_detail", "coming_soon")}</Text>
                    </View>
                  </View>
                }
                <Text allowFontScaling={false} style={applyStyle({ opacity: textOpacity, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectedTicket ? "#3ea4dc" : '#999' })}>{LibUtils.moment(itemC?.ondate).localeFormat('dddd')}</Text>
                <View style={applyStyle({ flexDirection: 'row' })}>
                  <Text allowFontScaling={false} style={applyStyle({ opacity: textOpacity, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectedTicket ? "#3ea4dc" : '#999' })}>{LibUtils.moment(itemC?.ondate).localeFormat('MMMM')}</Text>
                  <Text allowFontScaling={false} style={applyStyle({ opacity: textOpacity, marginLeft: 7, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: _selectedTicket ? "#3ea4dc" : '#999' })}>{LibUtils.moment(itemC?.ondate).localeFormat('YYYY')}</Text>
                </View>
              </View>
            </>
        }

        <View style={applyStyle({ marginRight: 5, marginLeft: 5, flexDirection: 'column' })} >
          {
            (itemC?.status == 1 || itemC?.status == 0) &&
            <Text allowFontScaling={false} style={applyStyle({ opacity: ticketWithDate ? textOpacity : 1, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, textAlign: "right", color: _selectedTicket ? "#3ea4dc" : (itemC?.price == 0 ? LibStyle.colorGreen : '#999') })} >{itemC?.price == 0 ? esp.lang("event/ticket_list", "free") : LibUtils.money(itemC?.price, item.currency)}</Text>
          }
          {
            item?.status == 1 && (ticketWithDate || ticketSpecial) && _selectedTicket &&
            <View style={applyStyle({ marginTop: 4, flexDirection: 'row', marginLeft: 8, alignContent: 'center', alignItems: 'center' })}>
              <TouchableOpacity onPress={() => { /* min() */ }}>
                <View style={applyStyle({ width: 28, height: 28, borderRadius: 6, backgroundColor: "#ecf0f1", alignContent: 'center', alignItems: 'center' })}>
                  <LibIcon name="minus" color="#e74c3c" />
                </View>
              </TouchableOpacity>
              <Text style={applyStyle({ fontFamily: "Arial", fontSize: 20, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#9b9b9b", marginLeft: 13, marginRight: 13 })}>{qty}</Text>
              <TouchableOpacity onPress={() => { /* add() */ }}>
                <View style={applyStyle({ width: 28, height: 28, borderRadius: 6, backgroundColor: "#ecf0f1", alignContent: 'center', alignItems: 'center' })}>
                  <LibIcon name="plus" color="#16a085" />
                </View>
              </TouchableOpacity>
            </View>
          }
        </View>
      </TouchableOpacity>
    )
  }

  const bgHeight = LibStyle.width * 9 / 16

  function renderImages(item: any, i: number) {
    const styleId_Z1ecB7O: any = { height: bgHeight, width: LibStyle.width, resizeMode: 'cover' }
    return (
      <TouchableOpacity key={i} onPress={() => LibNavigation.navigate('lib/gallery', { images: detailArtist?.images, index: i })}>
        <LibPicture source={{ uri: item.image }} style={styleId_Z1ecB7O} />
      </TouchableOpacity>
    )
  }

  let share = [
    {
      icon: 'icons/ic_facebook.png',
      title: 'Facebook',
      onPress: () => { EventShare.facebook(url) }
    },
    {
      icon: 'icons/ic_whatsapp.png',
      title: 'Whatsapp',
      onPress: () => { EventShare.whatsapp(url) }
    },
    {
      icon: 'icons/ic_twitter.png',
      title: 'Twitter',
      onPress: () => { EventShare.twitter(url) }
    },
    {
      icon: 'icons/ic_copy.png',
      title: esp.lang("event/artist_detail", "copy"),
      onPress: () => {
        LibUtils.copyToClipboard(url).then((v) => {
          LibToastProperty.show(esp.lang("event/artist_detail", "alert"))
        })
      }
    },
  ]

  function renderShare(item: any, i: number) {
    return (
      <View key={i} style={applyStyle({ marginRight: 10 })}>
        <TouchableOpacity onPress={item.onPress} >
          <LibPicture style={applyStyle({ resizeMode: 'contain', height: 25, width: 25, borderRadius: 12.5, backgroundColor: 'white' })} source={esp.assets(item.icon)} />
        </TouchableOpacity>
      </View>
    )
  }

  return (
    <View style={{ flex: 1 }}>
      <EventHeader title={esp.lang("event/artist_detail", "title")} subtitle={detailArtist?.name} />
      <ScrollView refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
      }>

        {
          detailArtist?.images && detailArtist?.images?.length > 0 ?
            <LibCarrousel
              delay={3000}
              style={{ height: bgHeight, width: LibStyle.width }}
              autoplay
              bullets
              bulletStyle={{ width: 7, height: 7, backgroundColor: "#fff", borderRadius: 3.5, borderWidth: 0, marginHorizontal: 2 }}
              chosenBulletStyle={{ width: 7, height: 7, backgroundColor: "#f4e31b", borderRadius: 3.5, borderWidth: 0, marginHorizontal: 2 }}
              bulletsContainerStyle={{ marginBottom: -10 }}>
              {
                detailArtist?.images && detailArtist?.images?.map(renderImages)
              }
            </LibCarrousel>
            :
            <Pressable onPress={() => LibNavigation.navigate('lib/gallery', { image: detailArtist?.image })} >
              <LibPicture
                style={applyStyle({ height: LibStyle.width * 9 / 16, width: LibStyle.width, backgroundColor: '#f2f3f4' })}
                source={{ uri: detailArtist?.image }} />
            </Pressable>
        }
        <View style={applyStyle({ marginTop: 10, marginLeft: 17, flexDirection: 'row' })}>
          {
            share.map(renderShare)
          }
        </View>
        <Text allowFontScaling={false} style={applyStyle({ marginBottom: 12, marginLeft: 17, fontFamily: "Arial", marginTop: 20, fontSize: 26, fontWeight: "bold", fontStyle: "normal", lineHeight: 30, letterSpacing: 0, color: "#000" })}>{detailArtist?.name}</Text>
        {
          detailArtist?.description != "" &&
          <ScrollView>
            <LibWebview onFinishLoad={() => { }} source={{ html: detailArtist?.description }} />
          </ScrollView>
        }
        {
          detailArtist?.video != "" &&
          <>
            <Text allowFontScaling={false} style={applyStyle({ marginHorizontal: 20, marginTop: 10, fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: "#4a4a4a" })} >{esp.lang("event/artist_detail", "video")}</Text>
            <TouchableOpacity onPress={() => LibNavigation.navigate('lib/video', { code: detailArtist?.video })} >
              <LibPicture source={{ uri: LibVideoProperty.getUrlThumbnail(detailArtist?.video) }} style={applyStyle({ height: LibStyle.width * 9 / 16, width: LibStyle.width - 40, marginHorizontal: 20, resizeMode: 'cover' })} />
            </TouchableOpacity>
          </>
        }


      </ScrollView>
      <View style={{ flexDirection: 'row', padding: 10, backgroundColor: 'white' }} >
        <EventButton label={esp.lang("event/artist_detail", "buy_ticket")} onPress={() => {
          EventIndexProperty.isLogin(() => {
            showSchedule.current?.show()
          })
        }} style={{ backgroundColor: LibStyle.colorGreen }} />
      </View>

      <LibSlidingup ref={showSchedule}>
        <View style={applyStyle({ backgroundColor: 'white', borderTopRightRadius: 30, borderTopLeftRadius: 30, paddingTop: 15, maxHeight: LibStyle.height - (LibStyle.height / 3) })}>
          <Text allowFontScaling={false} style={applyStyle({ marginBottom: 15, fontFamily: "Arial", fontSize: 16, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, textAlign: "center", color: "#34495e" })}>{esp.lang("event/artist_detail", "select_date")}</Text>
          <ScrollView showsVerticalScrollIndicator={false} >
            {
              priceList?.map((priceType: any, i: number) => {
                let filterFullData = priceList?.filter((it: any) => it.status != 0)
                const displayedData = showAll[priceType.price_id] ? priceType?.list : priceType?.list.slice(0, maxDisplay);
                let textOpacity = priceType?.status == 1 ? 1 : 0.3
                let _selectedTicket = getSelectedTicket()?.some((x: any) => x.price_id == priceType.price_id)

                return (
                  <View key={i} style={{ overflow: 'hidden', margin: 15, marginBottom: 5, backgroundColor: '#fff', borderRadius: 10, ...LibStyle.elevation(2), borderWidth: 1, borderColor: _selectedTicket ? LibStyle.colorBlue : LibStyle.colorBgGrey }}>
                    <View style={{ padding: 10, backgroundColor: '#f1f2f3', borderTopLeftRadius: 10, borderTopRightRadius: 10 }}>
                      <View style={{ alignContent: 'center', alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between', }}>
                        <EventHtmltext allowFontScaling={false} style={{ opacity: textOpacity, fontWeight: 'bold' }}>{priceType.name}</EventHtmltext>
                        {
                          priceType.qty_min > 1 &&
                          <Text style={{ color: LibStyle.colorRed, fontSize: 10, fontWeight: 'normal' }}> {"(" + esp.lang("event/ticket_list", "min_order") + LibUtils.number(priceType.qty_min) + ")"}</Text>
                        }
                        {
                          priceType?.status != 1 &&
                          <View style={applyStyle({ flexDirection: 'row' })}>
                            <View style={applyStyle({ alignContent: 'center', alignItems: 'center', justifyContent: 'center', borderWidth: 1, backgroundColor: priceType?.status == 0 ? LibStyle.colorRed : "#4cd964", borderColor: priceType?.status == 0 ? LibStyle.colorRed : "#4cd964", borderRadius: 5, padding: 3, opacity: 0.8 })}>
                              <Text allowFontScaling={false} style={applyStyle({ fontSize: 10, fontStyle: "normal", letterSpacing: 0, color: /* priceType?.status == 2 ? "#000" : */ "#fff", fontWeight: 'bold' })}>{priceType?.status == 0 ? esp.lang("event/artist_detail", "sold_out") : esp.lang("event/artist_detail", "coming_soon")}</Text>
                            </View>
                          </View>
                        }
                      </View>
                      {
                        priceType.hasOwnProperty("price_type_info") && priceType.price_type_info != "" &&
                        <View style={{ marginTop: 3, alignContent: 'center', alignItems: 'center', flexDirection: 'row', marginRight: 5 }}>
                          <Text allowFontScaling={false} style={{ fontSize: 12, color: LibStyle.colorBlue }}>{priceType.price_type_info}</Text>
                        </View>
                      }
                    </View>

                    {
                      displayedData?.map((itemC: any, iC: number) => renderItem(itemC, iC, priceType))
                    }
                    {
                      filterFullData?.[i]?.list?.length > 3 &&
                      <TouchableOpacity onPress={() => {
                        handleShowAll(priceType.price_id)
                      }} style={{ borderTopColor: LibStyle.colorGrey, borderTopWidth: 0.8, flex: 1, padding: 8, flexDirection: 'row', alignContent: 'center', alignItems: 'center', justifyContent: 'center' }}>
                        <Text allowFontScaling={false} style={{ marginRight: 5, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: LibStyle.colorBlue }}>{showAll[priceType.price_id] ? esp.lang("event/ticket_list", "see_less") : esp.lang("event/ticket_list", "see_more")}</Text>
                        <LibIcon name={showAll[priceType.price_id] ? 'chevron-up-circle-outline' : 'chevron-down-circle-outline'} color={LibStyle.colorBlue} size={18} />
                      </TouchableOpacity>
                    }

                  </View>
                )
              })
            }
          </ScrollView>
          <View style={applyStyle({ paddingVertical: 10 })} >
            <EventButton label={esp.lang("event/artist_detail", "buy_ticket")} onPress={() => {
              EventIndexProperty.isLogin(() => {
                // if (selectedTicket) {
                //   loadDataPriceConfig(selectedTicket?.url_config)
                // }
                // proceedToPayment()
              })
            }} style={{ backgroundColor: LibStyle.colorGreen, marginTop: 2, marginHorizontal: 15 }} />
          </View>
        </View>
      </LibSlidingup>

    </View>
  )
}