// withHooks
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 { LibUtils } from 'esoftplay/cache/lib/utils/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';

import { applyStyle } from 'esoftplay';
import React, { useEffect } from 'react';
import { Pressable, Text, TouchableOpacity, View } from 'react-native';
import Animated, { Extrapolate, interpolate, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue } from 'react-native-reanimated';


export interface EventSeatArgs {

}
export interface EventSeatProps {

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

  const [result, setResult] = useSafeState<any>(undefined)
  const [counter, setCounter] = useSafeState<any>(0)
  const [resultDataSize, setResultDataSize] = useSafeState<any>(0)
  const [sizeBox, setSizeBox] = useSafeState(10)

  const translationX = useSharedValue(0);
  const translationY = useSharedValue(0);

  const [completeScrollBarHeight, setCompleteScrollBarHeight] = useSafeState(1); // ini itu tinggu yang ditampilkan scroll
  const [visibleScrollBarHeight, setVisibleScrollBarHeight] = useSafeState(0); // ini itu tinggu seluruh scroll

  const [completeScrollBarWidth, setCompleteScrollBarWidth] = useSafeState(1); // ini itu lebar yang ditampilkan scroll
  const [visibleScrollBarWidth, setVisibleScrollBarWidth] = useSafeState(0); // ini itu lebar seluruh scroll

  const scrollIndicatorHeightSize = completeScrollBarHeight > visibleScrollBarHeight ? (visibleScrollBarHeight * visibleScrollBarHeight) / completeScrollBarHeight : visibleScrollBarHeight;
  const scrollIndicatorWidthSize = completeScrollBarWidth > visibleScrollBarWidth ? (visibleScrollBarWidth * visibleScrollBarWidth) / completeScrollBarWidth : visibleScrollBarWidth;

  const scrollHandlerX = useAnimatedScrollHandler((event) => {
    translationX.value = (event.contentOffset.x);
  })

  const scrollHandlerY = useAnimatedScrollHandler((event) => {
    translationY.value = (event.contentOffset.y);
  })

  const styleX = useAnimatedStyle(() => {
    const transfX = interpolate(
      translationX.value,
      [0, completeScrollBarWidth],
      [0, visibleScrollBarWidth],
      Extrapolate.CLAMP
    )

    return {
      transform: [{ translateX: transfX, }],
    };
  })

  const styleY = useAnimatedStyle(() => {
    const transfY = interpolate(
      translationY.value,
      [0, completeScrollBarHeight],
      [0, visibleScrollBarHeight],
      Extrapolate.CLAMP
    )

    return {
      transform: [{ translateY: transfY, }],
    };
  })

  const explanation = [
    {
      borderColor: LibStyle.colorBlue,
      backgroundColor: "#fff",
      text: esp.lang("event/seat", "text_available")
    },
    {
      borderColor: LibStyle.colorBlue,
      backgroundColor: LibStyle.colorBlue,
      text: esp.lang("event/seat", "text_selected")
    },
    {
      borderColor: LibStyle.colorGrey,
      backgroundColor: LibStyle.colorGrey,
      text: esp.lang("event/seat", "text_not_available")
    },
  ]

  useEffect(() => {
    loadDataSize()
  }, [])

  function loadDataSize() {
    let post = {
      event_id: dataTicket?.event_id,
      price_id: dataTicket?.selected_ticket?.list?.price_id || dataTicket?.selected_ticket?.price_id,
      ondate: dataTicket?.selected_ticket?.list?.ondate,
    }
    new LibCurl("event_seat_meta", post, (res, msg) => { // event_seat
      setResultDataSize(res)
      loadSeat("event_seat?offset_row=1&offset_column=1")
      // if (Number(res.seat_column) * Number(res.seat_row) > 100) {
      //   // untuk menampilkan button pilih ulang kalo misal di navigate terus di back lagi, biar tidak loading
      //   setResult('none')
      //   LibNavigation.navigateForResult('event/seat_map', {
      //     x: res.seat_column,
      //     y: res.seat_row,
      //     url: url,
      //     event_id: event_id,
      //     price_id: price_id,
      //     on_date: on_date,
      //   }, 345).then((item: any) => {
      //     setResult(undefined)
      //     loadSeat(item)
      //   })
      // } else {
      //   loadSeat("event_seat?offset_row=1&offset_column=1")
      // }
    }, (error) => {
      LibDialog.warning(esp.lang("event/seat", "load_failed"), error?.message)
      // LibNavigation.back()
    })
  }

  function loadSeat(_url?: string) {
    let post = {
      event_id: dataTicket?.event_id,
      price_id: dataTicket?.selected_ticket?.list?.price_id || dataTicket?.selected_ticket?.price_id,
      ondate: dataTicket?.selected_ticket?.list?.ondate,
    }
    new LibCurl(_url ? _url : url, post, (res, msg) => { // event_seat
      for (let i = 0; i < res.length; i++) {
        const element = res[i];
        element.map((item: any) => {
          item.check = false
        })
      }
      setResult(res)
      if (res.image_map != "") {
        LibDialog.custom(viewImageMap(res.image_map))
      }
    }, (error) => {
      LibDialog.warning(esp.lang("event/seat", "load_seat_failed"), error?.message)
      LibNavigation.back()
    }, 1)
  }

  function next() {
    if (dataTicket?.qty != counter) {
      LibToastProperty.show(esp.lang("event/seat", "select_seat"))
      return
    }

    let _selectSeat: any[] = []
    result?.list?.length > 0 && result?.list?.map((row: any) => row?.map((col: any) => {
      if (col.check) {
        _selectSeat.push(col)
      }
    }))

    let _rowId = _selectSeat.filter((item: any) => item.check).map((it: any) => it.row)
    let _colId = _selectSeat.filter((item: any) => item.check).map((it: any) => it.column)
    let _seatName = _selectSeat.filter((item: any) => item.check).map((it: any) => it.name)
    let value = {
      column_id: _colId.join('|'),
      row_id: _rowId.join('|'),
      seat_name: _seatName
    }
    LibNavigation.sendBackResult(value)
  }

  const viewImageMap = (image: string) => {
    return (
      <View>
        <TouchableOpacity onPress={() => {
          // LibNavigation.navigate('lib/gallery', { image: result?.image_map })
        }}>
          <LibPicture source={{ uri: image }} style={{ width: LibStyle.width - 100, height: LibStyle.width - 100, borderRadius: 10 }} resizeMode="contain" />
        </TouchableOpacity>
        <TouchableOpacity onPress={() => { LibDialog.hide() }} style={{ marginTop: 10, alignContent: 'center', alignItems: 'center', justifyContent: 'center' }}>
          <LibIcon name="close-circle-outline" color={LibStyle.colorPrimary} size={30} />
        </TouchableOpacity>
      </View>
    )
  }

  function alertSelectSeat() {
    LibToastProperty.show(esp.lang("event/seat", "seat_reselect", dataTicket?.qty), 5000)
  }

  const toggleSeat = (col: any, i: number, i1: number) => {
    return () => {
      if (col.status == "1") {
        if (!col.check && counter + 1 > dataTicket?.qty) {
          alertSelectSeat()
        } else {
          setResult(LibObject.set(result, !col.check)('list', i, i1, "check"))
          setCounter(!col.check ? counter + 1 : counter - 1)
        }
      }
    }
  }


  function renderStyleSeat(col: any) {
    return {
      colorBackground: col.status == "1" ? (col.check ? LibStyle.colorBlue : "#fff") : (col.status == 3 || col.status == 4) ? "#c9c9c9" : "#fff",
      colorBorder: col.status == "1" ? (col.check ? LibStyle.colorBlue : LibStyle.colorBlue) : "#fff",
      fontColor: (col.status == 2 || col.status == 3 || col.status == 4) ? "#fff" : col.check ? "#fff" : "#666",
    }
  }

  const margin = sizeBox / 9
  const fontSize = sizeBox / 3
  function renderRow(row: any, i: number) {
    return (
      <View key={i} style={applyStyle({ marginLeft: 5, marginRight: 5, flexDirection: 'row' })}>
        {
          row?.map((col: any, i1: number) => {
            const { colorBackground, colorBorder, fontColor } = renderStyleSeat(col)
            return (
              <TouchableOpacity onPress={toggleSeat(col, i, i1)} key={i1} style={applyStyle({ margin: margin, marginBottom: 0, marginRight: sizeBox / 9, marginLeft: margin, height: sizeBox, width: sizeBox, backgroundColor: colorBackground, borderWidth: 1, borderColor: colorBorder, borderRadius: 4, justifyContent: 'center', alignContent: 'center', alignItems: 'center' })}>
                <Text allowFontScaling={false} style={applyStyle({ fontFamily: "Arial", fontSize: fontSize, fontWeight: "normal", textAlign: 'center', fontStyle: "normal", letterSpacing: 0, color: fontColor })}>{col.name}</Text>
              </TouchableOpacity>
            )
          })
        }
      </View>
    )
  }

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

  return (
    <View style={{ flex: 1, backgroundColor: '#fff' }}>
      <EventHeader title={esp.lang("event/seat", "header_title_select")} subtitle={dataTicket?.selected_ticket?.type} />
      {
        !result ?
          <LibLoading />
          :
          result == "none" ?
            <View style={{ flex: 1, margin: 10, marginBottom: 0, justifyContent: 'center', alignContent: 'center', alignItems: 'center' }}>
              <TouchableOpacity onPress={() => {
                LibNavigation.navigateForResult('event/seat_map', {
                  x: resultDataSize.seat_column,
                  y: resultDataSize.seat_row,
                  url: url,
                  event_id: dataTicket?.event_id,
                  price_id: dataTicket?.selected_ticket?.list?.price_id || dataTicket?.selected_ticket?.price_id,
                  ondate: dataTicket?.selected_ticket?.list?.ondate,
                }, 345).then((item: any) => {
                  setResult(undefined)
                  loadSeat(item)
                })
              }} style={{ alignContent: 'center', alignItems: 'center', padding: 10, borderRadius: 5, backgroundColor: LibStyle.colorPrimary }}>
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontStyle: "normal", letterSpacing: 0, color: '#000' }}>{esp.lang("event/seat", "reselect")}</Text>
              </TouchableOpacity>
            </View>
            :
            <>
              <View style={{ margin: 10, marginBottom: 0, flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
                <View style={{ flex: 1 }}>
                  {/* {
                      Number(resultDataSize.seat_column) * Number(resultDataSize.seat_row) > 100 &&
                      <TouchableOpacity onPress={() => {
                        LibNavigation.navigateForResult('event/seat_map', {
                          x: resultDataSize.seat_column,
                          y: resultDataSize.seat_row,
                          url: url,
                          event_id: event_id,
                          price_id: price_id,
                          on_date: on_date,
                        }, 345).then((item: any) => {
                          setResult(undefined)
                          loadSeat(item)
                        })
                      }} style={{ marginRight: 20, alignContent: 'center', alignItems: 'center', padding: 5, borderRadius: 5, backgroundColor: LibStyle.colorPrimary }}>
                        <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontStyle: "normal", letterSpacing: 0, color: '#000' }}>Pilih Ulang</Text>
                      </TouchableOpacity>
                    } */}
                </View>
                <View style={{ flex: 1, alignContent: 'center', alignItems: 'center' }}>
                  <Text allowFontScaling={false} style={{ textAlign: 'center', fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: '#000' }}>{dataTicket?.selected_ticket?.type}</Text>
                </View>
                {
                  result?.image_map != "" ?
                    <TouchableOpacity onPress={() => {
                      if (result?.image_map == "") {
                        LibToastProperty.show(esp.lang("event/seat", "empty_image"))
                      } else {
                        LibDialog.custom(viewImageMap(result?.image_map))
                      }
                    }} style={{ flex: 1, justifyContent: 'flex-end', alignContent: 'flex-end', alignItems: 'flex-end' }} hitSlop={{ top: 10, left: 10, right: 10, bottom: 10 }}>
                      <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontStyle: "normal", letterSpacing: 0, color: LibStyle.colorBlue }}>{esp.lang("event/seat", "show_map")}</Text>
                    </TouchableOpacity>
                    :
                    <View style={{ flex: 1 }} />
                }
              </View>

              <View style={{ margin: 30, marginTop: 10, marginBottom: 10, borderBottomLeftRadius: 15, borderBottomRightRadius: 15, padding: 5, justifyContent: 'center', alignItems: 'center', alignContent: 'center', backgroundColor: LibStyle.colorGreen }}>
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: '#fff' }}>{esp.lang("event/seat", "front")}</Text>
              </View>

              <View key={sizeBox} style={{ flex: 3, marginVertical: 10 }}>
                <View style={{ flex: 1, flexDirection: 'row', margin: 10, marginVertical: 0 }} >
                  <Animated.ScrollView
                    horizontal
                    scrollEventThrottle={16}
                    overScrollMode="never"
                    showsHorizontalScrollIndicator={false}
                    onContentSizeChange={(width, height) => {
                      setCompleteScrollBarWidth(width)
                    }}
                    onLayout={(x) => {
                      setVisibleScrollBarWidth(x.nativeEvent.layout.width)
                    }}
                    onScroll={scrollHandlerX}>
                    <Animated.ScrollView
                      scrollEventThrottle={16}
                      overScrollMode="never"
                      showsVerticalScrollIndicator={false}
                      onContentSizeChange={(width, height) => {
                        setCompleteScrollBarHeight(height)
                      }}
                      onLayout={(x) => {
                        setVisibleScrollBarHeight(x.nativeEvent.layout.height)
                      }}
                      onScroll={scrollHandlerY}>
                      <View>
                        {result?.list?.map?.(renderRow)}
                      </View>
                    </Animated.ScrollView>
                  </Animated.ScrollView>
                  <View style={{ width: 8, height: "100%", backgroundColor: "#c9c9c9", borderRadius: 4 }}>
                    <Animated.View style={[{ width: 8, height: scrollIndicatorHeightSize, backgroundColor: LibStyle.colorPrimary, borderRadius: 4 }, styleY]} />
                  </View>
                </View>
                <View style={{ width: LibStyle.width - 28, margin: 10, height: 8, backgroundColor: "#c9c9c9", borderRadius: 4 }}>
                  <Animated.View style={[{ width: scrollIndicatorWidthSize, height: 8, backgroundColor: LibStyle.colorPrimary, borderRadius: 4 }, styleX]} />
                </View>
              </View>
              <View style={{ flexDirection: 'row', justifyContent: 'space-around' }} >
                <Pressable
                  style={{ opacity: sizeBox == 10 ? 0.2 : 1, height: 60, borderRadius: 30, ...LibStyle.elevation(3), backgroundColor: 'white', width: 60, justifyContent: 'center', alignItems: 'center' }}
                  onPress={() => setSizeBox(sizeBox >= 20 ? sizeBox - 10 : 10)} >
                  <LibIcon.MaterialIcons name='zoom-out' size={24} />
                </Pressable>
                <Pressable
                  style={{ opacity: sizeBox == 40 ? 0.2 : 1, height: 60, borderRadius: 30, ...LibStyle.elevation(3), backgroundColor: 'white', width: 60, justifyContent: 'center', alignItems: 'center' }}
                  onPress={() => setSizeBox(sizeBox <= 30 ? sizeBox + 10 : 40)} >
                  <LibIcon.MaterialIcons name='zoom-in' size={24} />
                </Pressable>
              </View>

              <View style={{ flex: 0.1 }} />

              <View style={{ paddingVertical: 10, paddingHorizontal: 10 }} >
                <View style={{ marginHorizontal: 0, margin: 10, marginBottom: 15, flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
                  <Text allowFontScaling={false} style={{ marginLeft: 5, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: '#999' }}>{esp.lang("event/seat", "select_seat_1", LibUtils.number(dataTicket?.qty - counter))}</Text>
                  <View style={{ flexDirection: 'row' }}>
                    {
                      explanation.map((item, i) => {
                        return (
                          <View key={i} style={{ flexDirection: 'row', alignContent: 'center', justifyContent: 'center', alignItems: 'center', marginRight: 5 }}>
                            <View key={i} style={{ height: 20, width: 20, borderRadius: 4, borderWidth: 1, borderColor: item.borderColor, backgroundColor: item.backgroundColor }} />
                            <Text allowFontScaling={false} style={{ marginLeft: 5, fontFamily: "Arial", fontSize: 8, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: '#999' }}>{item.text}</Text>
                          </View>
                        )
                      })
                    }
                  </View>
                </View>
                <EventButton label={esp.lang("event/seat", "next")} onPress={() => {
                  next()
                }} style={{ backgroundColor: dataTicket?.qty != counter ? LibStyle.colorGrey : LibStyle.colorPrimary }} />
              </View>
            </>
      }
    </View>
  )
}