import React, { useState, useEffect, useRef } from "react";
import { TouchableOpacity, View } from "react-native";
import { external } from "../../../../../../styles/externalStyle";
import { PackageItem } from "./packageItem/index";
import { useDispatch, useSelector } from "react-redux";
import { packageDataGet } from "@src/api/store/actions/packageAction";
import { BottomSheetFlatList } from "@gorhom/bottom-sheet";
import { appColors, windowHeight, windowWidth } from "@src/themes";
import { Back } from "@src/utils/icons";
import { styles } from "./style";
import { useValues } from "@src/utils/context";
import { AppDispatch } from "@src/api/store";

export function KmDetails({ onPackageSelect, onpackageVehicle, zoneValue }:any) {
  const [selectedId, setSelectedId] = useState(null);
  const { packageList } = useSelector((state:any) => state.package);
  const dispatch = useDispatch<AppDispatch>();
  const { isRTL, isDark } = useValues();
  useEffect(() => {
    if (zoneValue?.id) {
      dispatch(packageDataGet({ zone_id: zoneValue.id }));
    }
  }, [zoneValue?.id]);

  useEffect(() => {
    if (packageList?.data?.length > 0 && selectedId === null) {
      const firstItem = packageList.data[0];
      setSelectedId(firstItem.id);

      const details = {
        hour: firstItem?.hour,
        distance: firstItem?.distance,
        id: firstItem?.id,
        distanceType: firstItem?.distance_type,
        currency_symbol: firstItem?.currency_symbol,
      };
      onPackageSelect(details);
      onpackageVehicle(firstItem.vehicle_types);
    }
  }, [packageList.data]);

  const handlePress = (item:any) => {
    setSelectedId(item.id);
    const details = {
      hour: item.hour,
      distance: item.distance,
      id: item.id,
      distanceType: item.distance_type,
      currency_symbol: item?.currency_symbol,
    };
    onPackageSelect(details);
    onpackageVehicle(item.vehicle_types);
  };

  const renderItem = ({ item }:any) => (
    <PackageItem
      item={item}
      isSelected={item.id === selectedId}
      onPress={() => handlePress(item)}
    />
  );

  const flatListRef = useRef<any>(null);
  const [offset, setOffset] = useState(0);

  const itemWidth = windowWidth(120);
  const scrollStep = itemWidth * 2.1;

  const handleScroll = (direction: "left" | "right") => {
    const newOffset =
      direction === "left"
        ? Math.max(0, offset - scrollStep)
        : offset + scrollStep;

    flatListRef.current?.scrollToOffset({ offset: newOffset, animated: true });
    setOffset(newOffset);
  };

  return (
    <View
      style={[
        external.mv_15,
        { marginTop: windowHeight(8), marginHorizontal: windowWidth(10) },
      ]}
    >
      <TouchableOpacity
        onPress={() => handleScroll("left")}
        style={[
          styles.backButton,
          { marginLeft: isRTL ? 0 : -windowWidth(10) },
          { marginRight: isRTL ? windowWidth(-10) : 0 },
          {
            backgroundColor: isDark
              ? appColors.primaryText
              : appColors.whiteColor,
            borderColor: isDark
              ? appColors.darkBorder
              : appColors.loaderPrimary,
          },
        ]}
      >
        <Back />
      </TouchableOpacity>
      <BottomSheetFlatList
        ref={flatListRef}
        horizontal
        data={packageList?.data || []}
        renderItem={renderItem}
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={external.mh_5}
        keyExtractor={(item:any) => item.id.toString()}
      />
      <TouchableOpacity
        onPress={() => handleScroll("right")}
        style={[
          styles.backButton,
          { marginLeft: isRTL ? -windowWidth(10) : 0 },
          { marginRight: isRTL ? 0 : windowWidth(-10), alignSelf: "flex-end" },
          { transform: [{ rotate: "180deg" }] },
          {
            backgroundColor: isDark
              ? appColors.primaryText
              : appColors.whiteColor,
            borderColor: isDark
              ? appColors.darkBorder
              : appColors.loaderPrimary,
          },
        ]}
      >
        <Back />
      </TouchableOpacity>
    </View>
  );
}
