// 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 { EventTmsProperty } from 'esoftplay/cache/event/tms/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/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 esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import React from 'react';
import { Pressable, ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventTms_add_resultArgs {

}
export interface EventTms_add_resultProps {

}
export default function m(props: EventTms_add_resultProps): any {
  const { dataEvent, email, qr_code, is_add } = LibNavigation.getArgsAll(props)
  const [allowReset, setAllowReset] = useSafeState<any>(0)
  const [ticketTypes, setTicketTypes] = useSafeState<any>()
  const [dataTms, setDataTms] = useSafeState<any>()

  useEffect(() => {
    loadDataTickets()
    loadDataTms()
  }, [])

  function loadDataTms() {
    let post: any = {
      // email: "bagus@fisip.net",
      email: email?.trim(),
    }
    if (qr_code)
      post.qr = qr_code?.trim()
    new LibCurl('user', post,
      (res, msg) => {
        setDataTms(res)
      },
      (msg) => {
        LibDialog.warningConfirm(esp.lang("event/tms_add_result", "oops"), msg?.message, esp.lang("event/tms_add_result", "confirm_back"), () => {
          LibNavigation.back()
        }, "", () => { })
      }
    )
  }

  function loadDataTickets() {
    let post: any = {
      event_id: dataEvent?.id
    }

    if (email) {
      post.email = email
    }

    if (qr_code) {
      post.qrcode = qr_code
    }

    new LibCurl('event_tms_access' + LibUtils.objectToUrlParam(post), null, (res, msg) => {
      if (is_add) {
        const updatedPrice = [...res.price]
          .map((item: any) => {
            return { ...item, is_selected: "1" }
          })
          .sort((a: any, b: any) =>
            a.name.localeCompare(b.name, 'id', { sensitivity: 'base' })
          )

        const updatedData = { ...res, price: updatedPrice }

        setTicketTypes(updatedData)

      } else {
        setTicketTypes(res)
      }

      setAllowReset(res?.is_resetable)

    }, (err) => {
    })
  }

  function addTMS() {
    let ids = ticketTypes?.price?.filter((item: any) => item.is_selected == 1).map((it: any) => it.id)
    let post: any = {
      event_id: dataEvent?.id,
      resetable: allowReset,
      access_ticket: JSON.stringify(ids)
    }

    if (email) {
      post.email = email.trim()
    }
    if (qr_code) {
      post.qr = qr_code.trim()
    }

    LibProgress.show(esp.lang("event/tms_add_result", "wait"))
    new LibCurl('event_tms_add', post,
      (res, msg) => {
        LibProgress.hide()
        EventTmsProperty.subscribe().trigger()
        LibToastProperty.show(msg)
        LibNavigation.back()
        if (is_add) {
          LibNavigation.back()
        }
      }, (msg) => {
        LibProgress.hide()
        LibDialog.warning(esp.lang("cashier/list", "text_failed_add"), msg?.message)
      }
    )
  }

  return (
    <View style={{ flex: 1 }}>
      <EventHeader title={esp.lang("event/tms_add", "header")} />
      <ScrollView style={{ padding: 15 }}>
        <View style={{ flexDirection: 'row' }}>
          <LibPicture
            source={{ uri: dataTms?.image }}
            style={{ width: 60, height: 60, borderRadius: 50 }}
          />
          <View style={{ marginLeft: 10, justifyContent: 'center' }}>
            <Text allowFontScaling={false} numberOfLines={1} ellipsizeMode='tail' style={{ fontSize: 16, fontWeight: "bold", color: "#4a4a4a" }} >{dataTms?.name}</Text>
            <Text allowFontScaling={false} style={{ fontSize: 12, fontWeight: "bold", lineHeight: 22, color: "#b7b7b7" }} >{dataTms?.email}</Text>
          </View>
        </View>

        {
          ticketTypes &&
          <View style={{ marginTop: 10, marginBottom: 10 }}>
            <LibTextstyle textStyle='m_overline' text={esp.lang("event/tms_add_result", "ticket_type")} style={{ fontSize: 12, marginTop: 15, marginBottom: 15 }} />
            {
              ticketTypes?.price?.map((item: any, i: number) => {
                return (
                  <TouchableOpacity key={i} onPress={() => {
                    setTicketTypes(LibObject.set(ticketTypes, item.is_selected == 1 ? 0 : 1)("price", i, 'is_selected'))
                  }} style={applyStyle({ marginBottom: 10, flexDirection: 'row', alignContent: 'center', alignItems: 'center' })} >
                    <LibIcon name={item.is_selected == 0 ? "checkbox-blank-outline" : "checkbox-marked"} color={item.is_selected == 0 ? "#000" : LibStyle.colorGreen} />
                    <Text allowFontScaling={false} style={applyStyle({ marginLeft: 8, color: item.is_selected == 0 ? "#000" : LibStyle.colorGreen, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, paddingLeft: 3, paddingRight: 3 })}>{item.name}</Text>
                  </TouchableOpacity>
                )
              })
            }
          </View>
        }

      </ScrollView>
      <View style={{ padding: 10 }}>
        <Pressable onPress={() => { setAllowReset(allowReset == 1 ? 0 : 1) }} style={applyStyle({ marginBottom: 10, flexDirection: 'row', alignContent: 'center', alignItems: 'center' })} >
          <LibIcon name={allowReset == 0 ? "checkbox-blank-outline" : "checkbox-marked"} color={allowReset == 0 ? "#000" : LibStyle.colorGreen} />
          <Text allowFontScaling={false} style={applyStyle({ marginLeft: 8, color: allowReset == 0 ? "#000" : LibStyle.colorGreen, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, paddingLeft: 3, paddingRight: 3 })}>{esp.lang("event/tms_add_result", "reset")}</Text>
        </Pressable>
        <EventButton
          label={esp.lang("event/tms_add_result", "save")}
          backgroundColor={LibStyle.colorGreen}
          onPress={() => {
            addTMS()
          }}
        />
      </View>
    </View>
  )
}