import { useEffect, useState } from "react";
import { ITEM_GROUPS, ITEM_TYPES, getItemTypeLabel, getZoneValues } from "../../constants/classifications";
import useActionToast from "../../hooks/useActionToast";
import getApiErrorMessage from "../../lib/getApiErrorMessage";
import "../../styles/components/EditItemModal.css";
import AddImageModal from "./AddImageModal";

export default function EditItemModal({ item, onSave, onCancel, onImageUpdate }) {
  const toast = useActionToast();
  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);
      const message = getApiErrorMessage(error, "Failed to save changes");
      toast.error("Save item failed", `Save item failed: ${message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleImageUpload = async (imageFile) => {
    if (onImageUpdate) {
      try {
        await onImageUpdate(item.id, itemName, quantity, imageFile, "edit_modal");
        setShowImageModal(false);
      } catch (error) {
        console.error("Failed to upload image:", error);
        const message = getApiErrorMessage(error, "Failed to upload image");
        toast.error("Upload image failed", `Upload image failed: ${message}`);
      }
    }
  };

  const incrementQuantity = () => {
    setQuantity(prev => prev + 1);
  };

  const decrementQuantity = () => {
    setQuantity(prev => Math.max(1, prev - 1));
  };

  const availableGroups = itemType ? (ITEM_GROUPS[itemType] || []) : [];

  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>

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

        {/* Quantity Control - like AddItemForm */}
        <div className="edit-modal-quantity-control">
          <button
            type="button"
            className="quantity-btn quantity-btn-minus"
            onClick={decrementQuantity}
            disabled={quantity <= 1}
          >
            −
          </button>
          <input
            type="number"
            min="1"
            className="edit-modal-quantity-input"
            value={quantity}
            readOnly
          />
          <button
            type="button"
            className="quantity-btn quantity-btn-plus"
            onClick={incrementQuantity}
          >
            +
          </button>
        </div>

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

        {/* Inline Classification Fields */}
        <div className="edit-modal-inline-field">
          <label>Type</label>
          <select
            value={itemType}
            onChange={(e) => handleItemTypeChange(e.target.value)}
            className="edit-modal-select"
          >
            <option value="">-- Select Type --</option>
            {Object.values(ITEM_TYPES).map((type) => (
              <option key={type} value={type}>
                {getItemTypeLabel(type)}
              </option>
            ))}
          </select>
        </div>

        {itemType && (
          <div className="edit-modal-inline-field">
            <label>Group</label>
            <select
              value={itemGroup}
              onChange={(e) => setItemGroup(e.target.value)}
              className="edit-modal-select"
            >
              <option value="">-- Select Group --</option>
              {availableGroups.map((group) => (
                <option key={group} value={group}>
                  {group}
                </option>
              ))}
            </select>
          </div>
        )}

        <div className="edit-modal-inline-field">
          <label>Zone</label>
          <select
            value={zone}
            onChange={(e) => setZone(e.target.value)}
            className="edit-modal-select"
          >
            <option value="">-- Select Zone --</option>
            {getZoneValues().map((z) => (
              <option key={z} value={z}>
                {z}
              </option>
            ))}
          </select>
        </div>

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

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