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

import { Canvas, Group, Path, Skia } from '@shopify/react-native-skia';
import { applyStyle } from 'esoftplay';
import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventCheckout } from 'esoftplay/cache/event/checkout/import';
import { EventTicket } from 'esoftplay/cache/event/ticket/import';
import { LibCurl } from 'esoftplay/cache/lib/curl/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 { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { UseCondition } from 'esoftplay/cache/use/condition/import';
import esp from 'esoftplay/esp';
import useLazyState from 'esoftplay/lazy';
import moment from 'esoftplay/moment';
import useSafeState from 'esoftplay/state';
import { useTimeout } from 'esoftplay/timeout';
import React, { useEffect, useMemo } from 'react';
import { Dimensions, Pressable, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';

const { width: SCREEN_WIDTH, height } = Dimensions.get('window');

export interface EventLayoutArgs {

}
export interface EventLayoutProps {
  result: any,
  is_multiprice: boolean,
  priceTypes: any,
}

interface PassType {
  id: string,
  price_ids: string[],
  title: string,
  description: string
  date: string,
  disabled: boolean
}

export default function m(props: EventLayoutProps): any {
  const { result, priceTypes } = props
  const sliding = useRef<LibSlidingup>(null)
  const showTicket = useRef<LibSlidingup>(null)
  const [data, setData, getData] = useSafeState<any>()
  const [selectedId, setSelectedId] = useLazyState<string | null>(null);
  // const filterData: PassType[] = result?.passes
  const [selectedFilter, setSelectedFilter, getSelectedFilter] = useLazyState<string>()
  const [ondate, setOndate, getOndate] = useLazyState<any>(null)
  const [idsArray, setIdsArray, getIdsArray] = useLazyState<string[]>()

  const [filterData, setFilterData, getFilterData] = useLazyState<PassType[]>()

  const timeout = useTimeout()

  const [expanded, setExpanded] = useSafeState<boolean>(false);
  const LIMIT = 4

  useEffect(() => {
    loadFilter()
    timeout(() => {
      sliding.current?.show?.()
    }, 300);
  }, [])


  function buildUrl(url: string): string {
    url += url.includes('?') ? '&' : '?'
    url += 'ondate=' + moment().format('YYYY-MM-DD')
    return url
  }

  function loadFilter() {
    const url = buildUrl("v3/event_seat_filter?event_id=" + result?.id)
    new LibCurl(url, null,
      (result) => {
        setFilterData(result)()
      },
      (error) => {

      })
  }

  function loadOutline() {
    const url = buildUrl("v3/event_seat_outline?event_id=" + result?.id)
    new LibCurl(url, null,
      (result) => {
        setData(result)
      },
      (error) => { }, 1)
  }

  // 1. Calculations (Keep your existing path logic)
  const { globalBBox, processedItems, scale } = useMemo(() => {
    let minX = Infinity; let minY = Infinity;
    let maxX = -Infinity; let maxY = -Infinity;

    const items = getData() && getData()?.map?.((item: any) => {
      const path = Skia.Path.Make();
      item.outline.forEach((poly: any) => {
        if (poly.length < 4) return;
        path.moveTo(poly[0] + item.bbox.x1, poly[1] + item.bbox.y1);
        for (let i = 2; i < poly.length; i += 2) {
          path.lineTo(poly[i] + item.bbox.x1, poly[i + 1] + item.bbox.y1);
        }
        path.close();
      });
      const bounds = path.getBounds();
      minX = Math.min(minX, bounds.x);
      minY = Math.min(minY, bounds.y);
      maxX = Math.max(maxX, bounds.x + bounds.width);
      maxY = Math.max(maxY, bounds.y + bounds.height);
      return { id: item.price_ids.join(), path, color: item.color, price: item.price, ondate: item?.ondate };
    });

    const currentScale = (SCREEN_WIDTH - 30) / (maxX - minX || 1); //30 buat padding
    return { globalBBox: { minX, minY }, processedItems: items, scale: currentScale };
  }, [data]);

  // 2. Define the Tap Gesture
  const tapGesture = Gesture.Tap()
    .runOnJS(true) // Required to trigger State/Alerts
    .onStart((e) => {
      const { x, y } = e;

      // Map screen touch to path coordinates
      const localX = (x / scale) + globalBBox.minX;
      const localY = (y / scale) + globalBBox.minY;


      let foundId = null;
      const ondate = getOndate()?.split("|")[2].split(",")
      for (let i = processedItems.length - 1; i >= 0; i--) {
        const proc = processedItems[i].id.split(",")
        if (processedItems[i].path.contains(localX, localY) && proc.every((v: string) => ondate.includes(v))) {
          foundId = processedItems[i].id;
          const item = processedItems[i];

          setIdsArray(item.id.split(","))()
          showTicket.current?.show?.()

          break;
        }
      }
      setSelectedId(foundId)()
    });

  const filterD = filterData && filterData.length > 0 && filterData || []
  const displayedData = expanded ? filterD : filterD?.slice(0, LIMIT)

  return (
    <View style={{ flex: 1 }}>
      <View style={{ flexDirection: "row", padding: 15, justifyContent: 'flex-end' }}>
        <Pressable onPress={() => {
          sliding.current?.show?.()
        }} style={{ flexDirection: "row", borderRadius: 10, paddingVertical: 5, paddingHorizontal: 10, backgroundColor: '#eee', alignItems: 'center' }}>
          <Text allowFontScaling={false} style={{ color: "#4a4a4a" }}>{ondate ? ondate.split("|")[1] == "null" ? moment(ondate.split("|")[0]).format("DD MMM YYYY") : ondate.split("|")[1] : "Pilih Tanggal"}</Text>
          <LibIcon name='chevron-down' size={20} color='#4a4a4a' />
        </Pressable>
      </View>

      <UseCondition if={!!ondate} fallback={
        <View style={{ flex: 1, alignItems: "center", marginTop: 40 }}>
          <Text allowFontScaling={false} style={{ color: "#4a4a4a" }}>{"Silahkan pilih tanggal terlebih dahulu"}</Text>
        </View>
      } >
        <View style={{ flex: 1, padding: 15 }}>
          {
            !data ? <LibLoading /> :
              <GestureDetector gesture={tapGesture}>
                {/* Ensure the Canvas has a background or flex to fill the detector */}
                <Canvas style={{ flex: 1 }}>
                  <Group transform={[
                    { translateX: -globalBBox.minX * scale },
                    { translateY: -globalBBox.minY * scale },
                    { scale }
                  ]}>
                    {processedItems && processedItems?.length > 0 && processedItems?.map?.(({ id, path, color, }: any) => {
                      const fixedId = id?.split(",")
                      const fixedOndate = getOndate()?.split("|")[2].split(",")
                      const isSelected = selectedId === id;
                      const baseOpacity = selectedId === null || isSelected ? 1 : 0.3;
                      const shapeColor = fixedId.every((v: string) => fixedOndate.includes(v)) ? color : "#e6e6e6"
                      const borderColor = isSelected ? "white" : shapeColor

                      return (
                        <Group key={id}>
                          <Path
                            path={path}
                            color={shapeColor}
                            style="fill"
                            opacity={baseOpacity}
                            antiAlias={true}
                          />

                          <Path
                            path={path}
                            color={borderColor}
                            style="stroke"
                            strokeWidth={1 / scale}
                            opacity={baseOpacity * 0.8}
                            antiAlias={true}
                          />
                        </Group>
                      );
                    })}
                  </Group>
                </Canvas>
              </GestureDetector>
          }
        </View>
      </UseCondition>


      <LibSlidingup ref={sliding}>
        <View style={{ borderTopRightRadius: 20, borderTopLeftRadius: 20, padding: 15, backgroundColor: '#fff', maxHeight: height - (height * 0.333) }}>
          <ScrollView>
            {
              filterData && filterData?.length > 0 && displayedData.map?.((item, i) => {
                const key = `${item?.id}|${item?.title}|${item?.price_ids}`
                return (
                  <Pressable key={i} onPress={() => {
                    if (!item.disabled) {
                      setSelectedFilter(key)()
                    }
                  }} style={{ padding: 10, borderRadius: 10, borderWidth: selectedFilter == key ? 1.5 : 1, borderColor: selectedFilter == key ? LibStyle.colorGreen : "#e6e6e6", marginBottom: 8, backgroundColor: item?.disabled ? "#f5f5f5" : "white" }}>
                    <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 14, color: "#4a4a4a" }}>{item?.title || moment(item?.id).format("DD MMMM YYYY")}</Text>
                    {
                      !!item?.description && item?.description != "" &&
                      <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, color: "#999", marginTop: 5 }}>{item?.description}</Text>
                    }
                  </Pressable>
                )
              })
            }
            {
              filterData?.length > LIMIT &&
              <TouchableOpacity onPress={() => {
                setExpanded(x => !x)
              }} style={{ borderTopColor: LibStyle.colorGrey, borderTopWidth: 0.8, flex: 1, padding: 8, flexDirection: 'row', alignContent: 'center', alignItems: 'center', justifyContent: 'center' }}>
                <Text allowFontScaling={false} style={{ marginRight: 5, fontFamily: "Arial", fontSize: 12, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: LibStyle.colorBlue }}>{expanded ? esp.lang("event/ticket_list", "see_less") : esp.lang("event/ticket_list", "see_more")}</Text>
                <LibIcon name={expanded ? 'chevron-up-circle-outline' : 'chevron-down-circle-outline'} color={LibStyle.colorBlue} size={18} />
              </TouchableOpacity>
            }
          </ScrollView>
          <EventButton
            label='Pilih Tipe Tiket'
            backgroundColor={selectedFilter ? LibStyle.colorGreen : "#ccc"}
            onPress={() => {
              if (getSelectedFilter()) {
                setIdsArray([])
                setSelectedId(null)
                setOndate(getSelectedFilter())()
                loadOutline()
                sliding.current?.hide?.()
              }
            }}
          />
        </View>
      </LibSlidingup>

      <LibSlidingup ref={showTicket}>
        <View style={applyStyle({ backgroundColor: 'white', borderTopRightRadius: 30, borderTopLeftRadius: 30, paddingTop: 15, maxHeight: LibStyle.height - (LibStyle.height / 3) })}>
          {
            idsArray && priceTypes && priceTypes?.length > 0 &&
            <EventTicket
              multiprice={props?.is_multiprice}
              priceList={priceTypes?.filter?.((x: any) => idsArray.includes(x.price_id))}
              onSelectTickets={(datas) => {
                showTicket.current?.hide()

                const tiket = datas[0]
                if (datas?.length == 0) {
                  esp.modProp("lib/toast").show(esp.lang("event/ticket_list", "ticket_not_select"), 3000)
                  return
                }
                if (tiket?.use_code == 1) {
                  function checkInvBlock() {
                    LibProgress.show(esp.lang("event/ticket_list", "wait"))
                    new LibCurl('voucher_check_validate', null, (res, msg) => {
                      LibProgress.hide()
                      if (res?.status == 1) {
                        LibNavigation.navigate('event/block_invitation', {
                          dataCheck: res,
                        })
                      } else {
                        EventCheckout().doPayment(result, tiket, tiket.qty, undefined)
                      }
                    }, (err) => {
                      LibProgress.hide()
                    })
                  }
                  checkInvBlock()
                }
                else {
                  EventCheckout().doPayment(result, tiket, tiket.qty, undefined)
                }

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

    </View>
  )
}