// withHooks
import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventInput_rectangle } from 'esoftplay/cache/event/input_rectangle/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import { LibCollaps } from 'esoftplay/cache/lib/collaps/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDatepicker } from 'esoftplay/cache/lib/datepicker/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibKeyboard_avoid } from 'esoftplay/cache/lib/keyboard_avoid/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/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 useLazyState from 'esoftplay/lazy';
import useSafeState from 'esoftplay/state';
import { useEffect, useRef } from 'react';

import React from 'react';
import { Pressable, ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventAdditional_newArgs {

}
export interface EventAdditional_newProps {

}
export default function m(props: EventAdditional_newProps): any {
  const { dataTicket, additionalGlobal } = LibNavigation.getArgsAll(props)
  const dialogDatePicker = useRef<LibSlidingup>(null)
  const dialogDropdown = useRef<LibSlidingup>(null)
  const [dropdownData, setDropdownData] = useSafeState()

  const sampleForms = {
    "2671": {
      "loading": false,
      "loaded": true,
      "questions": [],
      "responses": [
        {
          "ticket_no": 1,
          "answers": {}
        }
      ]
    }
  }

  const [forms, setForms] = useSafeState<any>({})
  const [params, setParams] = useSafeState<any>()
  const [loading, setLoading] = useSafeState<any>(true)
  const [reload, setReload] = useLazyState<any>(1)
  const additionTickets = dataTicket?.filter((item: any) => Number(item?.has_addition) == 1)

  useEffect(() => {
    if (additionalGlobal) {
      loadForm(dataTicket?.[0])
    } else {
      dataTicket?.forEach((item: any) => {
        loadForm(item)
      })
    }
    return () => LibNavigation.cancelBackResult(LibNavigation.getResultKey(props))
  }, [])

  useEffect(() => {
    dataTicket?.forEach((item: any, i: number) => {
      loadForm(item)
    })
  }, [reload])

  function loadForm(item: any) {
    const formKey = additionalGlobal ? "GLOBAL_ADDITION" : item.list_id

    setForms((prev: any) => ({
      ...prev,
      [formKey]: {
      }
    }))

    let url = additionalGlobal
      ? 'event_booking_addition_form?event_id=' + item?.event_id
      : 'event_booking_addition_form?event_id=' + item?.event_id + "&price_id=" + item?.price_id

    LibProgress.show("Mohon tunggu data sedang dimuat")
    new LibCurl(url, null, (res, msg) => {
      setLoading(false)
      const questions = res?.additions || []
      const responses = Array.from({ length: additionalGlobal ? 1 : item.qty }).map((_, idx) => ({
        ticket_no: idx + 1,
        answers: questions.reduce((obj: any, q: any) => {
          obj[q.id] = q?.type == 5 ? [] : ""

          return obj
        }, {})
      }))

      setForms((prev: any) => ({
        ...prev,
        [formKey]: {
          error: false,
          ondate: item?.ondate,
          questions,
          responses
        }
      }))

      LibProgress.hide()
    }, (err) => {
      setLoading(false)
      LibProgress.hide()
      setForms((prev: any) => ({
        ...prev,
        [formKey]: {
          ondate: item?.ondate,
          error: true,
          message: err?.message
        }
      }))
    }
    )
  }

  function updateAnswer(listId: string, ticketIndex: number, questionId: string, value: string) {
    setForms((prev: any) => {
      const temp = { ...prev }
      temp[listId]
        .responses[ticketIndex]
        .answers[questionId] = value

      return {
        ...temp
      }

    })
  }

  function validateAdditionalForm() {
    let errorMessage = ""
    const hasError = Object.values(forms).some((form: any) => {
      return form?.questions?.some((question: any) => {
        const isRequired = Number(question?.is_required) === 1

        if (!isRequired) {
          return false
        }

        return form?.responses?.some((response: any) => {
          const value = response?.answers?.[question.id]
          const isEmpty = value == null || String(value).trim() == ""

          if (isEmpty) {
            errorMessage = "Info tambahan #" + response?.ticket_no + " : " + question?.question + " wajib diisi"
            return true
          }
          return false
        })
      })
    })

    if (hasError) {
      LibToastProperty.show(errorMessage, 3000)
      return false
    }

    return true
  }

  function copyFirstTicket(listId: string) {
    const key = String(listId)
    setForms((prev: any) => {
      const temp = { ...prev }
      const form = temp[key]

      if (!form || !form.responses || form.responses.length <= 1) {
        return prev
      }

      const firstAnswers = form.responses[0].answers

      form.responses = form.responses.map((response: any, index: number) => {
        // ticket pertama jangan diubah
        if (index == 0) {
          return response
        }
        return {
          ...response,
          answers: JSON.parse(JSON.stringify(firstAnswers))
        }
      })

      return {
        ...temp
      }
    })
  }

  function transformAdditionPayload() {
    const addition: any[] = []
    Object.values(forms).forEach((form: any) => {
      form.responses.forEach((response: any) => {
        const attendee = Object.entries(response.answers).map(([questionId, value]: any) => {
          const question = form.questions.find((q: any) => q.id == questionId)
          const type = String(question?.type)

          // INPUT / TEXTAREA / DATE
          if (type == "1" || type == "2" || type == "3") {
            return [
              questionId,
              [],
              value || ""
            ]
          }

          // RADIO
          if (type == "4") {
            return [
              questionId,
              value ? [value] : [],
              ""
            ]
          }

          // CHECKBOX
          if (type == "5") {
            return [
              questionId,
              value || [],
              ""
            ]
          }

          // DROPDOWN
          if (type == "6") {
            return [
              questionId,
              value?.id ? [value.id] : [],
              ""
            ]
          }
          return [
            questionId,
            [],
            ""
          ]
        })

        addition.push(attendee)
      })
    })

    return addition
  }

  function renderForm(form: any, item: any) {
    // item itu adalah ticket item ya geyz
    esp.log({ form, item });
    return (
      <View>
        {
          form?.responses?.map((ticket: any, ticketIndex: number) => (
            <View key={ticketIndex} style={{ padding: 10, marginBottom: 10, borderRadius: 5, backgroundColor: LibStyle.colorBgGrey }}>
              <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
                <Text allowFontScaling={false} style={{ flex: 1, fontWeight: 'bold', fontSize: 14, }} >Addition #{ticket.ticket_no}</Text>
                {
                  ticket?.ticket_no == 2 &&
                  <TouchableOpacity
                    onPress={() => {
                      LibDialog.confirm("Informasi", "Apakah anda ingin menggunakan data Addition #1 untuk semua addition ?", "Ya", () => {
                        copyFirstTicket(item.list_id)

                      }, "Tidak", () => { })
                    }}
                    style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center' }} >
                    <Text style={{ color: "#0d6efd", fontWeight: 'bold' }} >Apply to all</Text>
                  </TouchableOpacity>
                }
              </View>
              {
                form?.questions?.map((question: any, ii: number) => {
                  let value = ticket.answers[question.id]
                  const formKey = additionalGlobal ? "GLOBAL_ADDITION" : item.list_id

                  return (
                    <View key={question.id + ii} style={{ marginBottom: 10 }} >
                      <Text allowFontScaling={false} style={{ marginVertical: 8, color: '#495057' }} >{question.question}
                        {question?.is_required == 1 && <Text style={{ color: LibStyle.colorRed }}> *</Text>}
                      </Text>

                      {
                        question?.type == 1 && // text field
                        <EventInput_rectangle
                          key={question?.id}
                          placeholder={"Isi jawaban"}
                          placeholderTextColor='#c9c9c9'
                          style={{ marginTop: 0, borderRadius: 5, borderColor: '#c9c9c9' }}
                          value={value}
                          inputStyle={{ marginLeft: 0 }}
                          onChangeText={(text) => {
                            updateAnswer(formKey, ticketIndex, question.id, text)
                          }} />
                      }

                      {
                        question?.type == 2 && // text area
                        <EventInput_rectangle
                          key={question?.id}
                          multiline={true}
                          placeholder={"Isi jawaban"}
                          placeholderTextColor='#c9c9c9'
                          style={{ marginTop: 0, borderRadius: 5, borderColor: '#c9c9c9', height: 100, justifyContent: 'flex-start' }}
                          defaultValue={value}
                          inputStyle={{ textAlignVertical: 'top', marginLeft: 0, height: 100 }}
                          onChangeText={(text) => {
                            updateAnswer(formKey, ticketIndex, question.id, text)
                          }} />
                      }

                      {
                        question?.type == 3 && // datepicker
                        <TouchableOpacity onPress={() => {
                          setParams({
                            listId: formKey,
                            ticketIndex,
                            questionId: String(question.id)
                          })
                          dialogDatePicker.current?.show()
                        }} style={{ height: 40, borderRadius: 5, backgroundColor: "#ffffff", borderWidth: 1, borderColor: "#c5c5c5", flexDirection: 'row', alignContent: 'center', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: 9 }}>
                          <Text allowFontScaling={false} style={{ fontSize: 12, color: value != "" ? "#000" : "#e5e5e5", marginRight: 15, }}>{value != "" ? LibUtils.moment(value).format("DD MMM YYYY") : question?.question}</Text>
                          <LibIcon name='chevron-down' />
                        </TouchableOpacity>
                      }

                      {
                        question?.type == 4 && // choice
                        <View style={{}}>
                          {
                            question?.options?.length > 0 && question?.options?.map((it: any, z: number) => {
                              let _value = value == it?.id
                              return (
                                <Pressable
                                  key={z}
                                  hitSlop={{ top: 10, right: 10 }}
                                  onPress={() => {
                                    updateAnswer(formKey, ticketIndex, question.id, it?.id)
                                  }}
                                  style={{ flexDirection: 'row', marginBottom: 5, alignContent: 'center', alignItems: 'center' }}>
                                  <LibIcon name={_value ? 'circle' : 'circle-outline'} size={20} color={_value ? LibStyle.colorPrimary : '#9b9b9b'} />
                                  <Text allowFontScaling={false} style={{ marginLeft: 7, marginRight: 15, color: _value ? "#000" : "#9b9b9b" }}>{it.content}</Text>
                                </Pressable>
                              )
                            })
                          }
                        </View>
                      }

                      {
                        question?.type == 5 && // multichoice
                        <View style={{}}>
                          {
                            question?.options?.length > 0 && question?.options?.map((it: any, ii: number) => {
                              const checked = value.includes(it.id)
                              return (
                                <Pressable
                                  key={ii}
                                  hitSlop={{ top: 10, right: 10 }}
                                  onPress={() => {
                                    let newValue = checked ? value.filter((x: any) => x != it.id) : [...value, it.id]
                                    updateAnswer(
                                      formKey,
                                      ticketIndex,
                                      question.id,
                                      newValue
                                    )
                                  }}
                                  style={{ flexDirection: 'row', marginBottom: 5, alignContent: 'center', alignItems: 'center' }}>
                                  <LibIcon name={checked ? 'checkbox-marked' : 'square-outline'} size={20} color={checked ? LibStyle.colorPrimary : '#9b9b9b'} />
                                  <Text allowFontScaling={false} style={{ marginLeft: 7, marginRight: 15, color: checked ? "#000" : "#9b9b9b" }}>{it.content}</Text>
                                </Pressable>
                              )
                            })
                          }
                        </View>
                      }

                      {
                        question.type == 6 && // dropdown
                        <TouchableOpacity onPress={() => {
                          dialogDropdown.current?.show()
                          setDropdownData(question)
                          setParams({
                            listId: formKey,
                            ticketIndex,
                            questionId: String(question.id)
                          })
                        }} style={{ height: 40, borderRadius: 5, backgroundColor: "#ffffff", borderWidth: 1, borderColor: "#c5c5c5", flexDirection: 'row', alignContent: 'center', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: 9 }}>
                          <Text allowFontScaling={false} style={{ fontSize: 12, color: value != "" ? "#000" : "#e5e5e5", marginRight: 15, }}>{value != "" ? value?.content : question.question}</Text>
                          <LibIcon name='chevron-down' />
                        </TouchableOpacity>
                      }

                    </View>
                  )
                }
                )}
            </View>
          )
          )}
      </View>
    )
  }

  if (loading) {
    return <LibLoading />
  }

  // esp.log(forms);

  return (
    <LibKeyboard_avoid style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title='Info Tambahan' />
      <ScrollView>
        <UseCondition if={additionalGlobal} fallback={
          <>
            {
              additionTickets.map((item: any, i: number) => {
                const form = forms[item.list_id]
                return (
                  <LibCollaps
                    key={i}
                    header={(show) => (
                      <View style={{ margin: 15, marginBottom: 0, paddingHorizontal: 15, paddingVertical: 12, borderRadius: 7, backgroundColor: '#fff', flexDirection: 'row', alignItems: 'center' }} >
                        <View style={{ flex: 1 }}>
                          <Text style={{ fontWeight: 'bold', fontSize: 14, color: "#495057" }} >{"Info tambahan untuk " + item?.type} </Text>
                          <View style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center', marginTop: 3, }}>
                            <Text style={{ fontSize: 12, marginRight: 10, color: '#6c757d' }} >({item.qty + " Tiket"})</Text>
                            {form?.ondate != "0000-00-00" && <Text style={{ color: LibStyle.colorPrimary }}>{LibUtils.moment(form?.ondate).format("DD MMM YYYY")}</Text>}
                          </View>
                        </View>
                        <LibIcon name={!show ? "chevron-down" : "chevron-up"} />
                      </View>
                    )} >

                    <View style={{ padding: 15, backgroundColor: '#fff', marginHorizontal: 15, borderRadius: 7, marginTop: 1, marginBottom: 0 }} >

                      {/* ERROR */}
                      {
                        form?.error &&
                        <>
                          <EventMessage message={form?.message || "Gagal memuat data"}
                            children={
                              <EventButton label='Coba lagi' onPress={() => {
                                setReload(reload + 1)()
                              }} />
                            }
                          />
                        </>
                      }

                      {/* FORM */}
                      {
                        renderForm(form, item)
                      }
                    </View>
                  </LibCollaps>
                )
              })
            }
          </>
        } >
          <View>
            <View style={{ margin: 15, marginBottom: 0, paddingHorizontal: 15, paddingVertical: 12, borderRadius: 7, backgroundColor: '#fff', flexDirection: 'row', alignItems: 'center' }} >
              <Text style={{ fontWeight: 'bold', fontSize: 14, color: "#495057" }} >{"Info tambahan"} </Text>
            </View>

            <View style={{ padding: 15, backgroundColor: '#fff', marginHorizontal: 15, borderRadius: 7, marginTop: 1, marginBottom: 0 }} >
              {
                renderForm(forms?.GLOBAL_ADDITION, additionTickets[0])
              }
            </View>

          </View>
        </UseCondition>

      </ScrollView>

      <EventButton
        label='Selanjutnya'
        style={{ margin: 10 }}
        backgroundColor={LibStyle.colorGreen}
        onPress={() => {
          const valid = validateAdditionalForm()

          if (!valid) {
            return
          }

          const payload = {
            addition: transformAdditionPayload()
          }
          LibNavigation.sendBackResult(payload, LibNavigation.getResultKey(props))
        }}
      />

      <LibSlidingup ref={dialogDatePicker}>
        <View style={{ backgroundColor: 'white', paddingBottom: 25, height: 230 }}>
          <LibDatepicker
            minDate={LibUtils.moment().add(-90, 'years').localeFormat('YYYY-MM-DD')}
            maxDate={LibUtils.moment().localeFormat('YYYY-MM-DD')}
            onDateChange={(dt) => {
              updateAnswer(
                params?.listId,
                params?.ticketIndex,
                params?.questionId,
                LibUtils.moment(dt).localeFormat('YYYY-MM-DD'))
              dialogDatePicker.current?.hide()
            }}
            selectedDate={LibUtils.moment().localeFormat('YYYY-MM-DD')}
          />
        </View>
      </LibSlidingup>

      <LibSlidingup ref={dialogDropdown} >
        <View style={{ paddingVertical: 20, maxHeight: LibStyle.height - (LibStyle.height / 5), backgroundColor: 'white', borderTopLeftRadius: 15, paddingHorizontal: 25, borderTopRightRadius: 15, padding: 10 }} >
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
            <Text allowFontScaling={false} style={{ fontWeight: 'bold', flex: 3 }}>{dropdownData?.question}</Text>
            <Pressable style={{ flex: 1, justifyContent: 'flex-end', alignContent: 'flex-end', alignItems: 'flex-end', alignSelf: 'flex-end' }} onPress={() => dialogDropdown.current?.hide()}>
              <LibIcon name='close' color={"#c9c9c9"} />
            </Pressable>
          </View>

          <ScrollView>
            {
              dropdownData?.options?.map((item: any, i: number) => {
                return (
                  <Pressable onPress={() => {
                    updateAnswer(
                      params?.listId,
                      params?.ticketIndex,
                      params?.questionId,
                      item
                    )

                    dialogDropdown.current?.hide()
                  }} key={i} style={{ marginVertical: 10, marginBottom: 0, backgroundColor: '#fff', borderRadius: 10, borderWidth: 1, borderColor: '#c5c5c5', padding: 10, flexDirection: 'row', alignItems: "center" }}>
                    <Text allowFontScaling={false} style={{ color: '#2C2B2D' }}>{item?.content}</Text>
                  </Pressable>
                )
              })
            }

          </ScrollView>

        </View>
      </LibSlidingup>

    </LibKeyboard_avoid>
  )
}