import React, { useEffect, useState } from "react";
import "../../assets/styles/modal.css";
import "../../assets/styles/itembox.css";
import FormUpdateItem from "../form/formUpdateItem";
import { Image } from "../parts/image";
import { Description } from "../parts/description";
import { Characteristic } from "../parts/characteristic";
import { deleteItem } from '../../api/item'


export const ItemBox = ({ model, brand, purchaseDate, price, _id }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const openModal = () => {
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
    };

    const onDelete = async () => {
        let response = await deleteItem(_id);
        if (response?.status >= 200 && response?.status < 300) {
            window.location.reload();
        }
    } 

  let productname = brand + " " + model;
  let formatedPrice = price + "€";
  let formatedDate = new Date(purchaseDate).toLocaleDateString("fr-FR");

  let request = brand + " " + model;

    return (
        <div className="product-details">
            <Description title={productname}>
                <Image request={request} alt="Product" />
                <Characteristic label="Model" value={model} />
                <Characteristic label="Brand" value={brand} />
                <Characteristic label="Purchase Date" value={formatedDate} />
                <Characteristic label="Price" value={formatedPrice} />
                {/* Boutons d'édition et de suppression */}
                <div className="button-group">
                    <button className="edit-button" onClick={openModal}>Edit</button>
                    <button className="delete-button" onClick={onDelete}>Delete</button>
                </div>
            </Description>
            {/* Fenêtre modale */}
            {isModalOpen && (
                <div className="modal">
                    <div className="modal-content">
                        <span className="close" onClick={closeModal}>
                            &times;
                        </span>
                        <FormUpdateItem itemId={_id}>
                            {console.log("item ID :" + _id)}
                        </FormUpdateItem>
                    </div>
                </div>
            )}
        </div>
    );
};
