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

const mockCrews: Model.TripCrews[] = [
  {
    TripID: "f9884294-a7f2-46dc-aaf2-032da08a1ab6",
    PersonalID: "480863197307",
    role: "crew",
    joined_at: new Date("2025-11-06T08:13:33.230053Z"),
    left_at: null,
    note: null,
    Person: {
      personal_id: "480863197307",
      name: "Huỳnh Tấn Trang",
      phone: "0838944284",
      email: "huynhtantrang@crew.sgw.vn",
      birth_date: new Date("2025-01-11T00:00:00Z"),
      note: "",
      address: "49915 Poplar Avenue",
      created_at: new Date("0001-01-01T00:00:00Z"),
      updated_at: new Date("0001-01-01T00:00:00Z"),
    },
  },
  {
    TripID: "f9884294-a7f2-46dc-aaf2-032da08a1ab6",
    PersonalID: "714834545296",
    role: "crew",
    joined_at: new Date("2025-11-06T08:13:33.301376Z"),
    left_at: null,
    note: null,
    Person: {
      personal_id: "714834545296",
      name: "Trương Văn Nam",
      phone: "0773396753",
      email: "truongvannam@crew.sgw.vn",
      birth_date: new Date("2025-07-24T00:00:00Z"),
      note: "",
      address: "3287 Carlotta Underpass",
      created_at: new Date("0001-01-01T00:00:00Z"),
      updated_at: new Date("0001-01-01T00:00:00Z"),
    },
  },
  {
    TripID: "f9884294-a7f2-46dc-aaf2-032da08a1ab6",
    PersonalID: "049299828990",
    role: "crew",
    joined_at: new Date("2025-11-06T08:13:33.373037Z"),
    left_at: null,
    note: null,
    Person: {
      personal_id: "049299828990",
      name: "Đặng Anh Minh",
      phone: "0827640820",
      email: "danganhminh@crew.sgw.vn",
      birth_date: new Date("2024-10-30T00:00:00Z"),
      note: "",
      address: "68909 Gerda Burgs",
      created_at: new Date("0001-01-01T00:00:00Z"),
      updated_at: new Date("0001-01-01T00:00:00Z"),
    },
  },
  {
    TripID: "f9884294-a7f2-46dc-aaf2-032da08a1ab6",
    PersonalID: "851494873747",
    role: "captain",
    joined_at: new Date("2025-11-06T08:13:33.442774Z"),
    left_at: null,
    note: null,
    Person: {
      personal_id: "851494873747",
      name: "Tô Thị Linh",
      phone: "0337906041",
      email: "tothilinh@crew.sgw.vn",
      birth_date: new Date("2025-06-18T00:00:00Z"),
      note: "",
      address: "6676 Kulas Groves",
      created_at: new Date("0001-01-01T00:00:00Z"),
      updated_at: new Date("0001-01-01T00:00:00Z"),
    },
  },
  {
    TripID: "f9884294-a7f2-46dc-aaf2-032da08a1ab6",
    PersonalID: "384839614682",
    role: "crew",
    joined_at: new Date("2025-11-06T08:13:33.515532Z"),
    left_at: null,
    note: null,
    Person: {
      personal_id: "384839614682",
      name: "Lê Thanh Hoa",
      phone: "0937613034",
      email: "lethanhhoa@crew.sgw.vn",
      birth_date: new Date("2025-07-17T00:00:00Z"),
      note: "",
      address: "244 Cicero Estate",
      created_at: new Date("0001-01-01T00:00:00Z"),
      updated_at: new Date("0001-01-01T00:00:00Z"),
    },
  },
  {
    TripID: "f9884294-a7f2-46dc-aaf2-032da08a1ab6",
    PersonalID: "702319275290",
    role: "crew",
    joined_at: new Date("2025-11-06T08:13:33.588038Z"),
    left_at: null,
    note: null,
    Person: {
      personal_id: "702319275290",
      name: "Nguyễn Phước Hải",
      phone: "0347859214",
      email: "nguyenphuochai@crew.sgw.vn",
      birth_date: new Date("2025-08-13T00:00:00Z"),
      note: "",
      address: "6874 Devon Key",
      created_at: new Date("0001-01-01T00:00:00Z"),
      updated_at: new Date("0001-01-01T00:00:00Z"),
    },
  },
  {
    TripID: "f9884294-a7f2-46dc-aaf2-032da08a1ab6",
    PersonalID: "943534816439",
    role: "crew",
    joined_at: new Date("2025-11-06T08:13:33.668984Z"),
    left_at: null,
    note: null,
    Person: {
      personal_id: "943534816439",
      name: "Lý Hữu Hà",
      phone: "0768548881",
      email: "lyhuuha@crew.sgw.vn",
      birth_date: new Date("2025-08-18T00:00:00Z"),
      note: "",
      address: "655 Middle Street",
      created_at: new Date("0001-01-01T00:00:00Z"),
      updated_at: new Date("0001-01-01T00:00:00Z"),
    },
  },
  {
    TripID: "f9884294-a7f2-46dc-aaf2-032da08a1ab6",
    PersonalID: "096528446981",
    role: "crew",
    joined_at: new Date("2025-11-06T08:13:33.74379Z"),
    left_at: null,
    note: null,
    Person: {
      personal_id: "096528446981",
      name: "Trần Xuân Thi",
      phone: "0963449523",
      email: "tranxuanthi@crew.sgw.vn",
      birth_date: new Date("2024-09-21T00:00:00Z"),
      note: "",
      address: "59344 Burley Isle",
      created_at: new Date("0001-01-01T00:00:00Z"),
      updated_at: new Date("0001-01-01T00:00:00Z"),
    },
  },
];

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 { trip } = useTrip();

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

  const tongThanhVien = data.length;

  // Reset animated height khi dữ liệu thay đổi
  useEffect(() => {
    setContentHeight(0); // Reset để tính lại chiều cao
    setCollapsed(true); // Reset về trạng thái gập lại
  }, [data]);

  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}>Danh sách thuyền viên</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ên</Text>
          </View>
          <Text style={[styles.cell, styles.right, styles.headerText]}>
            Chức vụ
          </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ổng cộng</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ên</Text>
          </View>
          <Text style={[styles.cell, styles.right, styles.headerText]}>
            Chức vụ
          </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ổng cộng</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;
