// withHooks

import { useIsFocused } from '@react-navigation/native';
import { LibCarrousel } from 'esoftplay/cache/lib/carrousel/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/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 { LibStatusbar } from 'esoftplay/cache/lib/statusbar/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { UserClass } from 'esoftplay/cache/user/class/import';
import esp from 'esoftplay/esp';
import useGlobalState, { useGlobalReturn } from 'esoftplay/global';
import useSafeState from 'esoftplay/state';

import { EventBlock } from 'esoftplay/cache/event/block/import';
import { EventHeader_home } from 'esoftplay/cache/event/header_home/import';
import { EventIndexProperty } from 'esoftplay/cache/event/index/import';
import { EventItem } from 'esoftplay/cache/event/item/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import { EventNotice } from 'esoftplay/cache/event/notice/import';
import { EventSection } from 'esoftplay/cache/event/section/import';
import useGlobalSubscriber from 'esoftplay/subscribe';
import React, { useEffect } from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';

export interface EventIndexArgs {

}
export interface EventIndexProps {

}

const sliderHeight = 0.50 * LibStyle.width

function Blocktitle(props: any) {
  if (props.block.show_title == 1)
    // return null
    return (
      <EventSection
        text={props?.block?.title}
        textColor={props.color}
        icon={(props?.block?.params?.more_module == '' || props?.block?.show_more != 1) ? undefined : 'icons/ic_btn_more_rounded.png'}
        moreAction={() => props?.block?.params?.more_module == '' || props?.block?.show_more != 1 ? {} : LibNavigation.navigate(props?.block?.params?.more_module, { url: props?.block?.params?.more_url, title: props?.block?.title })}
      />
    )
  else
    return null
}

export function update(_callback?: () => void): void {
  // UserReminderProperty?.setReminder?.()
  new LibCurl('user?t=' + new Date().getTime(), null,
    (res) => {
      esp.mod("chatting/lib")().setUser()
      UserClass.create(res)
      _callback?.()
    },
    (msg) => {

    })
}

export function isLogin(isLogin: () => void, isLogout?: () => void): void {
  let user = UserClass.state().get()
  if (user && user?.id) {
    isLogin()
  } else {
    isLogout
      ? isLogout()
      : LibNavigation.navigate('user/login')
  }
}

const ticketState = useGlobalState<any>(undefined, { persistKey: 'bigbang_card_tiket_cache1', isUserData: true, inFile: true, loadOnInit: true })
export function stateTicketCache(): useGlobalReturn<any> {
  return ticketState
}

const bookedAddons = useGlobalState<any>({}, { persistKey: 'event_detail_addons_booked2', isUserData: true, inFile: true, loadOnInit: true })
export function stateBookedAddonsCache(): useGlobalReturn<any> {
  return bookedAddons
}

export const reload = useGlobalSubscriber()


const state = useGlobalState<any>(undefined, { persistKey: 'bigbang/event', inFile: true })

export default function m(props: EventIndexProps): any {
  const [data, setData] = state?.useState?.()
  const [error, setError] = useSafeState<any>()
  const isFocus = useIsFocused()
  const user = UserClass.state().useSelector(s => s)

  useEffect(() => {
    loadData()
    if (user) {
      EventIndexProperty?.update()
    }
  }, [isFocus])

  function loadData() {
    const langData = esp.mod("lib/locale").stateLang().get() || {}
    const currentLanguage = Object.keys(langData).length == 0 ? 'id' : esp.mod("lib/locale").state().get()
    const selectedLang = esp.modProp("user/language_list").allLanguage()?.filter?.((x: any) => x?.name == currentLanguage)?.[0] || {}

    const baseURL: string = esp.config("events", "home")
    let homeURL =
      baseURL.includes(".json") ?
        baseURL :
        baseURL + "-" + selectedLang.code + ".json"

    new LibCurl(homeURL, null, (res) => {
      setData(res)
    }, msg => setError(msg))
  }

  function renderImageSlider(item1: any, i: number) {
    if (item1.url != "") {
      return (
        <TouchableOpacity key={i.toString()} onPress={() => {
          {
            item1.url !== '' &&
              LibNavigation.navigate(item1.module, { url: item1.url, title: item1.title })
          }
        }}>
          <LibPicture source={{ uri: item1.image }} style={styleId_Z2fNAzg} />
        </TouchableOpacity>
      )
    } else {
      return (
        <LibPicture key={i} source={{ uri: item1.image }} style={styleId_Z2fNAzg} />
      )
    }
  }

  function renderBlockSlider(_block: any) {
    return (
      <LibCarrousel
        // key={block.list_url}
        delay={4000}
        style={styleId_2r0hN4}
        autoplay
        bullets
        bulletStyle={styleId_Z1RmiUb}
        chosenBulletStyle={styleId_xFf64}
        bulletsContainerStyle={styleId_Zoes0y} >
        {
          _block.map(renderImageSlider)
        }
      </LibCarrousel>
    )
  }


  function renderBlockGridItem(item: any, i: number) {
    return (
      <EventItem
        key={i.toString()}
        {...item}
        text={item.title}
        onPress={() => {
          {
            item.url !== '' &&
              LibNavigation.navigate(item.module, { url: item.url, title: item.title })
          }
        }} />
    )
  }

  function renderBlockGrid(block: any) {
    return (
      <View style={styleId_zwbK3} >
        {
          block.map(renderBlockGridItem)
        }
      </View>
    )
  }

  function renderBlock(block: any, i: number) {
    if (block.type == 'slider') {
      // return null
      return (
        <View key={i.toString()} >
          <Blocktitle block={block} color={LibStyle.colorRed} />
          <View style={styleId_2r0hN4} >
            <EventBlock
              // cache
              url={block.list_url}
              render={renderBlockSlider} />
          </View>
        </View>
      )
    } else if (block.type == 'grid') {
      // return null
      return (
        <View key={i.toString()}>
          <View style={{ margin: 10, marginBottom: 0, }}>
            <Blocktitle block={block} color={LibStyle.colorRed} />
          </View>
          <EventBlock
            cache
            url={block.list_url}
            render={renderBlockGrid}
          />
        </View>
      )
    } else if (block.type == 'event_cat') {
      return (
        <View key={i}>
          <View style={{ marginTop: 5, marginBottom: 10 }}>
            <Blocktitle block={block} color={LibStyle.colorRed} />
          </View>
          <View style={{ marginBottom: 5 }}>
            <ScrollView horizontal >
              <View style={{ flexDirection: 'row', height: 80 }}>
                <EventBlock
                  cache
                  url={block.list_url}
                  render={(block: any) => {
                    return (
                      block.map((item1: any, i: number) => {
                        return (
                          <TouchableOpacity key={i} onPress={() => {
                            LibNavigation.navigate(item1.module, { cat_id: item1.id, url: item1.url })
                          }}>
                            <View style={[{ height: 75, width: 75, marginTop: 3, marginRight: 1, marginLeft: 15, borderRadius: 10, backgroundColor: '#fff', alignContent: 'center', alignItems: 'center', justifyContent: 'center' }, LibStyle.elevation(2)]}>
                              <LibPicture source={{ uri: item1?.image }} style={{ width: 45, height: 45, resizeMode: 'contain' }} />
                              <Text allowFontScaling={false} ellipsizeMode={"tail"} numberOfLines={2} style={{ marginBottom: 7, marginTop: 4, fontFamily: "Arial", fontSize: 10, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, textAlign: "center", color: '#9e9e9e', paddingLeft: 3, paddingRight: 3 }}>{(item1?.title)}</Text>
                            </View>
                          </TouchableOpacity>
                        )
                      })
                    )
                  }} />
              </View>
            </ScrollView>
          </View>
        </View>
      )
    }
    else if (block.type == 'info') {
      return (
        <View key={i.toString()}>
          <EventNotice mode="info" text={block?.title} canPress={block?.task != '' && block.task_module != ''} onPress={() => LibNavigation.navigate(block?.task_module, { url: block?.task, title: block?.title })} containerStyle={{ marginVertical: 0, marginHorizontal: 0, borderRadius: 0 }} />
        </View>
      )
    } else {
      return null
    }
  }

  if (!data) {
    return (
      <View style={{ flex: 1 }}>
        <LibStatusbar style="dark" />
        <LibSkeleton>
          <View style={{ marginTop: LibStyle.STATUSBAR_HEIGHT }} />
          <View style={{ flexDirection: 'row' }}>
            <LibSkeleton.Circle size={33} />
            <LibSkeleton.BoxFlex size={33} />
            <LibSkeleton.Box size={33} />
            <LibSkeleton.Box size={33} />
            <LibSkeleton.Box size={33} />
          </View>
          <LibSkeleton.BoxFull size={sliderHeight} />
          <LibSkeleton.BoxHalf size={20} />
          <View style={{ flexDirection: 'row' }} >
            <LibSkeleton.BoxFlex size={100} />
            <LibSkeleton.BoxFlex size={100} />
          </View>
          <LibSkeleton.BoxHalf size={20} />
          <View style={{ flexDirection: 'row' }} >
            <LibSkeleton.BoxFlex size={100} />
            <LibSkeleton.BoxFlex size={100} />
          </View>
          <LibSkeleton.BoxHalf size={20} />
          <View style={{ flexDirection: 'row' }} >
            <LibSkeleton.BoxFlex size={100} />
            <LibSkeleton.BoxFlex size={100} />
          </View>
        </LibSkeleton>
      </View>
    )
  }

  return (
    <View style={styleId_ZcMJmd} >
      <View style={styleId_ZiB8gU} >
        <EventHeader_home onPress={() => { LibNavigation.navigate('search/index') }} cart />
      </View>
      {
        error ?
          <EventMessage message={error?.message} />
          :
          <LibScroll
            onRefresh={loadData}
            style={styleId_ZcMJmd}>
            {
              data?.blocks?.map?.(renderBlock)
            }
          </LibScroll>
      }
      {/* <LibUpdater show={esp.isDebug()} /> */}
    </View>
  )
}
const styleId_Z2fNAzg: any = { height: sliderHeight, width: LibStyle.width, resizeMode: 'cover', backgroundColor: "#f1f2f3" }
const styleId_2r0hN4: any = { height: sliderHeight, width: LibStyle.width }
const styleId_Z1RmiUb: any = { width: 7, height: 7, backgroundColor: "#7e7e7e", borderRadius: 3.5, borderWidth: 0, marginHorizontal: 2 }
const styleId_xFf64: any = { width: 7, height: 7, backgroundColor: "white", borderRadius: 3.5, borderWidth: 0, marginHorizontal: 2 }
const styleId_Zoes0y: any = { marginBottom: -15 }
const styleId_ZcMJmd: any = { flex: 1 }
const styleId_zwbK3: any = { flexDirection: 'row', flexWrap: 'wrap', padding: 10 }
const styleId_ZiB8gU: any = { backgroundColor: '#FFC523' }