import { useEffect, useState } from "react";
import "../../styles/components/EditItemModal.css";
import ClassificationSection from "../forms/ClassificationSection";
import AddImageModal from "./AddImageModal";

export default function EditItemModal({ item, onSave, onCancel, onImageUpdate }) {
  const [itemName, setItemName] = useState(item.item_name || "");
  const [quantity, setQuantity] = useState(item.quantity || 1);
  const [itemType, setItemType] = useState("");
  const [itemGroup, setItemGroup] = useState("");
  const [zone, setZone] = useState("");
  const [loading, setLoading] = useState(false);
  const [showImageModal, setShowImageModal] = useState(false);

  // Load existing classification
  useEffect(() => {
    if (item.classification) {
      setItemType(item.classification.item_type || "");
      setItemGroup(item.classification.item_group || "");
      setZone(item.classification.zone || "");
    }
  }, [item]);

  const handleItemTypeChange = (newType) => {
    setItemType(newType);
    setItemGroup(""); // Reset group when type changes
  };

  const handleSave = async () => {
    if (!itemName.trim()) {
      alert("Item name is required");
      return;
    }

    if (quantity < 1) {
      alert("Quantity must be at least 1");
      return;
    }

    // If classification fields are filled, validate them
    if (itemType && !itemGroup) {
      alert("Please select an item group");
      return;
    }

    setLoading(true);
    try {
      const classification = itemType ? {
        item_type: itemType,
        item_group: itemGroup,
        zone: zone || null
      } : null;

      await onSave(item.id, itemName, quantity, classification);
    } catch (error) {
      console.error("Failed to save:", error);
      alert("Failed to save changes");
    } finally {
      setLoading(false);
    }
  };

  const handleImageUpload = async (imageFile) => {
    if (onImageUpdate) {
      try {
        await onImageUpdate(item.id, itemName, quantity, imageFile);
        setShowImageModal(false);
      } catch (error) {
        console.error("Failed to upload image:", error);
        alert("Failed to upload image");
      }
    }
  };

  return (
    <div className="edit-modal-overlay" onClick={onCancel}>
      <div className="edit-modal-content" onClick={(e) => e.stopPropagation()}>
        <h2 className="edit-modal-title">Edit Item</h2>

        <div className="edit-modal-field">
          <label>Item Name</label>
          <input
            type="text"
            value={itemName}
            onChange={(e) => setItemName(e.target.value)}
            className="edit-modal-input"
          />
        </div>

        <div className="edit-modal-field">
          <label>Quantity</label>
          <input
            type="number"
            min="1"
            value={quantity}
            onChange={(e) => setQuantity(parseInt(e.target.value))}
            className="edit-modal-input"
          />
        </div>

        <div className="edit-modal-divider" />

        <ClassificationSection
          itemType={itemType}
          itemGroup={itemGroup}
          zone={zone}
          onItemTypeChange={handleItemTypeChange}
          onItemGroupChange={setItemGroup}
          onZoneChange={setZone}
          fieldClass="edit-modal-field"
          selectClass="edit-modal-select"
        />

        <div className="edit-modal-divider" />

        <div className="edit-modal-field">
          <button
            className="edit-modal-btn edit-modal-btn-image"
            onClick={() => setShowImageModal(true)}
            disabled={loading}
            type="button"
          >
            {item.item_image ? "🖼️ Change Image" : "📷 Set Image"}
          </button>
        </div>

        <div className="edit-modal-actions">
          <button
            className="edit-modal-btn edit-modal-btn-cancel"
            onClick={onCancel}
            disabled={loading}
          >
            Cancel
          </button>
          <button
            className="edit-modal-btn edit-modal-btn-save"
            onClick={handleSave}
            disabled={loading}
          >
            {loading ? "Saving..." : "Save Changes"}
          </button>
        </div>
      </div>

      {showImageModal && (
        <AddImageModal
          itemName={itemName}
          onClose={() => setShowImageModal(false)}
          onAddImage={handleImageUpload}
        />
      )}
    </div>
  );
}
