// withHooks
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/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 { LibStyle } from 'esoftplay/cache/lib/style/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 { applyStyle } from 'esoftplay';
import { EventFirebase_socket, EventFirebase_socketProperty } from 'esoftplay/cache/event/firebase_socket/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventIndexProperty } from 'esoftplay/cache/event/index/import';
import { EventSlider } from 'esoftplay/cache/event/slider/import';
import { UseCondition } from 'esoftplay/cache/use/condition/import';
import { UseDeeplinkProperty } from 'esoftplay/cache/use/deeplink/import';
import esp from 'esoftplay/esp';
import moment from 'esoftplay/moment';
import useSafeState from 'esoftplay/state';
import React, { useEffect } from 'react';
import { Linking, Pressable, Text, TouchableOpacity, View } from 'react-native';
import MapView, { Marker } from 'react-native-maps';

export interface EventDetailProps {

}

export default function m(props: EventDetailProps): any {
  const { isInPricingQueueConfig } = EventFirebase_socket()
  const [result, setResult] = useSafeState<any>(undefined)
  const url = LibNavigation.getArgs(props, 'url')
  const [deeplinkParams] = UseDeeplinkProperty.params.useState()
  const [priority, setPriority] = useSafeState(false)

  moment().locale('id')
  function loadData(): void {
    // CacheHit.doHit(url)
    new LibCurl(url, null, (res, msg) => {
      EventFirebase_socketProperty.eventIdQueue.set(res.id)
      setResult(res)
      if (res.allotment) {
        esp.modProp("event/firebase_socket").userIdKeyReplacer.set({
          t: Number(res.allotment.t),
          s: Number(res.allotment.s),
          priority: 1
        })
        setPriority(true)
      } else {
        setPriority(false)
      }
    }, (error) => {
      LibDialog.warning(esp.lang("event/detail", "load_failed"), error?.message)
      LibNavigation.back()
    })
  }

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

  if (!result) {
    let itemWidth = LibStyle.width - 60
    return (
      <View style={{ flex: 1 }}>
        <EventHeader title={esp.lang("event/detail", "header_empty")} />
        <LibSkeleton>
          <View style={{ margin: 15, height: 9 / 16 * itemWidth, width: itemWidth, borderRadius: 10, backgroundColor: '#fff', alignSelf: 'center' }} />
          <View style={{ marginLeft: 15, backgroundColor: 'white', width: '70%', height: 20, borderRadius: 10 }} />

          <View style={{ marginTop: 20, marginLeft: 15, flexDirection: 'row', borderRadius: 10, alignContent: 'center', alignItems: 'center' }}>
            <View style={{ width: 28, height: 28, borderRadius: 5, backgroundColor: 'white' }} />
            <View style={{ width: '40%', backgroundColor: 'white', height: 15, borderRadius: 10, marginLeft: 5 }} />
          </View>

          <View style={{ marginTop: 10, marginLeft: 15, flexDirection: 'row', borderRadius: 10, alignContent: 'center', alignItems: 'center' }}>
            <View style={{ width: 28, height: 28, borderRadius: 5, backgroundColor: 'white' }} />
            <View style={{ width: '30%', backgroundColor: 'white', height: 15, borderRadius: 10, marginLeft: 5 }} />
          </View>

          <View style={{ margin: 15, borderRadius: 10, height: '20%', width: '90%', backgroundColor: '#fff' }} />
          <View style={{ marginTop: 0, margin: 15, borderRadius: 10, height: '30%', width: '80%', backgroundColor: '#fff' }} />
          <View style={{ marginTop: 0, margin: 15, borderRadius: 10, height: '10%', width: '90%', backgroundColor: '#fff' }} />
        </LibSkeleton>
      </View>
    )
  }

  const hasLatlong = result?.location_latlong != '' && result?.location_latlong?.includes(',')
  let lat = 0
  let lng = 0
  if (hasLatlong) {
    lat = parseFloat(result.location_latlong?.split(',')[0])
    lng = parseFloat(result.location_latlong?.split(',')[1])
  }

  const curr = result?.hasOwnProperty('currency') ? result?.currency : ''
  const isFree = (result.price_min == result.price_max) && result.price_min == 0
  let priceRange = esp.lang("event/detail", "start_from", LibUtils.money(result.price_min, curr)) /*  + " s/d " + LibUtils.money(result.price_max, curr) */
  if (result.price_min == result.price_max) {
    priceRange = LibUtils.money(result.price_min, curr)
  }


  function renderTag(x: any, i: number) {
    return (
      <Pressable key={i} onPress={() => { LibNavigation.navigate('event/list', { url: x?.url, keywords: x?.title }) }} style={styleId_qGD26}>
        <Text allowFontScaling={false} numberOfLines={1} style={styleId_Z2qkux5}>#{String(x?.title).toLowerCase()}</Text>
      </Pressable>
    )
  }

  const date = moment().localeFormat('YYYY-MM-DD HH:mm:ss')
  const startBooking = result?.start_booking;
  const startDate: any = new Date(startBooking);
  const currentDate: any = new Date();

  // Hitung selisih hari antara tanggal sekarang dan startBooking
  const diffTime = startDate - currentDate;
  const diffDays = diffTime / (1000 * 60 * 60 * 24);

  esp.log(result);

  return (
    <View style={{ flex: 1, backgroundColor: '#fff' }} >
      <EventHeader
        title={result.title}
        iconShare={result?.url_share && result?.url_share !== ""}
        onPressShare={() => {
          LibUtils.share(result?.url_share)
        }}
      />

      <LibScroll onRefresh={loadData}>
        <EventSlider images={result.images} onIndexChange={(i) => { }} />
        <Text allowFontScaling={false} style={{ marginTop: -10, fontFamily: "Arial", fontSize: 18, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: "#4a4a4a", margin: 20 }} >{result.title}</Text>
        <View style={{ flexDirection: 'row', marginBottom: 10, alignItems: 'center', marginHorizontal: 20 }} >
          <LibPicture source={esp.assets('icons/ic_calendar_grey.png')} style={{ width: 14, height: 14 }} />
          <Text allowFontScaling={false} style={{ marginLeft: 10, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#f39c12" }} >{result.status == 4 ? esp.lang("event/detail", "evn_pending") : LibUtils.getDateRange(result.start_date, result.end_date, esp.lang("event/detail", "until"))}</Text>
        </View>
        <View style={{ flexDirection: 'row', marginBottom: 10, alignItems: 'center', marginHorizontal: 20 }} >
          <LibPicture source={esp.assets('icons/ic_tickets_grey.png')} style={{ width: 14, height: 14 }} />
          <Text allowFontScaling={false} style={{ marginLeft: 10, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#2980b9" }} >{result?.price_type == 0 ? esp.lang("event/detail", "tb_announce") : isFree ? esp.lang("event/detail", "text_free") : priceRange}</Text>
        </View>

        {
          result?.event_tag?.length > 0 &&
          <View style={{ flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', marginLeft: 17, marginTop: 5 }}>
            {
              result?.event_tag?.map?.(renderTag)
            }
          </View>
        }

        <View style={{ marginHorizontal: 20, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', alignContent: 'center' }}>
          <Text allowFontScaling={false} style={{ marginTop: 10, fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: "#4a4a4a" }} >{esp.lang("event/detail", "text_about_event")}</Text>
          {
            result && result.files !== '' &&
            <TouchableOpacity onPress={() => {
              Linking.canOpenURL(result.files).then((t) => {
                Linking.openURL(result.files)
              })
            }} >
              <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 10, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: LibStyle.colorRed }} >{esp.lang("event/detail", "text_show_brochure")}</Text>
            </TouchableOpacity>
          }
        </View>
        <LibWebview source={{ html: result.description }} onFinishLoad={() => { }} />
        {
          result && result.youtube !== "" &&
          <>
            <Text allowFontScaling={false} style={{ marginHorizontal: 20, marginTop: 10, fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: "#4a4a4a" }} >{esp.lang("event/detail", "text_video")}</Text>
            <Pressable onPress={() => LibNavigation.navigate('lib/video', { code: result.youtube })} >
              <LibPicture source={{ uri: LibVideoProperty.getUrlThumbnail(result.youtube) }} style={{ height: LibStyle.width * 9 / 16, width: LibStyle.width - 40, marginHorizontal: 20, resizeMode: 'cover' }} />
            </Pressable>
          </>
        }
        {
          result.address != undefined && result.address != "" &&
          <>
            <Text allowFontScaling={false} style={{ marginHorizontal: 20, marginTop: 10, fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: "#4a4a4a" }} >{esp.lang("event/detail", "text_location")}</Text>
            <View style={{ flexDirection: 'row', marginBottom: 10, alignItems: 'center', marginHorizontal: 20 }} >
              <LibPicture source={esp.assets('icons/ic_pin_grey.png')} style={{ width: 14, height: 14 }} />
              <Text allowFontScaling={false} style={{ marginLeft: 10, fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#9b9b9b", flex: 1 }} >{result.address + ' ' + result.location_name}</Text>
            </View>
          </>
        }
        {
          result.location_latlong !== '' && hasLatlong &&
          <Pressable onPress={() => LibUtils.mapTo(result.location_name, result.location_latlong)} >
            <View pointerEvents="none" style={{ marginHorizontal: 20, borderRadius: 10, backgroundColor: '#999', height: 180, marginBottom: 24, overflow: 'hidden' }} >
              <MapView
                style={{ flex: 1 }}
                liteMode
                initialRegion={{ latitude: lat, longitude: lng, latitudeDelta: 0.0122, longitudeDelta: 0.0121 }}>
                <Marker
                  onPress={() => { LibUtils.mapTo(result.location_name, result.location_latlong) }}
                  coordinate={{ latitude: lat, longitude: lng }}
                  title={result.title}
                  description={result.address}
                />
              </MapView>
            </View>
          </Pressable>
        }

        {
          result?.image_map !== "" &&
          <>
            <Text allowFontScaling={false} style={{ marginBottom: 10, marginHorizontal: 20, marginTop: 10, fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: "#4a4a4a" }} >{esp.lang("event/detail", "text_layout")}</Text>
            <Pressable onPress={() => {
              LibNavigation.navigate('lib/gallery', { image: result?.image_map })
            }}>
              <LibPicture source={{ uri: result?.image_map }} style={{ height: 0.50 * LibStyle.width - 30, width: LibStyle.width - 30, alignSelf: 'center' }} resizeMode="contain" />
            </Pressable>
          </>
        }
        {
          result?.event_cat?.length > 0 &&
          <>
            <Text allowFontScaling={false} style={{ marginHorizontal: 20, fontFamily: "Arial", fontSize: 13, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, color: "#4a4a4a" }} >{esp.lang("event/detail", "text_event_cat")}</Text>
            <View style={{ flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', marginLeft: 17, marginTop: 5 }}>
              {
                result?.event_cat?.map?.((x: any, i: number) => (
                  <Pressable key={i} onPress={() => { LibNavigation.navigate('event/list', { url: 'event', cat_id: x?.id }) }} style={{ marginTop: 5, padding: 7, paddingHorizontal: 10, marginRight: 5, borderRadius: 3, backgroundColor: LibStyle.colorGrey }}>
                    <Text allowFontScaling={false} numberOfLines={1} style={{ fontFamily: 'Arial', fontSize: 10, letterSpacing: 2, color: '#2980b9' }}>{x?.title}</Text>
                  </Pressable>
                ))
              }
            </View>
          </>
        }

      </LibScroll>

      {/* 0=pending, 1=active, 2=done, 3=cancel (posisi tdnya pending lalu diaktifkan ketika wktunya udah lewat), 4=postpone(sudah lewat tapi jangan done) */}

      {
        result?.status == 1 ?
          <View style={{ paddingVertical: 5, paddingHorizontal: 10 }} >
            {
              deeplinkParams?.type == 'event-voucher' &&
              <Text allowFontScaling={false} style={{ color: "coral", fontSize: 12, fontWeight: 'bold', marginBottom: 5 }}>{esp.lang("event/detail", "voucher_embed") + deeplinkParams?.code}</Text>
            }
            {
              result?.book_available == 0 ?
                <>
                  {
                    result.end_booking <= date && result.end_booking != '0000-00-00 00:00:00' ?
                      <View style={{ height: 35, borderRadius: 17, backgroundColor: LibStyle.colorLightGrey, justifyContent: 'center', alignItems: 'center', paddingHorizontal: 9 }} >
                        <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 12, textAlign: "center", textAlignVertical: 'center', color: 'black', marginHorizontal: 10 }} >{esp.lang("event/detail", "text_booking_end")}</Text>
                      </View>
                      :
                      <View style={{ height: 35, borderRadius: 17, backgroundColor: LibStyle.colorLightGrey, justifyContent: 'center', alignItems: 'center', paddingHorizontal: 9 }} >
                        <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 12, textAlign: "center", textAlignVertical: 'center', color: 'black', marginHorizontal: 10 }} >
                          {
                            diffDays <= 3 ?
                              esp.lang("event/detail", "text_book_on", moment(result.start_booking).serverFormat('DD MMMM YYYY'))
                              :
                              esp.lang("event/detail", "booking_not_yet")
                          }
                        </Text>
                      </View>
                  }
                </>
                :
                <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
                  {
                    result?.url_artist != "" &&
                    <TouchableOpacity onPress={() => {
                      // LibNavigation.navigate('event/artist', { title: result?.title, url: result?.url_artist, has_addition: result?.has_addition })
                      LibNavigation.navigate('event/artist', {
                        title: result?.title,
                        url: result?.url_artist,
                        has_addition: result?.has_addition
                      })
                    }} style={applyStyle({ width: (LibStyle.width - 30) * 0.5, borderWidth: 2, borderColor: LibStyle.colorGreen, height: 40, borderRadius: 16, backgroundColor: 'white', flexDirection: 'row', alignItems: 'center', alignContent: 'center', justifyContent: 'center', paddingHorizontal: 9 })} >
                      <Text allowFontScaling={false} style={applyStyle({ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: LibStyle.colorGreen })} >{esp.lang("event/detail", "line_up")}</Text>
                    </TouchableOpacity>
                  }
                  <TouchableOpacity onPress={() => {
                    EventIndexProperty.isLogin(() => {

                      if (isInPricingQueueConfig(result.id)) {
                        LibNavigation.navigateForResult('event/queue_pricing', { event_id: result?.id }).then((v) => {
                          LibNavigation.navigate(result?.config?.hasOwnProperty('multiprice') && result?.config?.multiprice == 1 ? 'event/ticket_list2' : 'event/ticket_list', {
                            url: result.url_price,
                            has_addition: result?.has_addition,
                            has_addition_global: result?.has_addition_global,
                            fee_platform: {
                              fee_platform_amount: result?.fee_platform_amount,
                              fee_platform_type: result?.fee_platform_type,
                            },
                            subscribed: {
                              is_subscribed: result?.config?.is_subscribed,
                              is_subscribed_default: result?.config?.is_subscribed_default,
                              is_subscribed_label: result?.config?.is_subscribed_label
                            }
                          })
                        })
                      } else {
                        LibNavigation.navigate(result?.config?.hasOwnProperty('multiprice') && result?.config?.multiprice == 1 ? 'event/ticket_list2' : 'event/ticket_list', {
                          url: result.url_price,
                          has_addition: result?.has_addition,
                          has_addition_global: result?.has_addition_global,
                          fee_platform: {
                            fee_platform_amount: result?.fee_platform_amount,
                            fee_platform_type: result?.fee_platform_type,
                          },
                          subscribed: {
                            is_subscribed: result?.config?.is_subscribed,
                            is_subscribed_default: result?.config?.is_subscribed_default,
                            is_subscribed_label: result?.config?.is_subscribed_label
                          }
                        })
                      }

                    })
                  }} style={applyStyle({ width: result?.url_artist != "" ? (LibStyle.width - 30) * 0.5 : LibStyle.width - 20, borderWidth: 2, borderColor: LibStyle.colorGreen, height: 40, borderRadius: 16, backgroundColor: LibStyle.colorGreen, flexDirection: 'row', alignItems: 'center', alignContent: 'center', justifyContent: 'center', paddingHorizontal: 9 })} >
                    <Text allowFontScaling={false} style={applyStyle({ fontFamily: "ArialBold", fontSize: 14, textAlign: "center", textAlignVertical: 'center', color: "#fff" })} >{esp.lang("event/detail", "text_buy_ticket")}</Text>
                  </TouchableOpacity>
                  <UseCondition if={priority} >
                    <View pointerEvents='none' style={{ height: 20, position: "absolute", right: 0, top: 0, bottom: 0, left: 0 }} >
                      <LibSkeleton
                        colors={['#fffdb8', '#fdf68c', '#f4cd2a', '#f4cd2a', '#d28d0d', '#fffdb8', '#fdf68c', '#f4cd2a', '#f4cd2a', '#d28d0d', '#fffdb8', '#fdf68c', '#f4cd2a', '#f4cd2a', '#d28d0d']}>
                        <Text style={{ color: "white", fontWeight: "bold", fontSize: 9, alignSelf: 'center', textAlign: 'center' }} >{esp.lang("event/detail", "priority_label")}</Text>
                      </LibSkeleton>
                    </View>
                  </UseCondition>
                </View>
            }
          </View>
          :
          result.status == 2 ? /* done */
            <View style={{ flexDirection: 'row', paddingVertical: 5, paddingHorizontal: 10 }} >
              <View style={{ flex: 1, height: 35, borderRadius: 17, backgroundColor: LibStyle.colorLightGrey, justifyContent: 'center', alignItems: 'center', paddingHorizontal: 9 }} >
                <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 12, textAlign: "center", textAlignVertical: 'center', color: 'black', marginRight: 10, marginLeft: 10 }} >{esp.lang("event/detail", "event_done")}</Text>
              </View>
            </View>
            :
            result.status == 4 ? /* postpone(sudah lewat tapi jangan done) */
              <View style={{ flexDirection: 'row', paddingVertical: 5, paddingHorizontal: 10 }} >
                <View style={{ flex: 1, height: 35, borderRadius: 17, backgroundColor: LibStyle.colorLightGrey, justifyContent: 'center', alignItems: 'center', paddingHorizontal: 9 }} >
                  <Text allowFontScaling={false} style={{ fontFamily: "ArialBold", fontSize: 12, textAlign: "center", textAlignVertical: 'center', color: 'black', marginRight: 10, marginLeft: 10 }} >{esp.lang("event/detail", "event_postpone")}</Text>
                </View>
              </View>
              :
              null
      }

    </View >
  )
}
const styleId_qGD26: any = { marginTop: 5, padding: 7, paddingHorizontal: 10, marginRight: 5, borderRadius: 3, backgroundColor: LibStyle.colorGrey }
const styleId_Z2qkux5: any = { fontFamily: 'Arial', fontSize: 10, letterSpacing: 2, color: '#2980b9' }