import React, { useState, useRef, useEffect } from "react";
import styles from "./Item.module.css";
const Item = ({
  blank,
  forCart,
  forInvoice,
  name: initialName,
  description: initialDescription,
  price: initialPrice,
  promoPrice,
  qty: initialQty,
  imageUrl,
  imageFile,
  id,
  onPlusClick,
  onNegativeClick,
  handleCreateItem,
  handleUpdateItem,
  onRemoveClick,
  isAvailable,
  isBeingEdit,
  last
}) => {
  const [selectedImage, setSelectedImage] = useState(imageFile);
  const [previewUrl, setPreviewUrl] = useState(imageUrl);
  const [itemQty, setItemQty] = useState(blank ? 0 : initialQty);
  const [itemName, setItemName] = useState(initialName);
  const [itemPrice, setItemPrice] = useState(initialPrice);
  const [itemDescription, setItemDescription] = useState(initialDescription);
  const fileInputRef = useRef(null);

  useEffect(() => {
    console.log(imageUrl);
    console.log(selectedImage);
    console.log(imageFile)
    if (imageFile) {
      setPreviewUrl(imageFile);
    } else {
      setPreviewUrl(imageUrl);
    }
  }, [imageFile, imageUrl]);

  const handlePlusClick = () => {
    if (!blank) onPlusClick(id);
    setItemQty(itemQty + 1);
  };

  const handleNegativeClick = () => {
    if (itemQty > 0) {
      if (!blank) onNegativeClick(id);
      setItemQty(itemQty - 1);
    }
  };

  const handleCreate = () => {
    handleCreateItem(itemName, itemPrice, selectedImage, previewUrl);
  };
  const handleUpdate = () => {
    handleUpdateItem(itemName, itemPrice, selectedImage, previewUrl);
  };

  const handleRemoveClick = () => {
    onRemoveClick(id);
  };

  const handleImageClick = () => {
    fileInputRef.current.click();
  };

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      setSelectedImage(file);
    }
  };

  const formatCurrency = (value) => {
    const num = Number(value) || 0;
    return num.toLocaleString('id-ID');
  };

  const handlePriceChange = (event) => {
    setItemPrice(event.target.value);
  };

  const handleQtyChange = (event) => {
    const newQty = parseInt(event.target.value, 10);
    if (!isNaN(newQty)) {
      setItemQty(newQty);
    }
  };

  const handleNameChange = (event) => {
    setItemName(event.target.value);
  };

  return (
    <div className={`${!last && !forInvoice ? styles.notLast : ""}`}>
      <div className={`${styles.item} ${forInvoice ? styles.itemInvoice : ""} `}>
        {!forInvoice && (
          <img
            src={previewUrl}
            onError={({ currentTarget }) => {
              currentTarget.onerror = null;
              currentTarget.src =
                "https://png.pngtree.com/png-vector/20221125/ourmid/pngtree-no-image-available-icon-flatvector-illustration-pic-design-profile-vector-png-image_40966566.jpg";
            }}
            alt={itemName}
            style={{ filter: !isAvailable ? "grayscale(100%)" : "none" }}
            className={styles.imageContainer}
          />
        )}
        <div className={styles.itemDetails}>
          {forInvoice &&
            <svg
              className={styles.plusNegative2}
              onClick={onRemoveClick}
              clipRule="evenodd"
              fillRule="evenodd"
              strokeLinejoin="round"
              strokeMiterlimit="2"
              viewBox="0 0 24 24"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="m12.002 2c5.518 0 9.998 4.48 9.998 9.998 0 5.517-4.48 9.997-9.998 9.997-5.517 0-9.997-4.48-9.997-9.997 0-5.518 4.48-9.998 9.997-9.998zm0 1.5c-4.69 0-8.497 3.808-8.497 8.498s3.807 8.497 8.497 8.497 8.498-3.807 8.498-8.497-3.808-8.498-8.498-8.498zm-.747 7.75h-3.5c-.414 0-.75.336-.75.75s.336.75.75.75h3.5v3.5c0 .414.336.75.75.75s.75-.336.75-.75v-3.5h3.5c.414 0 .75-.336.75-.75s-.336-.75-.75-.75h-3.5v-3.5c0-.414-.336-.75-.75-.75s-.75.336-.75.75z"
                fillRule="nonzero"
              />
            </svg>

          }
          {/* <input
          className={`${
            forInvoice ? styles.itemInvoiceName : styles.itemName
          } ${isBeingEdit || blank ? styles.blank : styles.notblank} ${
            !isAvailable ? styles.disabled : ""
          }`}
          value={itemName}
          placeholder="Nama item"
          onChange={handleNameChange}
          disabled={!blank && !isBeingEdit}
        /> */}
          <div style={{ marginRight: forInvoice ? 10 : 0 }}>
            <h3 className={styles.title} style={{ width: forInvoice ? 160 : 'auto' }}>{itemName}</h3>
            {!forInvoice && (
              <div className={styles.priceRow}>
                {promoPrice && promoPrice != 0 && promoPrice != '' ? (
                  <>
                    <div className={styles.promoBadge} style={{ background: !isAvailable ? 'gray' : undefined }}>
                      Promo {(((initialPrice - promoPrice) / initialPrice) * 100).toFixed(0)}%
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span className={styles.priceNow}>Rp {formatCurrency(promoPrice)}</span>
                      <span className={styles.priceOld}>Rp {formatCurrency(initialPrice)}</span>
                    </div>
                  </>
                ) : (
                  <span className={styles.priceNow}>Rp {formatCurrency(initialPrice)}</span>
                )}
              </div>
            )}
          </div>
          {forInvoice && (
            <>
              <p className={styles.multiplySymbol}>x</p>
              <p className={styles.qtyInvoice}>{itemQty}</p>
            </>
          )}

          {!forInvoice && (
            !isBeingEdit && itemQty > 0 ? (
              <div className={styles.itemQty}>
                <div className={styles.qtyGroup}>
                  <button className={styles.qtyBtn} onClick={handleNegativeClick} aria-label="Kurangi">-</button>
                  {!blank && !isBeingEdit ? (
                    <span className={styles.qtyVal}>{itemQty}</span>
                  ) : (
                    <input className={styles.itemQtyInput} value={itemQty} onChange={handleQtyChange} disabled={!blank && !isBeingEdit} />
                  )}
                  <button className={styles.qtyBtn} onClick={handlePlusClick} aria-label="Tambah">+</button>
                </div>
              </div>
            ) : !blank && !isBeingEdit ? (
              <div className={styles.itemQty}>
                <button className={styles.addButton} onClick={handlePlusClick} disabled={!isAvailable}>
                  Pesan
                </button>
              </div>
            ) : (
              <div className={styles.itemQty}>
                <button className={styles.addButton} style={{ backgroundColor: '#ffffff', color: 'var(--brand-sage, #6B8F71)', borderColor: 'var(--brand-sage, #6B8F71)', width: 150 }} onClick={isBeingEdit ? handleUpdate : handleCreate}>
                  {isBeingEdit ? 'Simpan' : 'Buat'}
                </button>
              </div>
            )
          )}

          {forInvoice && (
            <p className={styles.itemPriceInvoice}>Rp {formatCurrency(itemQty * (promoPrice > 0 ? promoPrice : itemPrice))}</p>
          )}
        </div>
        {forCart && (
          <div className={styles.remove} onClick={handleRemoveClick}>
            ⓧ
          </div>
        )}
        {/* {blank && (
        <button className={styles.createItem} onClick={handleCreate}>
          Create Item
        </button>
      )} */}
      </div>
      {itemDescription && itemDescription != 'undefined' && itemDescription?.length ? (
        <div>
          <p className={styles.desc} style={{ padding: '4px 6px', margin: 0 }}>{itemDescription}</p>
        </div>
      ) : null}
    </div>
  );
};

export default Item;
