// withHooks
import { applyStyle } from 'esoftplay';
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 { LibDialog } from 'esoftplay/cache/lib/dialog/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 { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import { useEffect } from 'react';

import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import React from 'react';
import { Pressable, ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventOrder_lotteryArgs {

}
export interface EventOrder_lotteryProps {

}
export default function m(props: EventOrder_lotteryProps): any {
  const { id } = LibNavigation.getArgsAll(props)
  const [result, setResult] = useSafeState<any>()

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

  function loadData(): void {
    new LibCurl("event_order_detail_luckydraw?id=" + id, null, (res: any) => {
      let a = res?.list?.map((item: any) => {
        return ({
          ...item,
          qty: 0
        })
      })
      let b = {
        coupon: res?.coupon,
        list: a
      }
      setResult(b)
    }, (error: any) => {
      esp.log(error);
      LibDialog.warning("Oops", error?.message)
      LibNavigation.back()
    }, 1)
  }

  function sendSubmit() {
    let filterData = result?.list?.filter((x: any) => x.qty > 0).map((item: any) => {
      return ({
        id: item.id,
        qty: item.qty
      })
    })

    let post = {
      prize_list: JSON.stringify(filterData)
    }

    LibDialog.confirm(esp.lang("event/order_lottery", "confirm"), esp.lang("event/order_lottery", "confirm_point"), esp.lang("event/order_lottery", "yes"), () => {
      LibProgress.show("Mohon tunggu")
      new LibCurl("event_order_detail_luckydraw_claim?id=" + id, post, (res: any) => {
        LibProgress.hide()
        esp.log(res);
        LibDialog.info(esp.lang("event/order_lottery", "information"), res)
        LibNavigation.sendBackResult(res)
      }, (error: any) => {
        LibProgress.hide()
        esp.log(error);
        LibDialog.warning(esp.lang("event/order_lottery", "oops"), error?.message)
      }, 1)
    }, esp.lang("event/order_lottery", "no"), () => {

    })
  }

  function getTotalQty() {
    return result.list.reduce((x: any, current: any) => x + current.qty, 0);
  };

  function renderItem(item: any, i: number) {

    return (
      <View key={i} style={{ flexDirection: 'row', margin: 15 }}>
        <Pressable onPress={() => { }} style={{ flex: 1, flexDirection: 'row', alignContent: 'center', alignItems: 'center', justifyContent: 'center', paddingLeft: 50, marginLeft: 35, borderRadius: 5, padding: 10, backgroundColor: '#fff' }}>
          <View style={{ flex: 1, marginRight: 5, }}>
            <Text allowFontScaling={false} numberOfLines={1} ellipsizeMode='tail' style={{ fontWeight: 'bold', fontSize: 16 }} >{item.title}</Text>
            <Text allowFontScaling={false} numberOfLines={2} ellipsizeMode='tail' style={{ fontSize: 12, color: 'grey' }}>{item.description}</Text>

            <View style={applyStyle({ marginTop: 10, alignSelf: 'flex-end', flexDirection: 'row', alignContent: 'center', alignItems: 'center' })}>
              <TouchableOpacity onPressIn={() => {
                if (item.qty > 0) {
                  let updatedList = LibObject.set(result, item.qty - 1)('list', i, 'qty');
                  setResult(updatedList);
                }
              }} hitSlop={{ top: 15, left: 15, right: 15, bottom: 15 }} testID='minus_btn' onPress={() => { }}>
                <View style={applyStyle({ padding: 1, borderRadius: 6, backgroundColor: "#ecf0f1", alignContent: 'center', alignItems: 'center' })}>
                  <LibIcon name="minus" color="#e74c3c" />
                </View>
              </TouchableOpacity>
              <Text style={applyStyle({ fontFamily: "Arial", fontSize: 20, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#9b9b9b", marginLeft: 13, marginRight: 13 })}>{item.qty}</Text>
              <TouchableOpacity onPressIn={() => {
                const currentTotalQty = getTotalQty();
                if (currentTotalQty < result.coupon) {
                  let updatedQty = item.qty + 1;
                  if (currentTotalQty + 1 > result.coupon) {
                    updatedQty = item.qty + (result.coupon - currentTotalQty);
                  }
                  let updatedList = LibObject.set(result, updatedQty)('list', i, 'qty');
                  setResult(updatedList);
                } else {
                  LibToastProperty.show(esp.lang("event/order_lottery", "your_maks_token_is") + result?.coupon)
                }
              }} hitSlop={{ top: 15, left: 15, right: 15, bottom: 15 }} testID='plus_btn' onPress={() => { }}>
                <View style={applyStyle({ padding: 1, borderRadius: 6, backgroundColor: "#ecf0f1", alignContent: 'center', alignItems: 'center' })}>
                  <LibIcon name="plus" color="#16a085" />
                </View>
              </TouchableOpacity>
            </View>

          </View>
        </Pressable>
        <View style={{ position: 'absolute', top: 15, height: 80, width: 80, borderRadius: 40, alignContent: 'center', alignItems: 'center', justifyContent: 'center', backgroundColor: '#fff' }}>
          <LibPicture style={{ height: 70, width: 70, borderRadius: 35, backgroundColor: '#000' }} resizeMode='cover' source={{ uri: item.image }} />
        </View>
      </View>
    )
  }

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

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey /* "#FFC523" */ }}>
      <EventHeader title={esp.lang("event/order_lottery", "follow_lucky_draw")} />

      <ScrollView>
        {
          result?.list?.map(renderItem)
        }

      </ScrollView>
      <View style={{ backgroundColor: '#fff' }}>
        <Text style={{ margin: 10, marginBottom: 0 }} >{esp.lang("event/order_lottery", "u_have") + result?.coupon + esp.lang("event/order_lottery", "token_for_luckydraw")}</Text>

        <EventButton
          label={esp.lang("event/order_lottery", "submit")}
          onPress={() => {
            if (getTotalQty() == result?.coupon) {
              sendSubmit()
            } else {
              LibToastProperty.show(esp.lang("event/order_lottery", "please_enter_all_point"))
            }
          }}
          style={{ margin: 10, borderRadius: 5 }}
          backgroundColor={getTotalQty() == result?.coupon ? LibStyle.colorGreen : LibStyle.colorBgGrey}
        />
      </View>
    </View>
  )
}