import React, { useCallback } from "react";
import { View, Text, StyleSheet } from "react-native";
import Animated, { useAnimatedRef } from "react-native-reanimated";
import { useNavigation } from "@react-navigation/native";
import Sortable from "react-native-sortables";
import { useFavoriteStation } from "../../stateBox/useFavoriteStation";
import { FavoriteSettingsItem } from "./FavoliteSettings/FavoiliteSettingsItem";
import { SheetHeaderItem } from "@/components/atom/SheetHeaderItem";
import { AS } from "@/storageControl";

export const FavoriteSettings = () => {
  const { favoriteStation, setFavoriteStation } = useFavoriteStation();
  const scrollableRef = useAnimatedRef();
  const { goBack } = useNavigation();
  const renderItem = useCallback((props) => {
    const { item, index } = props;
    return (
      <FavoriteSettingsItem currentStation={item} key={item[0].StationNumber} />
    );
  }, []);
  return (
    <View style={{ height: "100%", backgroundColor: "#0099CC" }}>
      <SheetHeaderItem
        title="お気に入り設定"
        LeftItem={{ title: "＜ 設定", onPress: goBack }}
      />
      <Animated.ScrollView
        style={{ flex: 1, backgroundColor: "white" }}
        contentContainerStyle={styles.contentContainer}
        ref={scrollableRef}
      >
        <Sortable.Grid
          columnGap={0}
          columns={1}
          data={favoriteStation}
          renderItem={renderItem}
          rowGap={0}
          scrollableRef={scrollableRef} // required for auto scroll
          snapOffsetY={0}
          onDragEnd={(newOrder) => {
            const newFavoriteStation = newOrder.indexToKey.map(
              (item, index, array) => {
                let returnData = [];
                favoriteStation.forEach((station) => {
                  if (station[0].StationNumber === item) returnData = station;
                });
                return returnData;
              }
            );
            setFavoriteStation(newFavoriteStation);
            AS.setItem("favoriteStation", JSON.stringify(newFavoriteStation));
          }}
          keyExtractor={(item) => item[0].StationNumber}
        />
      </Animated.ScrollView>
      <Text
        style={{
          backgroundColor: "white",
          borderWidth: 1,
          borderStyle: "solid",
        }}
      >
        お気に入り登録した駅を並び替えることができます。一番上に置いた駅が位置情報の起動時に表示されます。(移動不可能な駅の場合エラーが発生します。任意指定が可能になる機能を開発予定です。)
      </Text>
    </View>
  );
};

const styles = StyleSheet.create({
  card: {
    alignItems: "center",
    backgroundColor: "#36877F",
    borderRadius: 10,
    height: 100,
    justifyContent: "center",
  },
  contentContainer: {
    padding: 10,
  },
  text: {
    color: "white",
    fontWeight: "bold",
  },
});
