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

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 { LibCollaps } from 'esoftplay/cache/lib/collaps/import';
import { LibDatepicker } from 'esoftplay/cache/lib/datepicker/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibKeyboard_avoid } from 'esoftplay/cache/lib/keyboard_avoid/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/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 { 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 useGlobalState, { useGlobalReturn } from 'esoftplay/global';
import useLazyState from 'esoftplay/lazy';
import useSafeState from 'esoftplay/state';
import React from 'react';
import { Pressable, ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventAdditional_inputArgs {

}
export interface EventAdditional_inputProps {

}

// export type ItemAddition = {
//   "each": string,
//   "title": string,
//   "additions": Array<{
//     "id": string,
//     "question": string,
//     "type": string,
//     "is_option": string,
//     "is_content": string,
//     "is_required": string,
//     "options": Array<{
//       "id": string,
//       "content": string,
//     }>,
//     "value": Array<string>,
//     "display_value": Array<string>,
//     "subvalue"?: string,
//   }>,
// }

const additionalState = useGlobalState<any>(undefined, { persistKey: 'event/additional_input' })

export function state(): useGlobalReturn<any> {
  return additionalState
}

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

  const [newData, setNewData] = useSafeState()
  const [, setIdx, getIdx] = useLazyState<number>()
  const inputRefs = useRef<React.RefObject<EventInput_rectangle>[]>([]);


  useEffect(() => {
    if (Object.keys(itemAddition).length > 0) {
      setNewData(itemAddition)
    } else {
      setNewData(data)
    }

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

  useEffect(() => {
    if (data?.additions?.length) {
      inputRefs.current = data.additions.map((_, i: number) => inputRefs.current[i] || React.createRef<EventInput_rectangle>());
    }
  }, [data?.additions]);

  function save() {
    let stillEmpty1 = newData?.additions?.filter((item: any) => item.is_required == 1).filter((it: any) => (it.value?.length == 0 && !it.subvalue)).length > 0
    if (stillEmpty1) {
      LibToastProperty.show(esp.lang("event/additional_input", "complete_info"))
      return
    } else {
      LibNavigation.sendBackResult(newData, 190)
    }
  }


  function renderCatNew(item: any, i: number) {
    let values = newData?.additions?.[i]?.value
    let display_values = newData?.additions?.[i]?.display_value

    let show = true /* Object.keys(itemAddition).length > 0 ? true : false */

    return (
      <View key={i} style={{ backgroundColor: '#fff', borderRadius: 5, margin: 15, marginBottom: 5, marginTop: 10 }}>
        <LibCollaps key={i} show={show} header={(show) =>
          <View style={{ padding: 7, borderBottomColor: '#c9c9c9', borderBottomWidth: 0.5, justifyContent: 'space-between', flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
            <View style={{ flex: 6, flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
              <Text allowFontScaling={false} style={{ flexWrap: 'wrap', fontSize: 14, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#000", }}>{item.question}</Text>
              {
                item.is_required == 1 &&
                <Text allowFontScaling={false} style={{ fontSize: 14, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#d0021b" }}> *</Text>
              }
            </View>
            <LibIcon name={show ? 'chevron-up' : 'chevron-down'} color="#4a4a4a" />
          </View>}>
          {/* type: 1: text field, 2: textarea, 3: date picker, 4: choice, 5: multichoice, 6: dropdown */}
          <View style={{ marginHorizontal: 10 }}>
            {
              item.type == 1 && // text field
              <EventInput_rectangle
                ref={inputRefs.current[i]}
                placeholder={item.question}
                returnKeyType='next'
                placeholderTextColor='#c9c9c9'
                style={{ borderRadius: 5, borderColor: '#c9c9c9' }}
                defaultValue={newData?.additions?.[i]?.value?.[0]}
                inputStyle={{ marginLeft: 0 }}
                onSubmitEditing={() => {
                  const nextInput = inputRefs.current[i + 1];
                  nextInput?.current?.focus();
                }}
                onChangeText={(text) => {
                  let t = text?.length == 0 ? [] : [text]
                  let updateValue = LibObject.set(newData, t)('additions', i, 'value')
                  let updateDisplayValue = LibObject.set(updateValue, t)('additions', i, 'display_value')
                  setNewData(updateDisplayValue)
                }} />
            }

            {
              item.type == 2 && // textarea
              <EventInput_rectangle
                multiline={true}
                placeholder={item.question}
                placeholderTextColor='#c9c9c9'
                style={{ borderRadius: 5, borderColor: '#c9c9c9', height: 100, justifyContent: 'flex-start' }}
                defaultValue={newData?.additions?.[i]?.value?.[0]}
                inputStyle={{ textAlignVertical: 'top', paddingTop: 10, paddingBottom: 10, marginLeft: 0, height: 100 }}
                onChangeText={(text) => {
                  let t = text?.length == 0 ? [] : [text]
                  let updateValue = LibObject.set(newData, t)('additions', i, 'value')
                  let updateDisplayValue = LibObject.set(updateValue, t)('additions', i, 'display_value')
                  setNewData(updateDisplayValue)
                }} />
            }

            {
              item.type == 3 && // datepicker
              <TouchableOpacity onPress={() => {
                setIdx(i)()
                dialogDatePicker.current?.show()
              }} style={{ height: 40, borderRadius: 5, marginTop: 12, backgroundColor: "#ffffff", borderWidth: 1, borderColor: "#c5c5c5", flexDirection: 'row', alignContent: 'center', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: 9 }}>
                <Text allowFontScaling={false} style={{ fontSize: 12, color: values?.length > 0 ? "#000" : "#e5e5e5", marginRight: 15, }}>{values?.length > 0 ? display_values[0] : item.question}</Text>
                {
                  values?.length == 0 &&
                  <LibIcon name='chevron-down' />
                }
              </TouchableOpacity>
            }

            {
              item.type == 4 && // choice
              <View style={{ marginTop: 8 }}>
                {
                  item?.options?.length > 0 && item?.options?.map((it: any, ii: number) => {
                    let values = newData?.additions?.[i]?.value?.[0] == it.id
                    return (
                      <Pressable
                        key={ii}
                        hitSlop={{ top: 10, right: 10 }}
                        onPress={() => {
                          let updateValue = LibObject.set(newData, [it.id])('additions', i, 'value')
                          let updateDisplayValue = LibObject.set(updateValue, [it.content])('additions', i, 'display_value')
                          let deleteSubvalue = LibObject.set(updateDisplayValue, "")('additions', i, 'subvalue')
                          setNewData(deleteSubvalue)

                        }}
                        style={{ flexDirection: 'row', marginBottom: 5, alignContent: 'center', alignItems: 'center' }}>
                        <LibIcon name={values ? 'circle' : 'circle-outline'} size={20} color={values ? LibStyle.colorPrimary : '#9b9b9b'} />
                        <Text allowFontScaling={false} style={{ marginLeft: 7, marginRight: 15, color: values ? "#000" : "#9b9b9b" }}>{it.content}</Text>
                      </Pressable>
                    )
                  })
                }
              </View>
            }

            {
              item.type == 5 && // multichoice
              <View style={{ marginTop: 8 }}>
                {
                  item?.options?.length > 0 && item?.options?.map((it: any, ii: number) => {
                    return (
                      <Pressable
                        key={ii}
                        hitSlop={{ top: 10, right: 10 }}
                        onPress={() => {
                          const out = values.includes(it.id) ? values.filter((id: any) => it.id != id) : [...values, it.id]
                          const out_content = item?.options?.filter((item: any) => out.includes(item.id)).map((x: any) => x.content)

                          let updateValue = LibObject.set(newData, out)('additions', i, 'value')
                          let updateDisplayValue = LibObject.set(updateValue, out_content)('additions', i, 'display_value')
                          setNewData(updateDisplayValue)
                        }}
                        style={{ padding: 3, marginBottom: 8, paddingHorizontal: 15, marginRight: 4, borderWidth: 1, borderRadius: 3, borderColor: values?.includes?.(it.id) ? "#fff" : "#9b9b9b", backgroundColor: values?.includes?.(it.id) ? LibStyle.colorPrimary : "#fff", justifyContent: 'center' }} >
                        <LibTextstyle textStyle='body' text={it.content} style={{ color: values?.includes?.(it.id) ? (esp.isDebug("") ? "#fff" : "#000") : "#9b9b9b" }} />
                      </Pressable>
                    )
                  })
                }
              </View>
            }

            {
              item.type == 6 && // dropdown
              <TouchableOpacity onPress={() => {
                dialogDropdown.current?.show()
                setDropdownData(item)
                setIdx(i)
              }} style={{ height: 40, borderRadius: 5, marginTop: 12, backgroundColor: "#ffffff", borderWidth: 1, borderColor: "#c5c5c5", flexDirection: 'row', alignContent: 'center', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: 9 }}>
                <Text allowFontScaling={false} style={{ fontSize: 12, color: values?.length > 0 ? "#000" : "#e5e5e5", marginRight: 15, }}>{values?.length > 0 ? display_values[0] : item.question}</Text>
                {
                  values?.length == 0 &&
                  <LibIcon name='chevron-down' />
                }
              </TouchableOpacity>
            }

            {
              item.is_content == 1 &&
              <EventInput_rectangle
                placeholder={esp.lang("event/additional_input", "other")}
                placeholderTextColor='#c9c9c9'
                style={{ borderRadius: 5, borderColor: '#c9c9c9' }}
                defaultValue={newData?.additions?.[i]?.subvalue}
                // value={newData?.additions?.[i]?.subvalue}
                inputStyle={{ marginLeft: 0 }}

                onChangeText={(text) => {
                  let fillSubValue = LibObject.set(newData, text)('additions', i, 'subvalue')
                  if (item.type == 4) {
                    let emptyValue = LibObject.set(fillSubValue, [])('additions', i, 'value')
                    let emptyDisplayValue = LibObject.set(emptyValue, [])('additions', i, 'display_value')
                    setNewData(emptyDisplayValue)
                  } else {
                    setNewData(fillSubValue)
                  }
                }} />
            }

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

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={esp.lang("event/additional_input", "header_title")} />
      <LibKeyboard_avoid>
        <ScrollView>
          {data?.additions?.length > 0 && data?.additions?.map(renderCatNew)}

        </ScrollView>
        <View style={{ padding: 10 }} >
          <EventButton
            label={esp.lang("event/additional_input", "btn_save")}
            backgroundColor={LibStyle.colorPrimary}
            onPress={save}
          />
        </View>

      </LibKeyboard_avoid>

      <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) => {
              let updateValue = LibObject.set(newData, [dt])('additions', getIdx(), 'value')
              let updateDisplayValue = LibObject.set(updateValue, [LibUtils.moment(dt).localeFormat("DD MMMM YYYY")])('additions', getIdx(), 'display_value')
              setNewData(updateDisplayValue)
              dialogDatePicker.current?.hide()
            }}
            selectedDate={newData?.additions?.[getIdx()]?.value?.[0] || LibUtils.moment().localeFormat('YYYY-MM-DD')}
          />
        </View>
      </LibSlidingup>

      <LibSlidingup ref={dialogDropdown} >
        <View style={{ width: 40, height: 3, borderRadius: 5, backgroundColor: "#fff", alignSelf: 'center', marginBottom: 10 }} />
        <View style={{ maxHeight: LibStyle.height - (LibStyle.height / 5), backgroundColor: 'white', borderTopLeftRadius: 15, paddingHorizontal: 25, borderTopRightRadius: 15, padding: 10 }} >
          <Pressable style={{ marginTop: 10, alignSelf: 'flex-end' }} onPress={() => dialogDropdown.current?.hide()}>
            <LibIcon name='close' color={"#c9c9c9"} />
          </Pressable>
          <Text allowFontScaling={false} style={{ fontWeight: 'bold', fontSize: 16, marginBottom: 15 }}>{dropdownData?.question}</Text>

          <ScrollView>
            {
              dropdownData?.options?.map((item: any, i: number) => {
                return (
                  <Pressable onPress={() => {
                    let updateValue = LibObject.set(newData, [item.id])('additions', getIdx(), 'value')
                    let updateDisplayValue = LibObject.set(updateValue, [item.content])('additions', getIdx(), 'display_value')
                    setNewData(updateDisplayValue)

                    dialogDropdown.current?.hide()
                  }} key={i} style={{ borderBottomWidth: 1, borderColor: '#c5c5c5', padding: 10, flexDirection: 'row', alignItems: "center" }}>
                    <Text allowFontScaling={false} style={{ flex: 1, fontFamily: 'InterMedium', fontSize: 16, color: '#2C2B2D' }}>{item?.content}</Text>
                  </Pressable>
                )
              })
            }

          </ScrollView>

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