import Styles from "@/constants/Styles";
import { useRef, useState, useEffect } from "react";
import { Animated, Pressable, View } from "react-native";
import Text from "./Text";

export default function TextExpandable({ content, maxLines }: { content: string, maxLines: number }) {
   const [isExpanded, setIsExpanded] = useState(false);
   const [shouldShowMore, setShouldShowMore] = useState(false);
   const [collapsedHeight, setCollapsedHeight] = useState(0);
   const [fullHeight, setFullHeight] = useState(0);
   const animatedHeight = useRef(new Animated.Value(0)).current;

   const measureCollapsed = (e: any) => {
      if (collapsedHeight === 0) {
         setCollapsedHeight(e.nativeEvent.layout.height);
         animatedHeight.setValue(e.nativeEvent.layout.height);
      }
   };

   const measureFull = (e: any) => {
      if (fullHeight === 0) {
         setFullHeight(e.nativeEvent.layout.height);
      }
   };

   // Cek apakah memang perlu "View More"
   useEffect(() => {
      if (collapsedHeight > 0 && fullHeight > 0) {
         setShouldShowMore(fullHeight > collapsedHeight + 1); // +1 untuk toleransi float
      }
   }, [collapsedHeight, fullHeight]);

   const toggleExpand = () => {
      Animated.timing(animatedHeight, {
         toValue: isExpanded ? collapsedHeight : fullHeight,
         duration: 300,
         useNativeDriver: false,
      }).start();
      setIsExpanded(!isExpanded);
   };

   return (
      <View>
         {/* Hidden full text for measurement */}
         <View style={Styles.hidden}>
            <Text style={Styles.textDefault} onLayout={measureFull}>
               {content}
            </Text>
         </View>

         {/* Collapsed text for measurement */}
         <View style={Styles.hidden}>
            <Text
               numberOfLines={maxLines}
               style={Styles.textDefault}
               onLayout={measureCollapsed}
               ellipsizeMode="tail"
            >
               {content}
            </Text>
         </View>

         {/* Animated visible text */}
         <Animated.View style={{ height: animatedHeight, overflow: 'hidden' }}>
            <Text
               style={Styles.textDefault}
               numberOfLines={isExpanded ? undefined : maxLines}
               ellipsizeMode="tail"
            >
               {content}
            </Text>
         </Animated.View>

         {shouldShowMore && (
            <Pressable onPress={toggleExpand}>
               <Text style={Styles.textLink}>
                  {isExpanded ? 'View Less' : 'View More'}
               </Text>
            </Pressable>
         )}
      </View>
   );
};
