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

import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/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 { UserClass } from 'esoftplay/cache/user/class/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import React from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventAdditionalArgs {

}
export interface EventAdditionalProps {

}

export default function m(props: EventAdditionalProps): any {

  const { event_id, qty, ondate, price_id, type_ticket }: any = LibNavigation.getArgsAll(props)
  const [result, setResult] = useSafeState()
  const [dataAddPost, setDataAddPost] = useSafeState<any[]>([])
  const user = UserClass.state().get()


  useEffect(() => {
    loadData()
    return () => LibNavigation.cancelBackResult(LibNavigation.getResultKey(props))
  }, [])

  function loadData() {
    let url = price_id
      ? 'event_booking_addition_form?event_id=' + event_id + "&price_id=" + price_id
      : 'event_booking_addition_form?event_id=' + event_id

    new LibCurl(url, null, (res, msg) => {
      // langsung skip kalau confignya per event ada additionalnya dan di price_id tidak ada additionalnya
      if (res?.additions?.length == 0) {
        LibNavigation.sendBackResult("", LibNavigation.getResultKey(props))
      }

      const a = res?.additions?.length > 0 && res?.additions?.map?.((item: any, i: number) => {
        return ({
          ...item,
          value: [],
        })
      })
      const b = {
        ...res,
        additions: a
      }
      setResult(b)

      let is_each = res?.each == 0 ? 1 : qty
      setDataAddPost(new Array(is_each).fill({}))

    }, (err) => {
      esp.log({ err });
      LibToastProperty.show(err.message)
      LibNavigation.back()
    }, 1)
  }

  function renderItem(item: any, i: number) {
    let isEmptyObj = Object.keys(item).length > 0
    return (
      <View key={i} >
        <View style={{ margin: 15, padding: 10, marginBottom: 5, marginTop: 10, backgroundColor: '#fff', borderRadius: 5 }}>
          <TouchableOpacity onPress={() => {
            LibNavigation.navigateForResult('event/additional_input', { data: result, itemAddition: item }, 190).then((value) => {
              setDataAddPost(LibObject.set(dataAddPost, value)(i))
            })
          }} style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center', justifyContent: 'space-between' }}>
            <Text allowFontScaling={false} style={{ color: LibStyle.colorPrimary, fontWeight: 'bold' }}>{esp.lang("event/additional", "complete_info", String(Number(i + 1)))}</Text>
            <LibIcon name='pencil-outline' size={20} color={LibStyle.colorPrimary} />
          </TouchableOpacity>
        </View>
        {
          isEmptyObj &&
          <View style={{ margin: 18, padding: 10, marginBottom: 5, marginTop: -3, backgroundColor: '#fff', borderBottomLeftRadius: 5, borderBottomRightRadius: 5 }}>
            {
              item.additions?.map((it: any, ii: number) => {
                return (
                  <View key={ii} style={{ paddingHorizontal: 10, paddingVertical: 5, borderRadius: 5, marginBottom: 10, backgroundColor: LibStyle.colorBgGrey }}>
                    <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode='tail' style={{ fontSize: 14, color: "#009688", fontWeight: 'bold', letterSpacing: 0.5, marginBottom: 5 }}>{it.question}</Text>
                    {
                      it.display_value?.map((x: any, z: number) => {
                        return (
                          <Text key={z} allowFontScaling={false} style={{ fontSize: 12, color: '#000', marginRight: 6 }}>{x}</Text>
                        )
                      })
                    }
                    {
                      it.value?.length == 0 &&
                      <Text allowFontScaling={false} style={{ fontSize: 12, color: '#000', marginRight: 6 }}>-</Text>
                    }
                    {
                      it.subvalue &&
                      <Text allowFontScaling={false} style={{ marginTop: 5, fontSize: 12, color: '#000' }}>{it.subvalue}</Text>
                    }
                  </View>
                )
              })
            }
          </View>
        }
      </View>
    )
  }

  function isObjectEmpty(obj: any) {
    return Object.keys(obj).length === 0;
  }

  if (!result) {
    return <LibLoading />
  }


  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={esp.lang("event/additional", "header_title")} subtitle={
        type_ticket ?
          (ondate && ondate != "0000-00-00" ? type_ticket + " " + LibUtils.moment(ondate).format("DD MMM YYYY") : type_ticket)
          :
          ""
      } />
      <ScrollView>
        <View style={{ margin: 15, marginBottom: 5, marginTop: 10, padding: 10, borderWidth: 1, borderColor: '#fff', borderRadius: 5, backgroundColor: '#fff', ...LibStyle.elevation(2) }}>
          <LibTextstyle textStyle='m_overline' text={esp.lang("event/additional", "buyer_info")} style={{ color: "#aaa", fontSize: 12, marginBottom: 5 }} />
          <Text allowFontScaling={false} style={{ fontWeight: 'bold', fontSize: 16, letterSpacing: 1 }}>{user?.name}</Text>
          <Text allowFontScaling={false} style={{ fontSize: 14, letterSpacing: 1 }}>{user?.email}</Text>
          <Text allowFontScaling={false} style={{ fontSize: 12, letterSpacing: 1 }}>{user?.phone}</Text>
        </View>

        {
          result?.title != "" &&
          <LibTextstyle textStyle='m_overline' text={result?.title} style={{ lineHeight: 20, color: '#000', fontSize: 14, margin: 15, fontWeight: 'bold', marginBottom: 0 }} />
        }

        {
          dataAddPost?.map(renderItem)
        }

      </ScrollView>
      <View style={{ padding: 10 }}>
        <EventButton
          label={esp.lang("event/additional", "btn_next")}
          backgroundColor={LibStyle.colorPrimary}
          onPress={() => {
            let isRequire = result?.additions?.length > 0 && result?.additions?.filter((item: any) => item.is_required == 1)
            let obj2: any[] = []
            dataAddPost.map((item: any) => {
              let obj1: any[] = []
              item.additions?.map((it: any) => {
                let a = [
                  it.id,
                  it.value,
                ]
                if (it.hasOwnProperty("subvalue")) {
                  a.push(it.subvalue)
                }
                if (it.type == 1 || it.type == 2 || it.type == 3) {
                  a.push(it.value[0])
                  a[1] = []
                }
                obj1.push(a)
              })
              obj2.push(obj1)
            })

            if (isRequire.length > 0) {
              const emptyObject = dataAddPost.some(item => isObjectEmpty(item));

              if (emptyObject) {
                LibToastProperty.show(esp.lang("event/additional", "toast_empty"))
              } else {

                let addition = JSON.stringify(obj2)
                LibNavigation.sendBackResult(addition, LibNavigation.getResultKey(props))
              }
            } else {
              let addition = JSON.stringify(obj2)
              LibNavigation.sendBackResult(addition == "[[]]" ? "" : addition, LibNavigation.getResultKey(props))
            }
          }}
        />
      </View>
    </View>
  )
}