import { Dimensions, ScrollView, Keyboard, Platform } from "react-native";
import { View } from "react-native-ui-lib";
import React, { useEffect, useRef, useState } from "react";
import GroceryList from "./GroceryList";
import { useGroceryContext } from "@/contexts/GroceryContext";

const GroceryWrapper = () => {
  const { isAddingGrocery } = useGroceryContext();
  const scrollViewRef = useRef<ScrollView>(null);
  const [keyboardHeight, setKeyboardHeight] = useState(0);

  useEffect(() => {
    const keyboardWillShowListener = Keyboard.addListener(
      Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow',
      (e) => {
        setKeyboardHeight(e.endCoordinates.height);
      }
    );

    const keyboardWillHideListener = Keyboard.addListener(
      Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide',
      () => {
        setKeyboardHeight(0);
      }
    );

    return () => {
      keyboardWillShowListener.remove();
      keyboardWillHideListener.remove();
    };
  }, []);

  useEffect(() => {
    if (isAddingGrocery && scrollViewRef.current) {
      scrollViewRef.current.scrollTo({
        y: 400,
        animated: true,
      });
    }
  }, [isAddingGrocery]);

  const handleInputFocus = (y: number) => {
    if (scrollViewRef.current) {
      const windowHeight = Dimensions.get('window').height;
      const topSpacing = 20;
      
      const scrollPosition = Math.max(0, y - topSpacing);

      scrollViewRef.current.scrollTo({
        y: scrollPosition,
        animated: true,
      });
    }
  };

  return (
    <>
      <ScrollView
        ref={scrollViewRef}
        automaticallyAdjustKeyboardInsets={true}
        showsHorizontalScrollIndicator={false}
        showsVerticalScrollIndicator={false}
      >
        <View marginB-60>
          <GroceryList onInputFocus={handleInputFocus} />
        </View>
      </ScrollView>
    </>
  );
};

export default GroceryWrapper;