import { IconSymbol } from "@/components/ui/icon-symbol";
import React, { useState } from "react";
import {
  Modal,
  ScrollView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import styles from "./style/NetDetailModal.styles";

// ---------------------------
// 🧩 Interface
// ---------------------------
interface FishCatch {
  fish_species_id: number;
  fish_name: string;
  catch_number: number;
  catch_unit: string;
  fish_size: number;
  fish_rarity: number;
  fish_condition: string;
  gear_usage: string;
}

interface NetDetail {
  id: string;
  stt: string;
  trangThai: string;
  thoiGianBatDau?: string;
  thoiGianKetThuc?: string;
  viTriHaThu?: string;
  viTriThuLuoi?: string;
  doSauHaThu?: string;
  doSauThuLuoi?: string;
  catchList?: FishCatch[];
  ghiChu?: string;
}

interface NetDetailModalProps {
  visible: boolean;
  onClose: () => void;
  netData: NetDetail | null;
}

// ---------------------------
// 🧵 Component Modal
// ---------------------------
const NetDetailModal: React.FC<NetDetailModalProps> = ({
  visible,
  onClose,
  netData,
}) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editableCatchList, setEditableCatchList] = useState<FishCatch[]>([]);
  const [selectedFishIndex, setSelectedFishIndex] = useState<number | null>(
    null
  );
  const [selectedUnitIndex, setSelectedUnitIndex] = useState<number | null>(
    null
  );
  const [selectedConditionIndex, setSelectedConditionIndex] = useState<
    number | null
  >(null);

  // Khởi tạo dữ liệu khi netData thay đổi
  React.useEffect(() => {
    if (netData?.catchList) {
      setEditableCatchList(netData.catchList);
    }
  }, [netData]);

  if (!netData) return null;

  const isCompleted = netData.trangThai === "Đã hoàn thành";

  // Danh sách tên cá có sẵn
  const fishNameOptions = [
    "Cá chim trắng",
    "Cá song đỏ",
    "Cá hồng",
    "Cá nục",
    "Cá ngừ đại dương",
    "Cá mú trắng",
    "Cá hồng phớn",
    "Cá hổ Napoleon",
    "Cá nược",
    "Cá đuối quạt",
  ];

  // Danh sách đơn vị
  const unitOptions = ["kg", "con", "tấn"];

  // Danh sách tình trạng
  const conditionOptions = ["Còn sống", "Chết", "Bị thương"];

  const handleEdit = () => {
    setIsEditing(!isEditing);
  };

  const handleSave = () => {
    setIsEditing(false);
    // TODO: Save data to backend
    console.log("Saved catch list:", editableCatchList);
  };

  const handleCancel = () => {
    setIsEditing(false);
    setEditableCatchList(netData.catchList || []);
  };

  const updateCatchItem = (
    index: number,
    field: keyof FishCatch,
    value: string | number
  ) => {
    setEditableCatchList((prev) =>
      prev.map((item, i) => {
        if (i === index) {
          const updatedItem = { ...item };
          if (
            field === "catch_number" ||
            field === "fish_size" ||
            field === "fish_rarity"
          ) {
            updatedItem[field] = Number(value) || 0;
          } else {
            updatedItem[field] = value as never;
          }
          return updatedItem;
        }
        return item;
      })
    );
  };

  const totalCatch = editableCatchList.reduce(
    (sum, item) => sum + item.catch_number,
    0
  );

  const infoItems = [
    { label: "Số thứ tự", value: netData.stt },
    {
      label: "Trạng thái",
      value: netData.trangThai,
      isStatus: true,
    },
    {
      label: "Thời gian bắt đầu",
      value: netData.thoiGianBatDau || "Chưa cập nhật",
    },
    {
      label: "Thời gian kết thúc",
      value: netData.thoiGianKetThuc || "Chưa cập nhật",
    },
    {
      label: "Vị trí hạ thu",
      value: netData.viTriHaThu || "Chưa cập nhật",
    },
    {
      label: "Vị trí thu lưới",
      value: netData.viTriThuLuoi || "Chưa cập nhật",
    },
    {
      label: "Độ sâu hạ thu",
      value: netData.doSauHaThu || "Chưa cập nhật",
    },
    {
      label: "Độ sâu thu lưới",
      value: netData.doSauThuLuoi || "Chưa cập nhật",
    },
  ];

  return (
    <Modal
      visible={visible}
      animationType="slide"
      presentationStyle="pageSheet"
      onRequestClose={onClose}
    >
      <View style={styles.container}>
        {/* Header */}
        <View style={styles.header}>
          <Text style={styles.title}>Chi tiết mẻ lưới</Text>
          <View style={styles.headerButtons}>
            {isEditing ? (
              <>
                <TouchableOpacity
                  onPress={handleCancel}
                  style={styles.cancelButton}
                >
                  <Text style={styles.cancelButtonText}>Hủy</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  onPress={handleSave}
                  style={styles.saveButton}
                >
                  <Text style={styles.saveButtonText}>Lưu</Text>
                </TouchableOpacity>
              </>
            ) : (
              <TouchableOpacity onPress={handleEdit} style={styles.editButton}>
                <View style={styles.editIconButton}>
                  <IconSymbol
                    name="pencil"
                    size={28}
                    color="#fff"
                    weight="heavy"
                  />
                </View>
              </TouchableOpacity>
            )}
            <TouchableOpacity onPress={onClose} style={styles.closeButton}>
              <View style={styles.closeIconButton}>
                <IconSymbol name="xmark" size={28} color="#fff" />
              </View>
            </TouchableOpacity>
          </View>
        </View>

        {/* Content */}
        <ScrollView style={styles.content}>
          {/* Thông tin chung */}
          <View style={styles.infoCard}>
            {infoItems.map((item, index) => (
              <View key={index} style={styles.infoRow}>
                <Text style={styles.infoLabel}>{item.label}</Text>
                {item.isStatus ? (
                  <View
                    style={[
                      styles.statusBadge,
                      isCompleted
                        ? styles.statusBadgeCompleted
                        : styles.statusBadgeInProgress,
                    ]}
                  >
                    <Text
                      style={[
                        styles.statusBadgeText,
                        isCompleted
                          ? styles.statusBadgeTextCompleted
                          : styles.statusBadgeTextInProgress,
                      ]}
                    >
                      {item.value}
                    </Text>
                  </View>
                ) : (
                  <Text style={styles.infoValue}>{item.value}</Text>
                )}
              </View>
            ))}
          </View>

          {/* Danh sách cá bắt được */}
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>Danh sách cá bắt được</Text>
            <Text style={styles.totalCatchText}>
              Tổng: {totalCatch.toLocaleString()} kg
            </Text>
          </View>

          {editableCatchList.map((fish, index) => (
            <View key={index} style={styles.fishCard}>
              {/* Tên cá - Select */}
              <View style={[styles.fieldGroup, { zIndex: 1000 - index }]}>
                <Text style={styles.label}>Tên cá</Text>
                {isEditing ? (
                  <View style={{ zIndex: 1000 - index }}>
                    <TouchableOpacity
                      style={styles.selectButton}
                      onPress={() =>
                        setSelectedFishIndex(
                          selectedFishIndex === index ? null : index
                        )
                      }
                    >
                      <Text style={styles.selectButtonText}>
                        {fish.fish_name}
                      </Text>
                      <IconSymbol
                        name={
                          selectedFishIndex === index
                            ? "chevron.up"
                            : "chevron.down"
                        }
                        size={16}
                        color="#666"
                      />
                    </TouchableOpacity>
                    {selectedFishIndex === index && (
                      <ScrollView
                        style={styles.optionsList}
                        nestedScrollEnabled={true}
                      >
                        {fishNameOptions.map((option, optIndex) => (
                          <TouchableOpacity
                            key={optIndex}
                            style={styles.optionItem}
                            onPress={() => {
                              updateCatchItem(index, "fish_name", option);
                              setSelectedFishIndex(null);
                            }}
                          >
                            <Text style={styles.optionText}>{option}</Text>
                          </TouchableOpacity>
                        ))}
                      </ScrollView>
                    )}
                  </View>
                ) : (
                  <Text style={styles.infoValue}>{fish.fish_name}</Text>
                )}
              </View>

              {/* Số lượng & Đơn vị */}
              <View style={styles.rowGroup}>
                <View style={[styles.fieldGroup, { flex: 1, marginRight: 8 }]}>
                  <Text style={styles.label}>Số lượng</Text>
                  {isEditing ? (
                    <TextInput
                      style={styles.input}
                      value={String(fish.catch_number)}
                      onChangeText={(value) =>
                        updateCatchItem(index, "catch_number", value)
                      }
                      keyboardType="numeric"
                      placeholder="0"
                    />
                  ) : (
                    <Text style={styles.infoValue}>{fish.catch_number}</Text>
                  )}
                </View>
                <View
                  style={[
                    styles.fieldGroup,
                    { flex: 1, marginLeft: 8, zIndex: 900 - index },
                  ]}
                >
                  <Text style={styles.label}>Đơn vị</Text>
                  {isEditing ? (
                    <View style={{ zIndex: 900 - index }}>
                      <TouchableOpacity
                        style={styles.selectButton}
                        onPress={() =>
                          setSelectedUnitIndex(
                            selectedUnitIndex === index ? null : index
                          )
                        }
                      >
                        <Text style={styles.selectButtonText}>
                          {fish.catch_unit}
                        </Text>
                        <IconSymbol
                          name={
                            selectedUnitIndex === index
                              ? "chevron.up"
                              : "chevron.down"
                          }
                          size={16}
                          color="#666"
                        />
                      </TouchableOpacity>
                      {selectedUnitIndex === index && (
                        <ScrollView
                          style={styles.optionsList}
                          nestedScrollEnabled={true}
                        >
                          {unitOptions.map((option, optIndex) => (
                            <TouchableOpacity
                              key={optIndex}
                              style={styles.optionItem}
                              onPress={() => {
                                updateCatchItem(index, "catch_unit", option);
                                setSelectedUnitIndex(null);
                              }}
                            >
                              <Text style={styles.optionText}>{option}</Text>
                            </TouchableOpacity>
                          ))}
                        </ScrollView>
                      )}
                    </View>
                  ) : (
                    <Text style={styles.infoValue}>{fish.catch_unit}</Text>
                  )}
                </View>
              </View>

              {/* Kích thước & Độ hiếm */}
              <View style={styles.rowGroup}>
                <View style={[styles.fieldGroup, { flex: 1, marginRight: 8 }]}>
                  <Text style={styles.label}>Kích thước (cm)</Text>
                  {isEditing ? (
                    <TextInput
                      style={styles.input}
                      value={String(fish.fish_size)}
                      onChangeText={(value) =>
                        updateCatchItem(index, "fish_size", value)
                      }
                      keyboardType="numeric"
                      placeholder="0"
                    />
                  ) : (
                    <Text style={styles.infoValue}>{fish.fish_size} cm</Text>
                  )}
                </View>
                <View style={[styles.fieldGroup, { flex: 1, marginLeft: 8 }]}>
                  <Text style={styles.label}>Độ hiếm</Text>
                  {isEditing ? (
                    <TextInput
                      style={styles.input}
                      value={String(fish.fish_rarity)}
                      onChangeText={(value) =>
                        updateCatchItem(index, "fish_rarity", value)
                      }
                      keyboardType="numeric"
                      placeholder="1-5"
                    />
                  ) : (
                    <Text style={styles.infoValue}>{fish.fish_rarity}</Text>
                  )}
                </View>
              </View>

              {/* Tình trạng */}
              <View style={[styles.fieldGroup, { zIndex: 800 - index }]}>
                <Text style={styles.label}>Tình trạng</Text>
                {isEditing ? (
                  <View style={{ zIndex: 800 - index }}>
                    <TouchableOpacity
                      style={styles.selectButton}
                      onPress={() =>
                        setSelectedConditionIndex(
                          selectedConditionIndex === index ? null : index
                        )
                      }
                    >
                      <Text style={styles.selectButtonText}>
                        {fish.fish_condition}
                      </Text>
                      <IconSymbol
                        name={
                          selectedConditionIndex === index
                            ? "chevron.up"
                            : "chevron.down"
                        }
                        size={16}
                        color="#666"
                      />
                    </TouchableOpacity>
                    {selectedConditionIndex === index && (
                      <ScrollView
                        style={styles.optionsStatusFishList}
                        nestedScrollEnabled={true}
                      >
                        {conditionOptions.map((option, optIndex) => (
                          <TouchableOpacity
                            key={optIndex}
                            style={styles.optionItem}
                            onPress={() => {
                              updateCatchItem(index, "fish_condition", option);
                              setSelectedConditionIndex(null);
                            }}
                          >
                            <Text style={styles.optionText}>{option}</Text>
                          </TouchableOpacity>
                        ))}
                      </ScrollView>
                    )}
                  </View>
                ) : (
                  <Text style={styles.infoValue}>{fish.fish_condition}</Text>
                )}
              </View>

              {/* Ngư cụ sử dụng */}
              <View style={styles.fieldGroup}>
                <Text style={styles.label}>Ngư cụ sử dụng</Text>
                {isEditing ? (
                  <TextInput
                    style={styles.input}
                    value={fish.gear_usage}
                    onChangeText={(value) =>
                      updateCatchItem(index, "gear_usage", value)
                    }
                    placeholder="Nhập ngư cụ..."
                  />
                ) : (
                  <Text style={styles.infoValue}>
                    {fish.gear_usage || "Không có"}
                  </Text>
                )}
              </View>
            </View>
          ))}

          {/* Ghi chú */}
          {netData.ghiChu && (
            <View style={styles.infoCard}>
              <View style={styles.infoRow}>
                <Text style={styles.infoLabel}>Ghi chú</Text>
                <Text style={styles.infoValue}>{netData.ghiChu}</Text>
              </View>
            </View>
          )}
        </ScrollView>
      </View>
    </Modal>
  );
};

export default NetDetailModal;
