import { IconSymbol } from "@/components/ui/icon-symbol";
import { useI18n } from "@/hooks/use-i18n";
import { useAppTheme } from "@/hooks/use-app-theme";
import { useTrip } from "@/state/use-trip";
import { createTableStyles } from "./style/createTableStyles";
import TripCostDetailModal from "./modal/TripCostDetailModal";
import React, { useRef, useState, useMemo } from "react";
import { Animated, Text, TouchableOpacity, View } from "react-native";
import { useThemeContext } from "@/hooks/use-theme-context";

const TripCostTable: React.FC = () => {
  const [collapsed, setCollapsed] = useState(true);
  const [contentHeight, setContentHeight] = useState<number>(0);
  const [modalVisible, setModalVisible] = useState(false);
  const animatedHeight = useRef(new Animated.Value(0)).current;
  const { t } = useI18n();
  const { colorScheme } = useAppTheme();
  const { colors } = useThemeContext();

  const { trip } = useTrip();

  const styles = useMemo(() => createTableStyles(colorScheme), [colorScheme]);

  const data: Model.TripCost[] = trip?.trip_cost ?? [];
  const tongCong = data.reduce((sum, item) => sum + item.total_cost, 0);

  const handleToggle = () => {
    const toValue = collapsed ? contentHeight : 0;
    Animated.timing(animatedHeight, {
      toValue,
      duration: 300,
      useNativeDriver: false,
    }).start();
    setCollapsed((prev) => !prev);
  };

  const handleViewDetail = () => {
    setModalVisible(true);
  };

  const handleCloseModal = () => {
    setModalVisible(false);
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity
        activeOpacity={0.7}
        onPress={handleToggle}
        style={{
          flexDirection: "row",
          justifyContent: "space-between",
          alignItems: "center",
          //   marginBottom: 12,
        }}
      >
        <Text style={styles.title}>{t("trip.costTable.title")}</Text>
        {collapsed && (
          <Text style={[styles.totalCollapsed]}>
            {tongCong.toLocaleString()}
          </Text>
        )}
        <IconSymbol
          name={collapsed ? "chevron.down" : "chevron.up"}
          size={15}
          color={colors.icon}
        />
      </TouchableOpacity>

      {/* Nội dung ẩn để đo chiều cao */}
      <View
        style={{ position: "absolute", opacity: 0, zIndex: -1000 }}
        onLayout={(event) => {
          const height = event.nativeEvent.layout.height;
          if (height > 0 && contentHeight === 0) {
            setContentHeight(height);
          }
        }}
      >
        {/* Header */}
        <View style={[styles.row, styles.header]}>
          <Text style={[styles.cell, styles.left, styles.headerText]}>
            {t("trip.costTable.typeHeader")}
          </Text>
          <Text style={[styles.cell, styles.headerText]}>
            {t("trip.costTable.totalCostHeader")}
          </Text>
        </View>

        {/* Body */}
        {data.map((item, index) => (
          <View key={index} style={styles.row}>
            <Text style={[styles.cell, styles.left]}>{item.type}</Text>
            <Text style={[styles.cell, styles.right]}>
              {item.total_cost.toLocaleString()}
            </Text>
          </View>
        ))}

        {/* Footer */}
        <View style={[styles.row]}>
          <Text style={[styles.cell, styles.left, styles.footerText]}>
            {t("trip.costTable.totalLabel")}
          </Text>
          <Text style={[styles.cell, styles.total]}>
            {tongCong.toLocaleString()}
          </Text>
        </View>

        {/* View Detail Button */}
        {data.length > 0 && (
          <TouchableOpacity
            style={styles.viewDetailButton}
            onPress={handleViewDetail}
          >
            <Text style={styles.viewDetailText}>
              {t("trip.costTable.viewDetail")}
            </Text>
          </TouchableOpacity>
        )}
      </View>

      <Animated.View style={{ height: animatedHeight, overflow: "hidden" }}>
        {/* Header */}
        <View style={[styles.row, styles.header]}>
          <Text style={[styles.cell, styles.left, styles.headerText]}>
            {t("trip.costTable.typeHeader")}
          </Text>
          <Text style={[styles.cell, styles.headerText]}>
            {t("trip.costTable.totalCostHeader")}
          </Text>
        </View>

        {/* Body */}
        {data.map((item, index) => (
          <View key={index} style={styles.row}>
            <Text style={[styles.cell, styles.left]}>{item.type}</Text>
            <Text style={[styles.cell, styles.right]}>
              {item.total_cost.toLocaleString()}
            </Text>
          </View>
        ))}

        {/* Footer */}
        <View style={[styles.row]}>
          <Text style={[styles.cell, styles.left, styles.footerText]}>
            {t("trip.costTable.totalLabel")}
          </Text>
          <Text style={[styles.cell, styles.total]}>
            {tongCong.toLocaleString()}
          </Text>
        </View>

        {/* View Detail Button */}
        {data.length > 0 && (
          <TouchableOpacity
            style={styles.viewDetailButton}
            onPress={handleViewDetail}
          >
            <Text style={styles.viewDetailText}>
              {t("trip.costTable.viewDetail")}
            </Text>
          </TouchableOpacity>
        )}
      </Animated.View>

      {/* Modal */}
      <TripCostDetailModal
        visible={modalVisible}
        onClose={handleCloseModal}
        data={data}
      />
    </View>
  );
};

export default TripCostTable;
