import Styles from "@/constants/Styles";
import { useTheme } from "@/providers/ThemeProvider";
import { MaterialCommunityIcons } from "@expo/vector-icons";
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 { colors } = useTheme();
   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;

   useEffect(() => {
      setCollapsedHeight(0);
      setFullHeight(0);
      setShouldShowMore(false);
      setIsExpanded(false);
   }, [content]);

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

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

   useEffect(() => {
      if (collapsedHeight > 0 && fullHeight > 0) {
         setShouldShowMore(fullHeight > collapsedHeight + 1);
      }
   }, [collapsedHeight, fullHeight]);

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

   return (
      <View>
         <View style={Styles.hidden}>
            <Text style={Styles.textDefault} onLayout={measureFull}>
               {content}
            </Text>
         </View>

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

         <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} style={Styles.expandBtn}>
               <Text style={[Styles.textMediumSemiBold, { color: colors.tabActive }]}>
                  {isExpanded ? 'Sembunyikan' : 'Lihat selengkapnya'}
               </Text>
               <MaterialCommunityIcons
                  name={isExpanded ? 'chevron-up' : 'chevron-down'}
                  size={16}
                  color={colors.tabActive}
               />
            </Pressable>
         )}
      </View>
   );
};
