// withHooks

import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventOrder_detailProperty } from 'esoftplay/cache/event/order_detail/import';
import { EventRating } from 'esoftplay/cache/event/rating/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibInput } from 'esoftplay/cache/lib/input/import';
import { LibKeyboard_avoid } from 'esoftplay/cache/lib/keyboard_avoid/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibNet_status } from 'esoftplay/cache/lib/net_status/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import esp from 'esoftplay/esp';
import useGlobalState, { useGlobalReturn } from 'esoftplay/global';
import useLazyState from 'esoftplay/lazy';
import moment from 'esoftplay/moment';
import useSafeState from 'esoftplay/state';
import React, { useEffect, useRef } from 'react';
import { Pressable, ScrollView, View } from 'react-native';


export interface EventReview_addArgs {

}
export interface EventReview_addProps {
  type: number;
  type_name: string;
  title: string;
  categories: ResultCategories[];
  booking_id: string;
  url_form: string
}

export interface Item {
  booking_id: number;
  url: string;
  post: any;
  status: number;
  review: ItemReview;
  surveys: any;
}


export interface ItemReview {
  booking_id: number;
  content: string;
  rating: number;
  created: string;
}


export interface ResultCategories {
  title: string;
  suggestions: string[];
}

const stateReviews = useGlobalState<any>(undefined, { persistKey: 'event/review_add', loadOnInit: true })

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

// export function syncAll() {
//   const status = LibNet_status.state().get()
//   if (status?.isOnline == true && status?.isInternetReachable == true) {
//     const listReviewsLocal = stateReviews.get()
//     if (listReviewsLocal.length > 0) {
//       let hasNext = false;
//       if (listReviewsLocal.length >= 2) {
//         hasNext = true;
//       }
//       const currentReview = listReviewsLocal[0]
//       new LibCurl(currentReview.url, currentReview.post, (res, msg) => {
//         let a = listReviewsLocal.filter((it: any) => {
//           return it.booking_id != currentReview.booking_id
//         })
//         stateReviews.set(a)
//         if (hasNext) {
//           syncAll()
//         }
//       }, (err)=>{
//         // let a = listReviewsLocal.filter((it: any) => {
//         //   return it.booking_id != currentReview.booking_id
//         // })
//         // stateReviews.set(a)
//         if (hasNext) {
//           syncAll()
//         }
//       })
//     }
//   }
// }


function buildOfflineReview(data: any, surveys: any[]) {
  let out: any[] = []
  Object.entries(data).forEach((item) => {
    const key = item[0].replace('c', '')
    const options: any = item[1]
    let survey = surveys?.filter?.((x) => x.id == key) || []
    if (survey?.length) {
      const currSurvey = survey[0]
      const curOptions = currSurvey.options
      if (typeof options != 'string') {
        options.forEach((opt: any) => {
          out.push({
            survey_id: key,
            survey_question: currSurvey.question,
            survey_option: curOptions.filter((x: any) => x.id == opt)[0].content,
            content: null
          })
        })
      } else {
        out.push({
          survey_id: key,
          survey_question: currSurvey.question,
          survey_option: "",
          content: options
        })
      }
    }

  })
  return out;
}


export default function m(props: EventReview_addProps): any {
  const { url_form, booking_id, type, rate }: any = LibNavigation.getArgsAll(props)
  const reviewText = useRef<LibInput>(null)
  let inputReview = useRef('').current

  const title_text = type == 1 ? esp.lang("event/review_add", "review_event") : type == 2 ? esp.lang("event/review_add", "review_eo") : esp.lang("event/review_add", "review_sponsor")

  const [result, setResult, getResult] = useSafeState<any>()
  const [rating, setRating] = useSafeState(rate || 0)
  const [survey, setSurvey, getSurvey] = useLazyState<any>({})
  const [status] = LibNet_status.state().useState()


  // { survey_id, survey_question, survey_option, content }

  useEffect(() => {
    loadData()
    // stateReviews.reset()
  }, [])


  function loadData() {
    new LibCurl(url_form, null, (res, msg) => {
      setResult(res)
    }, (err) => {
      LibDialog.warningConfirm(esp.lang("event/review_add", "oops"), err?.message, esp.lang("event/review_add", "confirm_ok"), () => {
        LibNavigation.back()
      }, "", () => { })
    })
  }

  // function setReview(t: string) {
  //   if (inputReview.length < 1) {
  //     inputReview = t
  //   } else {
  //     inputReview = inputReview + ', ' + t
  //   }
  //   reviewText.current!.setText(inputReview)
  // }

  function sendReview() {
    if (rating == 0) {
      LibToastProperty.show(esp.lang("event/review_add", "rating"))
      return
    }

    let url = "event_order_detail_review_submit?id=" + booking_id + "&type=" + type

    const postSurvey = (data: any) => {
      let out: any = {}
      Object.entries(data).forEach((item) => {
        if (!item[0].includes('c')) {
          if (typeof item[1] == 'string')
            out[item[0]] = [item[0], []]
          else
            out[item[0]] = [item[0], item[1]]
        }
      })
      Object.entries(data).forEach(item => {
        if (item[0].includes('c')) {
          let cleanKey = item[0].replace('c', '')
          let currentValue = out[cleanKey]
          if (currentValue) {
            out[cleanKey] = [...currentValue, item[1]]
          } else {
            out[cleanKey] = [cleanKey, [], item[1]]
          }
        }
      })
      return Object.values(out)
    }

    let post = {
      rating: rating,
      content: reviewText.current?.getText().replace(/\n/g, '\\n'),
      survey: JSON.stringify(postSurvey(getSurvey())),
    }
    let listReviewsLocal = stateReviews.get()
    let ctime = new Date()
    let formattedTime = moment(ctime).serverFormat('YYYY-MM-DD HH:mm:ss')
    let x: Item = {
      booking_id: booking_id,
      url: url,
      post: post,
      status: 1,
      review: {
        booking_id: booking_id,
        content: reviewText.current?.getText?.().replace(/\n/g, '\\n') || '',
        rating: rating,
        created: formattedTime
      },
      surveys: buildOfflineReview(getSurvey(), getResult()?.surveys),
    }

    let checkSame = listReviewsLocal?.filter((z: any) => z?.booking_id == booking_id)
    if (checkSame == undefined || checkSame?.length == 0) {
      EventOrder_detailProperty.subscribe().trigger(x)
      stateReviews.set(LibObject.push(listReviewsLocal, x)())
      // syncAll()
      if (status?.isOnline == true && status?.isInternetReachable == true) {
        new LibCurl(url, post, (res, msg) => {
          let a = listReviewsLocal.filter((it: any) => {
            return it.booking_id != x.booking_id
          })
          stateReviews.set(a)
        })
      }

      LibNavigation.back()
      LibDialog.info(esp.lang("event/review_add", "info"), esp.lang("event/review_add", "review_sended"))
    } else {
      if (esp.isDebug("toast"))
        LibToastProperty.show(JSON.stringify(checkSame))
    }
  }

  function renderCat(item: any, i: number) {
    return (
      <View style={{ marginTop: 14, borderLeftColor: '#e1e1e1', borderLeftWidth: 2, paddingLeft: 12 }} key={i} >
        <LibTextstyle textStyle='callout' text={item.question} />
        {/* single */ item.is_option == 1 &&
          <ScrollView horizontal style={{ marginTop: 8 }} >
            {
              item?.options?.length > 0 && item?.options?.map((it: any, ii: number) => {
                let values = survey[item.id]
                return (
                  <>
                    <Pressable
                      key={ii}
                      onPress={() => { setSurvey(LibObject.set(getSurvey(), [it.id])(item.id))() }}
                      style={{ padding: 3, paddingHorizontal: 15, marginRight: 4, borderWidth: 1, borderRadius: 29, borderColor: "#202020", opacity: !values?.includes?.(it.id) ? 0.3 : 1, justifyContent: 'center' }} >
                      <LibTextstyle textStyle='body' text={it.content} style={{ color: "#202020" }} />
                    </Pressable>
                  </>
                )
              })
            }
          </ScrollView>
        }
        {/* multi */ item.is_option == 2 &&
          <ScrollView horizontal style={{ marginTop: 8 }} >
            {
              item?.options?.length > 0 && item?.options?.map((it: any, ii: number) => {
                let values = survey[item.id]
                return (
                  <>
                    <Pressable
                      key={ii}
                      onPress={() => {
                        setSurvey(LibObject.update(getSurvey(), (ov) => {
                          if (!Array.isArray(ov)) ov = []
                          const out = ov.includes(it.id) ? ov.filter((id: any) => it.id != id) : [...ov, it.id]
                          return out
                        })(item.id))()
                      }}
                      style={{ padding: 3, paddingHorizontal: 15, marginRight: 4, borderWidth: 1, borderRadius: 3, borderColor: "#202020", opacity: !values?.includes?.(it.id) ? 0.3 : 1, justifyContent: 'center' }} >
                      <LibTextstyle textStyle='body' text={it.content} style={{ color: "#202020" }} />
                    </Pressable>
                  </>
                )
              })
            }
          </ScrollView>
        }
        {
          item?.is_content == 1 &&
          <View style={{ marginHorizontal: -16 }}>
            <LibInput
              label={item.is_option == 0 ? esp.lang("event/review_add", "answer") : esp.lang("event/review_add", "other")}
              value={survey[item.id + 'c'] || ''}
              onChangeText={(text) => setSurvey(LibObject.set(getSurvey(), text)(item.id + 'c'))()} />
          </View>
        }
      </View>
    )
  }

  return (
    <LibKeyboard_avoid style={{ flex: 1 }} >
      <EventHeader title={esp.lang("event/review_add", "header_title")} notif />
      <ScrollView style={{ margin: 16 }} >
        <LibTextstyle text={result ? result?.title : title_text} textStyle='m_h6' style={{ marginBottom: 20, textAlign: 'center' }} />
        {/* <LibTextstyle textStyle='m_overline' text='Rating' style={{ marginTop: 24, borderRadius: 1, marginBottom: 5 }} /> */}
        <EventRating defaultValue={rating} onChangeRating={(rate) => { setRating(rate) }} />
        {
          result?.surveys?.length > 0 &&
          <>
            <LibTextstyle textStyle='m_overline' text={esp.lang("event/review_add", "survey")} style={{ marginTop: 36, borderRadius: 1, marginBottom: 5 }} />
          </>
        }
        {result?.surveys?.length > 0 && result?.surveys?.map(renderCat)}

        <LibTextstyle textStyle='m_overline' text={esp.lang("event/review_add", "review")} style={{ marginTop: 36, borderRadius: 1, marginBottom: 5 }} />
        <LibInput
          ref={reviewText}
          defaultValue={inputReview}
          base
          multiline={true}
          style={{ color: '#000', height: 100, borderColor: 'gray', borderWidth: 1, borderRadius: 8, padding: 10, textAlignVertical: 'top' }}
          onChangeText={(t) => { inputReview = t }}
        />
      </ScrollView>
      <EventButton label={esp.lang("event/review_add", "send_review")} onPress={() => {
        LibDialog.confirm(esp.lang("event/review_add", "review_title"), esp.lang("event/review_add", "review_ok"), esp.lang("event/review_add", "review_send"), () => {
          sendReview()
        }, esp.lang("event/review_add", "review_cancel"), () => {

        })
      }} style={{ margin: 16 }} />
    </LibKeyboard_avoid>
  )
}
