// withHooks
import { Canvas, Group, RoundedRect, Text, useFont } from '@shopify/react-native-skia';
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 { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { UseMap } from 'esoftplay/cache/use/map/import';
import esp from 'esoftplay/esp';
import useLazyState from 'esoftplay/lazy';
import useSafeState from 'esoftplay/state';
import React, { useCallback, useEffect, useState } from 'react';
import { Dimensions, Pressable, ScrollView, View } from 'react-native';
import { TapGestureHandler, TapGestureHandlerStateChangeEvent } from 'react-native-gesture-handler';


export interface EventSeat_map_matrixArgs {

}
export interface EventSeat_map_matrixProps {

}
export default function m(props: any): any {
  const deviceWidth = Dimensions.get('window').width;
  const [selectedIdx, setSelectedIdx] = useState<number | null>(null);
  const [scale, setScale] = useState(1);
  const [boundingBox, setBoundingBox] = useSafeState({ "x1": 1, "x2": 2, "y1": 1, "y2": 2 })
  const [data, setData, getData] = useSafeState<[number, number, string, number][]>([])
  const initialBoxSize = 30;
  const contentWidth = (boundingBox.x2 - (boundingBox.x1 - 1.1)) * initialBoxSize
  const [stage, setStage] = useLazyState('')

  // Scale boxSize so that contentWidth fits deviceWidth
  const scaleToFit = deviceWidth / contentWidth;
  const boxSize = initialBoxSize * scaleToFit;

  // Recalculate xs, ys, width, height with scaled boxSize
  const xsScaled = data.map(([x]) => isNaN(x) ? 0 : (boxSize) + (x * boxSize));
  const ysScaled = data.map(([_, y]) => isNaN(y) ? 0 : (boxSize) + (y * boxSize));

  const width = Math.max(deviceWidth, xsScaled.length && xsScaled.every(v => !isNaN(v)) ? Math.max(...xsScaled) + boxSize : boxSize * 2);
  const height = ysScaled.length && ysScaled.every(v => !isNaN(v)) ? Math.max(...ysScaled) + boxSize : boxSize * 2;

  const size: any = {
    1: useFont(esp.assets('fonts/MonoSpace.ttf'), boxSize * 0.3),
    2: useFont(esp.assets('fonts/MonoSpace.ttf'), boxSize * 0.3),
    3: useFont(esp.assets('fonts/MonoSpace.ttf'), boxSize * 0.25),
    4: useFont(esp.assets('fonts/MonoSpace.ttf'), boxSize * 0.2),
    5: useFont(esp.assets('fonts/MonoSpace.ttf'), boxSize * 0.2),
    6: useFont(esp.assets('fonts/MonoSpace.ttf'), boxSize * 0.15),
  }
  const handleTap = useCallback((event: TapGestureHandlerStateChangeEvent) => {
    if (event.nativeEvent.state !== 5) return;
    // Adjust tap coordinates for scale
    const x = event.nativeEvent.x / scale;
    const y = event.nativeEvent.y / scale;
    for (let i = 0; i < data.length; i++) {
      const [sx, sy, seatName, status] = data[i];
      const xSize = (boxSize / 2) + (sx * boxSize);
      const ySize = (boxSize / 2) + (sy * boxSize);

      if (x >= xSize && x <= xSize + boxSize && y >= ySize && y <= ySize + boxSize) {
        if (status == 0) {
          setSelectedIdx(i);
        } /* else {
          setSelectedIdx(null);
        } */
        return;
      }

    }
  }, [data, boxSize, scale]);

  useEffect(() => {
    new LibCurl("v3/event_seat", {
      event_id: 398,
      price_id: 1922,
      ondate: "0000-00-00"
    }, (res, msg) => {
      setBoundingBox(res.metadata.bounding_box)
      setData(res.layout.split(';').map((item: any) => item.split(',')).map(([x, y, seatName, status]: any) => [Number(x), Number(y), seatName, Number(status)]))
    })

    loadDataSeatmapBooked()

  }, [])

  function updateIndexByRes(data: any, res: any) {
    const resArr = res.split(",").map((item: any) => item.trim()); // biar aman dari spasi
    return data.map((row: any) => {
      if (resArr.includes(row[2])) {
        return [row[0], row[1], row[2], 3];
      }
      return row;
    });
  }

  function loadDataSeatmapBooked() {
    new LibCurl("v3/event_seat_booked", {
      event_id: 398,
      price_id: 1922,
      ondate: "0000-00-00"
    }, (res, msg) => {
      let updated = updateIndexByRes(getData(), res)
      setData(updated)
      // esp.log({ updated, res });
    }, (err) => {
      esp.log({ err });
    })

  }

  return (
    <View key={scale} style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }} >
      <EventHeader title={esp.lang("event/seat_map", "header_title")} />
      <View style={{ flex: 1 }}>
        <View style={{ marginBottom: 5, }}>
          <ScrollView style={{ padding: 10, paddingLeft: 0, }} horizontal>
            <UseMap
              data={getLegends()}
              renderItem={(item) => (
                <View style={{ flexDirection: 'row', alignItems: 'center', marginLeft: 15, marginRight: 5 }} >
                  <View style={{ height: 20, width: 20, borderRadius: 2, borderWidth: 0.5, backgroundColor: item[0], marginRight: 8 }} />
                  <LibTextstyle textStyle='caption1' text={item[1]} />
                </View>
              )}
            />
          </ScrollView>
        </View>
        <View style={{ height: 40, marginLeft: 20, marginRight: 20, backgroundColor: LibStyle.colorPrimary, marginBottom: 10, borderRadius: 2, justifyContent: 'center', alignItems: 'center' }} >
          <LibTextstyle textStyle='body' style={{ color: 'white', fontWeight: 'bold' }} >{stage || esp.lang("event/seat_map", "front")}</LibTextstyle>
        </View>

        <ScrollView horizontal >
          <ScrollView >
            <TapGestureHandler onHandlerStateChange={handleTap}>
              <View>
                <Canvas
                  style={{
                    width: width * scale,
                    height: height * scale,
                    padding: 10,
                    backgroundColor: LibStyle.colorBgGrey,

                  }}>
                  {
                    data.map(([x, y, name, status], i) => {
                      const color = selectedIdx == i ? "#8EF67B" : getColorByStatus(status)
                      const xSize = (boxSize / 2) + (x * boxSize)
                      const ySize = (boxSize / 2) + (y * boxSize)
                      return (
                        <Group key={i}>
                          <RoundedRect
                            x={xSize - 1}
                            r={(boxSize + 2) * 0.1}
                            y={ySize - 1}
                            width={boxSize + 2}
                            transform={[{ scale }]}
                            height={boxSize + 2}
                            color={"#999"} />
                          <RoundedRect
                            x={xSize}
                            r={boxSize * 0.1}
                            y={ySize}
                            width={boxSize}
                            transform={[{ scale }]}
                            height={boxSize}
                            color={color} />
                          {name && size[name.length] && (
                            <Text
                              x={(xSize) + boxSize * (5 - name.length) * 0.1}
                              y={(ySize) + boxSize * 0.60}
                              color={"#020202"}
                              text={name}
                              transform={[{ scale }]}
                              font={size[name.length]} />
                          )}
                        </Group>
                      )
                    })
                  }
                </Canvas>
              </View>
            </TapGestureHandler>
          </ScrollView>
        </ScrollView>
        <View style={{ flexDirection: 'row', marginHorizontal: 12, height: 40, borderColor: '#060606', borderWidth: 1, borderRadius: 5, alignItems: 'center' }} >
          <Pressable onPress={() => setScale((x) => x - 0.3)} style={{ height: 40, width: 40, alignItems: 'center', justifyContent: 'center' }} >
            <LibIcon.SimpleLineIcons name='magnifier-remove' />
          </Pressable>
          <Pressable onPress={() => setScale((x) => x + 0.3)} style={{ height: 40, width: 40, alignItems: 'center', justifyContent: 'center' }} >
            <LibIcon.SimpleLineIcons name='magnifier-add' />
          </Pressable>
          <View style={{ height: 40, width: 1, backgroundColor: '#060606', marginRight: 12 }} />
          {/* <Text style={{}} >{esp.lang("event/seat_map", "selected", String(data.filter((x) => x == -1).length), qty)}</Text> */}
          <LibTextstyle textStyle='callout'>{"Kursi terpilih"}</LibTextstyle>
        </View>
        <EventButton
          backgroundColor={LibStyle.colorPrimary}
          testID={"save_btn"}
          style={{ margin: 7 }}
          label={esp.lang("event/seat_map", "save")}
          onPress={() => { }}
        />
      </View>
    </View>
  )
}

function getLegends() {
  const colors: any = [
    ["#fff", esp.lang("event/seat_map", "available"), 0],
    // ["#8EF67B", esp.lang("event/seat_map", "chosen"), "-1"],
    ["#2EBBE8", esp.lang("event/seat_map", "reserved"), 3],
    // ["#6C432C", esp.lang("event/seat_map", "chosen_by"), 7],
    // ["#f1f2f3", esp.lang("event/seat_map", "way"), 5],
    // ["#9FA1A4", esp.lang("event/seat_map", "not_sold"), 1],
    ["#6B71E6", esp.lang("event/seat_map", "seat_hold"), 2],
    // ["#FF4866", esp.lang("event/seat_map", "wall"), 6],
    // ["#FFA601", esp.lang("event/seat_map", "other_type"), 4],
    // ["purple", esp.lang("event/seat_map", "stage"), 8]
  ]
  return colors
}

function getColorByStatus(statuses: number) {
  const colors: any = {
    8: 'purple',
    0: '#fff',
    1: "#9FA1A4",
    2: "#6B71E6",
    3: "#2EBBE8",
    4: "#FFA601",
    5: "#fff",
    6: "#FF4866",
    7: "#6C432C"
  }
  return colors[statuses]
}