// withHooks

import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';
import React, { useEffect } from 'react';
import { ScrollView, Text, View } from 'react-native';


export interface EventOrder_detail_visitorArgs {

}
export interface EventOrder_detail_visitorProps {

}
export default function m(props: EventOrder_detail_visitorProps): any {
  const { url, url_addition }: any = LibNavigation.getArgsAll(props)

  const [result, setResult] = useSafeState<any>()
  const [dataAddition, setDataAddition] = useSafeState<any>()
  const [error, setError] = useSafeState<any>()

  useEffect(() => {
    loadData()
    loadDataAddition()
  }, [])

  function loadData() {
    new LibCurl(url, null, (res, msg) => {
      esp.log({ res });
      setResult(res)
    }, (err) => {
      setError(err)
    })
  }

  function loadDataAddition() {
    new LibCurl(url_addition, null, (res: any, msg: string) => {
      setDataAddition(res)
    }, (err: any) => {
      esp.mod("lib/dialog").warningConfirm(esp.lang("event/order_detail_visitor", "warning_titke"), err?.message, esp.lang("event/order_detail_visitor", "warning_back"), () => {
        esp.mod("lib/dialog").hide()
      }, "", () => { })
    })
  }

  function groupingData(additions: any[]) {
    let output: any = {};

    additions?.forEach((addition) => {
      const { booking_member_id, addition_id, addition_question, addition_option, content } = addition;

      if (!output[booking_member_id]) {
        output[booking_member_id] = {};
      }

      if (!output[booking_member_id][addition_id]) {
        output[booking_member_id][addition_id] = {
          addition_id,
          addition_question,
          values: []
        };
      }

      if (content !== null) {
        output[booking_member_id][addition_id].values.push(content);
      } else {
        output[booking_member_id][addition_id].values.push(addition_option);
      }
    })

    // const finalResult = [];

    // for (const key in output) {
    //   const entry = output[key];
    //   let result = "";

    //   for (const subKey in entry) {
    //     const question = entry[subKey].addition_question;
    //     const value = entry[subKey].values.join(', ');
    //     result += `\n${question}\n${value}`;
    //   }

    //   finalResult.push(result);
    // }

    let finalResult = [];

    for (const key in output) {
      const item = output[key];
      const resultItem = [];

      for (const questionKey in item) {
        const question = item[questionKey];
        const result = [question.addition_question, question.values.join(', ')];
        resultItem.push(result);
      }

      finalResult.push(resultItem);
    }
    return finalResult
  }

  let filterBuyerVisitor = result?.tickets?.reduce((r: any, a: any) => {
    r[a.email] = [...r[a.email] || [], a];
    return r;
  }, {});

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={esp.lang("event/order_detail_visitor", "header")} />
      {
        (!result && !error) ?
          <View style={{ marginTop: LibStyle.width * 0.5 }}>
            <LibLoading />
          </View>
          : error ? <EventMessage message={error?.message} /> :
            <ScrollView>
              <View style={{ margin: 15, borderRadius: 10, backgroundColor: '#fff', padding: 10 }}>
                {
                  Object.values(filterBuyerVisitor)?.map((item: any, i: number) => {
                    return (
                      <View key={i} style={{ marginLeft: 14, marginBottom: 15, flexDirection: 'row', alignContent: 'center', alignItems: 'center', justifyContent: 'space-between' }}>
                        <View style={{ flex: 1, flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
                          <Text allowFontScaling={false} style={{ marginRight: 6, fontFamily: "Arial", fontSize: 30, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#484848" }}>{i + 1}.</Text>
                          <View style={{ flex: 1 }} >
                            <Text allowFontScaling={false} style={{ fontFamily: "Arial", marginTop: 10, fontSize: 10, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#c3c3c3" }}>{esp.lang("event/order_detail", "buyer_name")}</Text>
                            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a", marginTop: 4 }} ellipsizeMode='tail'>{item[0].name}</Text>
                            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 10, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#c3c3c3", marginTop: 10 }}>{esp.lang("event/order_detail", "phone_number")}</Text>
                            <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a", marginTop: 4 }}>{item[0].phone.trim()}</Text>
                          </View>
                        </View>
                        <View style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
                          <Text allowFontScaling={false} style={{ marginLeft: 6, fontFamily: "Arial", fontSize: 20, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#484848" }}>{item.length}</Text>
                          <Text allowFontScaling={false} style={{ marginLeft: 4, fontFamily: "Arial", fontSize: 16, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#484848" }}>{esp.lang("event/order_detail", "ticket")}</Text>
                        </View>
                      </View>
                    )
                  })
                }

                {
                  result?.flag?.use_seat == 1 &&
                  <>
                    <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{esp.lang("event/order_detail", "seat_number")}</Text>
                    <View style={{ flexDirection: 'row', flexWrap: 'wrap', marginLeft: -10, padding: 10 }}>
                      {
                        result?.tickets?.map((item: any, i: number) => {
                          return (
                            <View key={i} style={{ paddingVertical: 5, paddingHorizontal: 7, borderWidth: 1, borderColor: '#000', backgroundColor: '#fff', borderRadius: 5, marginRight: 7 }}>
                              <Text allowFontScaling={false} style={{ fontWeight: 'bold', fontSize: 20, color: '#000' }}>{item.seat_name}</Text>
                            </View>
                          )
                        })
                      }
                    </View>
                  </>
                }
              </View>

              {
                dataAddition?.additions?.length > 0 &&
                <View style={{ margin: 15, marginTop: 0, borderRadius: 7, backgroundColor: 'white', padding: 10 }}>
                  <Text allowFontScaling={false} style={{ fontWeight: 'bold', fontSize: 14, }}>{esp.lang("event/order_detail_visitor", "ticket_holder")}</Text>
                  {
                    groupingData(dataAddition?.additions).map((add, i) => {
                      return (
                        <View key={i} style={{ marginTop: 10 }}>
                          {
                            add?.map((item: any, ii: number) => {
                              return (
                                <View key={ii} style={{ flexDirection: 'row', marginBottom: 3 }}>
                                  <Text allowFontScaling={false} style={{ flex: 1, fontSize: 12, color: '#000' }}>{item[0]}</Text>
                                  <Text allowFontScaling={false} style={{ fontSize: 12, marginHorizontal: 10, color: '#000' }}>:</Text>
                                  <Text allowFontScaling={false} style={{ flex: 2, fontSize: 12, color: '#000' }}>{item[1]}</Text>
                                </View>
                              )
                            })
                          }
                        </View>
                      )
                    })
                  }
                </View>
              }

            </ScrollView>
      }
    </View>
  )
}