import React, { useState } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  LayoutChangeEvent,
  Dimensions,
  StyleSheet,
} from "react-native";
import RenderHTML from "react-native-render-html";
import { Ionicons } from "@expo/vector-icons";
import { LinearGradient } from "expo-linear-gradient";

const MAX_HEIGHT = 300;

const ProductHTMLContent = ({ htmlContent }: { htmlContent: string }) => {
  const [showFull, setShowFull] = useState(false);
  const [contentHeight, setContentHeight] = useState(0);
  const [shouldShowToggle, setShouldShowToggle] = useState(false);

  const onContentLayout = (event: LayoutChangeEvent) => {
    const height = event.nativeEvent.layout.height;
    setContentHeight(height);
    if (height > MAX_HEIGHT) {
      setShouldShowToggle(true);
    }
  };

  return (
    <View style={styles.container}>
      <View
        style={[
          !showFull && shouldShowToggle
            ? { maxHeight: MAX_HEIGHT, overflow: "hidden" }
            : null,
        ]}
        onLayout={onContentLayout}
      >
        <RenderHTML
          contentWidth={Dimensions.get("window").width - 32}
          source={{ html: htmlContent }}
        />
      </View>

      {!showFull && shouldShowToggle && (
        <LinearGradient
          colors={["transparent", "#ffffff"]}
          style={styles.fadeGradient}
          pointerEvents="none"
        />
      )}

      {shouldShowToggle && (
        <TouchableOpacity
          onPress={() => setShowFull(!showFull)}
          style={styles.button}
        >
          <Text style={styles.buttonText}>
            {showFull ? "Thu gọn" : "Xem thêm"}
          </Text>
          <Ionicons
            name={showFull ? "chevron-up-outline" : "chevron-down-outline"}
            size={18}
            color="#ff7a00"
            style={{ marginLeft: 4 }}
          />
        </TouchableOpacity>
      )}
    </View>
  );
};

export default ProductHTMLContent;

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#fff",
    position: "relative",
  },
  fadeGradient: {
    position: "absolute",
    bottom: 30,
    left: 0,
    right: 0,
    height: 80,
    zIndex: 1,
  },
  button: {
    marginTop: 12,
    alignSelf: "center",
    flexDirection: "row",
    alignItems: "center",
  },
  buttonText: {
    color: "#ff7a00",
    fontSize: 14,
  },
});
