import { ThemedText } from "@/components/themed-text";
import { ThemedView } from "@/components/themed-view";
import { queryUpdateShip } from "@/controller/DeviceController";
import { useTheme } from "@/hooks/use-theme-context";
import { showSuccessToast } from "@/services/toast_service";
import { useShip } from "@/state/use-ship";
import { useEffect, useState } from "react";
import { ScrollView, StyleSheet, TouchableOpacity, View } from "react-native";
import CreateOrUpdateShip from "./ship_components/CreateOrUpdateShip";
import ShipCard from "./ship_components/ShipCard";

interface ShipUpdateData {
  ship_id: string;
  body: Model.ShipBodyRequest;
}

export default function ShipsScreen() {
  const { ships, getShip } = useShip();
  const { colors } = useTheme();
  const [ship, setShip] = useState<ShipUpdateData | null>(null);
  const [showUpdateShip, setShowUpdateShip] = useState<boolean>(false);
  const [isCreateShip, setIsCreateShip] = useState<boolean>(false);
  useEffect(() => {
    if (ships === null) {
      getShip();
    }
  }, [ships]);
  const handleClickShip = async (ship: Model.Ship) => {
    const shipBodyRequest: Model.ShipBodyRequest = {
      name: ship.name,
      reg_number: ship.reg_number,
      imo_number: ship.imo_number,
      mmsi_number: ship.mmsi_number,
      thing_id: ship.thing_id,
      ship_type: ship.ship_type,
      owner_id: ship.owner_id,
      home_port: ship.home_port,
      ship_length: ship.ship_length,
      ship_power: ship.ship_power,
      ship_group_id: ship.ship_group_id,
      fishing_license_number: ship.fishing_license_number,
      fishing_license_expiry_date: ship.fishing_license_expiry_date,
    };
    setShip({ ship_id: ship.id!, body: shipBodyRequest });
    setIsCreateShip(false); // Đảm bảo là mode update khi edit
    setShowUpdateShip(true);
  };
  const handleUpdateShip = async (body: Model.ShipBodyRequest) => {
    try {
      let resp;
      if (isCreateShip) {
        // TODO: Thêm API create ship khi có
        showSuccessToast("Thêm tàu mới thành công");
      } else {
        resp = await queryUpdateShip(ship!.ship_id, body);
        if (resp.status === 200) {
          showSuccessToast("Cập nhật thông tin tàu thành công");
        }
      }
      setShowUpdateShip(false);
      await getShip();
    } catch (error) {
      console.error("Error when update/create Ship: ", error);
    }
  };

  const handleCreateNewShip = () => {
    setShip(null);
    setIsCreateShip(true);
    setShowUpdateShip(true);
  };
  return (
    <>
      <ScrollView>
        <ThemedView style={styles.container}>
          {ships?.map((ship) => (
            <ShipCard
              key={ship.id}
              ship={ship}
              onPress={() => handleClickShip(ship)}
            />
          ))}

          {/* Thêm khoảng trống ở cuối để không bị FAB che */}
          <View style={styles.bottomPadding} />
        </ThemedView>
      </ScrollView>

      {/* Floating Action Button */}
      <TouchableOpacity
        style={[styles.fab, { backgroundColor: colors.primary }]}
        onPress={handleCreateNewShip}
      >
        <ThemedText style={styles.fabText}>+</ThemedText>
      </TouchableOpacity>

      <CreateOrUpdateShip
        isOpen={showUpdateShip}
        initialValue={ship?.body || undefined}
        type={isCreateShip ? "create" : "update"}
        onClose={() => setShowUpdateShip(false)}
        onSubmit={handleUpdateShip}
      />
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingBottom: 20, // Khoảng trống cho FAB
  },
  bottomPadding: {
    height: 50, // Thêm khoảng trống ở cuối
  },
  fab: {
    position: "absolute",
    bottom: 30,
    right: 20,
    width: 56,
    height: 56,
    borderRadius: 28,
    justifyContent: "center",
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  fabText: {
    fontSize: 24,
    fontWeight: "bold",
    color: "#ffffff",
    lineHeight: 24,
  },
});
