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

// ---------------------------
// 🧩 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);
  const [expandedFishIndices, setExpandedFishIndices] = useState<number[]>([]);

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

  // Reset state khi modal đóng
  React.useEffect(() => {
    if (!visible) {
      setExpandedFishIndices([]);
      setSelectedFishIndex(null);
      setSelectedUnitIndex(null);
      setSelectedConditionIndex(null);
      setIsEditing(false);
    }
  }, [visible]);

  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);
    console.log("Saved catch list:", editableCatchList);
  };

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

  const handleToggleExpanded = (index: number) => {
    setExpandedFishIndices((prev) =>
      prev.includes(index) ? prev.filter((i) => i !== index) : [...prev, index]
    );
  };

  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
  );

  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 */}
          <InfoSection netData={netData} isCompleted={isCompleted} />

          {/* Danh sách cá bắt được */}
          <CatchSectionHeader totalCatch={totalCatch} />

          {/* Fish cards */}
          <FishCardList
            catchList={editableCatchList}
            isEditing={isEditing}
            expandedFishIndex={expandedFishIndices}
            selectedFishIndex={selectedFishIndex}
            selectedUnitIndex={selectedUnitIndex}
            selectedConditionIndex={selectedConditionIndex}
            fishNameOptions={fishNameOptions}
            unitOptions={unitOptions}
            conditionOptions={conditionOptions}
            onToggleExpanded={handleToggleExpanded}
            onUpdateCatchItem={updateCatchItem}
            setSelectedFishIndex={setSelectedFishIndex}
            setSelectedUnitIndex={setSelectedUnitIndex}
            setSelectedConditionIndex={setSelectedConditionIndex}
          />

          {/* Ghi chú */}
          <NotesSection ghiChu={netData.ghiChu} />
        </ScrollView>
      </View>
    </Modal>
  );
};

export default NetDetailModal;
