// withHooks
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 { LibObject } from 'esoftplay/cache/lib/object/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 { UseCondition } from 'esoftplay/cache/use/condition/import';
import esp from 'esoftplay/esp';
import moment from 'esoftplay/moment';
import useSafeState from 'esoftplay/state';
import React, { useEffect, useRef } from 'react';
import { Pressable, ScrollView, Text, View } from 'react-native';

export interface EventQueue_outArgs {
  event_id: number | string,
  notes: string
}
export interface EventQueue_outProps {

}

export default function m(props: EventQueue_outProps): any {
  const LibNavigation = useRef(esp.mod("lib/navigation")).current
  const LibTextstyle = useRef(esp.mod("lib/textstyle")).current
  const UseMap = useRef(esp.mod("use/map")).current

  const { event_id, notes } = LibNavigation.getArgsAll(props)
  const [types, setTypes] = useSafeState<any[]>([])
  const [dates, setDates] = useSafeState<any[]>([])
  const [post, setPost, getPost] = useSafeState<any>({
    event_id: event_id,
    qty: 1,
    qty_min: 1,
    qty_max: 10
  })
  const datesRef = useRef<LibSlidingup>(null)

  useEffect(() => {
    LibUtils.getInstallationID().then((iid) => {
      setPost(LibObject.set(getPost(), iid)('installation_id'))
    })
    new LibCurl('event_detail_price?id=' + (event_id || '264'), null, (res) => {
      setTypes(res.price_type)
    }, (err) => {
      LibToastProperty.show(err.message)
    })
  }, [])

  const isSelectedPriceId = (price_id: string) => post.price_id == price_id

  return (
    <View style={{ flex: 1, backgroundColor: '#f1f2f2' }} >
      <EventHeader title={esp.lang("event/queue_out", "title")} notif />
      <ScrollView>
        <View style={{ padding: 0 }} >
          <View style={[{ margin: 0, marginBottom: 0, backgroundColor: 'white', padding: 12, borderRadius: 0 }, LibStyle.elevation(3)]} >
            <LibTextstyle textStyle="headline" text={notes.replace(/<br\s{0,}\/>/g, '')} style={{ textAlign: 'center', marginBottom: 10 }} />
          </View>
          <View style={[{ margin: 16, backgroundColor: 'white', padding: 12, borderRadius: 16, zIndex: 100 }, LibStyle.elevation(3)]} >
            <LibTextstyle textStyle="title3" text={esp.lang("event/queue_out", "form_title")} style={{ textAlign: 'center', fontWeight: 'bold', marginBottom: 10 }} />
            <View style={{ flexDirection: 'row', marginTop: 20 }} >
              <LibTextstyle textStyle='caption1' text={esp.lang("event/queue_out", "type_title")} style={{ marginBottom: 8, fontWeight: "bold" }} />
            </View>
            <UseMap
              data={types.filter((x) => !(["8", "2", "7", "102", "108"].includes(x.kind)))}
              renderItem={(item) => (
                <Pressable
                  onPress={() => {
                    if (item.list.length == 1) {
                      setPost(
                        new (esp.mod("lib/object"))(post)
                          .set(item.price_id)('price_id')
                          .set(item.qty_max)('qty_max')
                          .set(item.qty_min)('qty_min')
                          .set(item.qty_min)('qty')
                          .set(item.list[0].ondate)('ondate')
                          .value()
                      )
                    } else {
                      setPost(
                        new (esp.mod("lib/object"))(post)
                          .set(item.price_id)('price_id')
                          .set(item.qty_max)('qty_max')
                          .set(item.qty_min)('qty_min')
                          .set(item.qty_min)('qty')
                          .value()
                      )
                      setDates(item.list)
                      datesRef.current?.show()
                    }
                  }}
                  style={{ flexDirection: 'row', marginBottom: 8, alignItems: 'center' }} >
                  <View style={[{ padding: 10, paddingHorizontal: 20, backgroundColor: isSelectedPriceId(item.price_id) ? LibUtils.hexToRgba('#1DC111', 0.05) : '#f8f8f8', borderRadius: 8, flex: 1, paddingVertical: 12, flexDirection: 'row', alignItems: 'center' }, isSelectedPriceId(item.price_id) ? { borderWidth: 1, borderColor: '#1DC111' } : {}]} >
                    <LibTextstyle textStyle="body" text={item.type} style={{ textAlign: 'left', fontWeight: isSelectedPriceId(item.price_id) ? "bold" : "normal" }} />
                    <UseCondition if={isSelectedPriceId(item.price_id)} >
                      <Text style={{ fontSize: 12, color: "#888" }} > ({post.ondate == '0000-00-00' ? "All Date" : moment(post.ondate).format('DD MMMM YYYY')})</Text>
                      <View style={{ flex: 1 }} />
                      <LibIcon name='check-circle' color='#1DC111' />
                    </UseCondition>
                  </View>
                </Pressable>
              )}
            />
            <UseCondition if={post.price_id} >
              <>
                <View style={{ flexDirection: 'row', marginTop: 20 }} >
                  <LibTextstyle textStyle='caption1' text={esp.lang("event/queue_out", "qty_title") + (post.qty_min > 1 ? (" " + esp.lang("event/queue_out", "min_order", post.qty_min)) : "")} style={{ marginBottom: 8, fontWeight: "bold" }} />
                </View>
                <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }} >
                  <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }} >
                    <Pressable
                      onPress={() => setPost(LibObject.update(post, (oldQty) => Math.max(Number(oldQty) - 1, Number(post.qty_min)))('qty'))}
                      style={{ opacity: post.qty == post.qty_min ? 0.5 : 1, alignItems: 'center', justifyContent: 'center', height: 40, width: 40, borderRadius: 20, backgroundColor: LibUtils.hexToRgba(LibStyle.colorRed, .4) }} >
                      <LibIcon.AntDesign name='minus' />
                    </Pressable>
                    <Text style={{ fontSize: 30, margin: 12, minWidth: 40, textAlign: 'center' }} >{post.qty || post.qty_min}</Text>
                    <Pressable
                      onPress={() => setPost(LibObject.update(post, (oldQty) => Math.min(Number(oldQty) + 1, post.qty_max))('qty'))}
                      style={{ opacity: post.qty == post.qty_max ? 0.5 : 1, alignItems: 'center', justifyContent: 'center', height: 40, width: 40, borderRadius: 20, backgroundColor: LibUtils.hexToRgba(LibStyle.colorGreen, .4) }} >
                      <LibIcon.AntDesign name='plus' />
                    </Pressable>
                  </View>
                </View>
              </>
            </UseCondition>
            <View style={{ backgroundColor: '#f9f9f9', marginHorizontal: -12, paddingHorizontal: 10, marginBottom: -12, borderBottomLeftRadius: 16, borderBottomRightRadius: 16, paddingVertical: 5, paddingTop: 10 }} >
              <LibTextstyle textStyle='caption2' text={esp.lang("event/queue_out", "notes")} style={{ marginBottom: 8 }} />
            </View>
          </View>
          <Pressable
            onPress={() => {
              if (!post.price_id) {
                LibToastProperty.show(esp.lang("event/queue_out", "err_no_type"))
                return
              }
              esp.mod("lib/dialog").confirm(esp.lang("event/queue_out", "dialog_title"), esp.lang("event/queue_out", "dialog_msg"), esp.lang("event/queue_out", "dialog_yes"), () => {
                new LibCurl("event_booking_waiting_allotment", post, (res, msg) => {
                  LibToastProperty.show(res)
                  LibNavigation.back()
                }, (err) => {
                  LibToastProperty.show(err.message)
                })
              }, esp.lang("event/queue_out", "dialog_no"), () => {

              })

            }}
            style={[{ backgroundColor: LibStyle.colorPrimary, alignItems: 'center', justifyContent: 'center', paddingVertical: 15, marginHorizontal: 16, borderBottomLeftRadius: 16, borderBottomRightRadius: 16, margin: 10, marginTop: -32, paddingTop: 26 }, LibStyle.elevation(3)]} >
            <Text style={{ color: 'white', fontWeight: 'bold' }} >{esp.lang("event/queue_out", "submit")}</Text>
          </Pressable>
        </View>
      </ScrollView>
      <LibSlidingup ref={datesRef} >
        <View style={{ maxHeight: esp.mod("lib/style").height * 0.5, backgroundColor: 'white', borderTopLeftRadius: 30, borderTopRightRadius: 30 }} >
          <LibTextstyle textStyle='m_h6' text={esp.lang("event/queue_out", "date_title")} style={{ textAlign: 'center', padding: 20 }} />
          <ScrollView>
            <UseMap
              data={dates}
              renderItem={(item) => (
                <Pressable
                  onPress={() => {
                    setPost(
                      new (esp.mod("lib/object"))(post)
                        .set(item.price_id)('price_id')
                        .set(item.ondate)('ondate')
                        .value()
                    )
                    datesRef.current?.hide()
                  }}
                  style={{ padding: 10, marginHorizontal: 16, marginBottom: 8, backgroundColor: '#f9f9f9', borderRadius: 8, paddingVertical: 12 }} >
                  <LibTextstyle textStyle="body" text={item.ondate == '0000-00-00' ? "All Date" : moment(item.ondate).format('DD MMMM YYYY')} style={{ textAlign: 'center' }} />
                </Pressable>
              )}
            />
          </ScrollView>
          {/* <View style={{ padding: 18 }} >
            <EventButton label='Kirim' onPress={() => { }} />
          </View> */}
        </View>
      </LibSlidingup>
    </View>
  )
}