import { IconSymbol } from "@/components/ui/icon-symbol";
import { useI18n } from "@/hooks/use-i18n";
import { useTrip } from "@/state/use-trip";
import React, { useRef, useState } from "react";
import { Animated, Text, TouchableOpacity, View } from "react-native";
import CrewDetailModal from "./modal/CrewDetailModal";
import styles from "./style/CrewListTable.styles";

const CrewListTable: React.FC = () => {
  const [collapsed, setCollapsed] = useState(true);
  const [contentHeight, setContentHeight] = useState<number>(0);
  const animatedHeight = useRef(new Animated.Value(0)).current;
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedCrew, setSelectedCrew] = useState<Model.TripCrews | null>(
    null
  );
  const { t } = useI18n();

  const { trip } = useTrip();

  const data: Model.TripCrews[] = trip?.crews ?? [];

  const tongThanhVien = data.length;

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

  const handleCrewPress = (crewId: string) => {
    const crew = data.find((item) => item.Person.personal_id === crewId);
    if (crew) {
      setSelectedCrew(crew);
      setModalVisible(true);
    }
  };

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

  return (
    <View style={styles.container}>
      {/* Header toggle */}
      <TouchableOpacity
        activeOpacity={0.7}
        onPress={handleToggle}
        style={styles.headerRow}
      >
        <Text style={styles.title}>{t("trip.crewList.title")}</Text>
        {collapsed && (
          <Text style={styles.totalCollapsed}>{tongThanhVien}</Text>
        )}
        <IconSymbol
          name={collapsed ? "chevron.down" : "chevron.up"}
          size={16}
          color="#000"
        />
      </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.tableHeader]}>
          <View style={styles.cellWrapper}>
            <Text style={[styles.cell, styles.headerText]}>
              {t("trip.crewList.nameHeader")}
            </Text>
          </View>
          <Text style={[styles.cell, styles.right, styles.headerText]}>
            {t("trip.crewList.roleHeader")}
          </Text>
        </View>

        {/* Body */}
        {data.map((item) => (
          <View key={item.Person.personal_id} style={styles.row}>
            <TouchableOpacity
              style={styles.cellWrapper}
              onPress={() => handleCrewPress(item.Person.personal_id)}
            >
              <Text style={[styles.cell, styles.linkText]}>
                {item.Person.name}
              </Text>
            </TouchableOpacity>
            <Text style={[styles.cell, styles.right]}>{item.role}</Text>
          </View>
        ))}

        {/* Footer */}
        <View style={[styles.row]}>
          <Text style={[styles.cell, styles.footerText]}>
            {t("trip.crewList.totalLabel")}
          </Text>
          <Text style={[styles.cell, styles.footerTotal]}>{tongThanhVien}</Text>
        </View>
      </View>

      {/* Bảng hiển thị với animation */}
      <Animated.View style={{ height: animatedHeight, overflow: "hidden" }}>
        {/* Header */}
        <View style={[styles.row, styles.tableHeader]}>
          <View style={styles.cellWrapper}>
            <Text style={[styles.cell, styles.headerText]}>
              {t("trip.crewList.nameHeader")}
            </Text>
          </View>
          <Text style={[styles.cell, styles.right, styles.headerText]}>
            {t("trip.crewList.roleHeader")}
          </Text>
        </View>

        {/* Body */}
        {data.map((item) => (
          <View key={item.Person.personal_id} style={styles.row}>
            <TouchableOpacity
              style={styles.cellWrapper}
              onPress={() => handleCrewPress(item.Person.personal_id)}
            >
              <Text style={[styles.cell, styles.linkText]}>
                {item.Person.name}
              </Text>
            </TouchableOpacity>
            <Text style={[styles.cell, styles.right]}>{item.role}</Text>
          </View>
        ))}

        {/* Footer */}
        <View style={[styles.row]}>
          <Text style={[styles.cell, styles.footerText]}>
            {t("trip.crewList.totalLabel")}
          </Text>
          <Text style={[styles.cell, styles.footerTotal]}>{tongThanhVien}</Text>
        </View>
      </Animated.View>

      {/* Modal chi tiết thuyền viên */}
      <CrewDetailModal
        visible={modalVisible}
        onClose={handleCloseModal}
        crewData={selectedCrew}
      />
    </View>
  );
};

export default CrewListTable;
