import { useState, useEffect } from "react";
import {
  getStorage,
  ref,
  uploadBytesResumable,
  getDownloadURL,
} from "firebase/storage";
import { updateProduct } from "../redux/apiCalls";
import app from "../firebase";
import { useAppDispatch } from "../redux/store";
interface Product {
  _id: string;
  title: string;
  description: string;
  categories: [];
  img: string;
  price: number;
  color: string[];
  quantity: number;
  inStock: boolean;
}
interface EditProductProps {
  product: Product;
}
const EditProduct: React.FC<EditProductProps> = ({ product }) => {
  const [inputs, setInputs] = useState<Product>(product);
  const [file, setFile] = useState<File[]>([]);
  const [cat, setCat] = useState<string[]>([]);
  const dispatch = useAppDispatch();

  useEffect(() => {
    setInputs(product);
    setCat(product.categories);
  }, [product]);

  const handleChange = (
    e:
      | React.ChangeEvent<HTMLInputElement>
      | React.ChangeEventHandler<HTMLTextAreaElement>
  ) => {
    setInputs((prev) => {
      return { ...prev, [e.target.name]: e.target.value };
    });
  };

  const handleCategories = (e: React.ChangeEvent<HTMLInputElement>) => {
    setCat(e.target.value.split(","));
  };

  const handleSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setInputs((prev) => {
      return { ...prev, [e.target.name]: e.target.value };
    });
  };

  const handleClick = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
    e.preventDefault();

    const updatedProduct = {
      ...inputs,
      categories: cat,
    };

    // Check for changes in input fields
    if (
      updatedProduct.title !== product.title ||
      updatedProduct.description !== product.description ||
      updatedProduct.price !== product.price ||
      updatedProduct.quantity !== product.quantity ||
      updatedProduct.inStock !== product.inStock
    ) {
      updateProduct(product._id, updatedProduct, dispatch);
    }

    if (file && file.length > 0) {
      const storage = getStorage(app);
      const fileName = new Date().getTime() + file[0].name;
      const storageRef = ref(storage, fileName);
      const uploadTask = uploadBytesResumable(storageRef, file[0]);

      uploadTask.on(
        "state_changed",
        (snapshot) => {
          const progress =
            (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          console.log("Upload is " + progress + "% done");
          switch (snapshot.state) {
            case "paused":
              console.log("Upload is paused");
              break;
            case "running":
              console.log("Upload is running");
              break;
            default:
          }
        },
        (error) => {
          console.log("Upload error: " + error);
        },
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
            const updatedProduct = {
              ...inputs,
              img: downloadURL,
              categories: cat,
            };
            updateProduct(product._id, updatedProduct, dispatch);
          });
        }
      );
    }
  };

  return (
    <>
      <h1 className="productTitle">Edit Product</h1>
      <main className="editProduct">
        <form className="editProduct__editProductForm">
          <section className="editProduct__editProductItem">
            <label>Image</label>
            <input
              type="file"
              id="file"
              onChange={(e) => {
                const files = e.target.files;
                if (files && files.length > 0) {
                  setFile([files[0]]);
                }
              }}
            />
          </section>
          <section className="editProduct__editProductItem">
            <label>Title</label>
            <input
              name="title"
              type="text"
              placeholder="Apple Airpods"
              value={inputs.title}
              onChange={handleChange}
            />
          </section>
          <section className="editProduct__editProductItem">
            <label htmlFor="productDescription">Product Description</label>
            <textarea
              name="description"
              type="text"
              id="productDescription"
              placeholder=""
              value={inputs.description}
              onChange={handleChange}
            />
          </section>
          <section className="editProduct__editProductItem">
            <label htmlFor="productPrice">Product Price</label>
            <input
              name="price"
              type="number"
              id="productPrice"
              placeholder=""
              value={inputs.price}
              onChange={handleChange}
            />
          </section>
          <section className="editProduct__editProductItem">
            <label htmlFor="productQuantity">Product Quantity</label>
            <input
              name="quantity"
              type="number"
              id="productQuantity"
              placeholder=""
              value={inputs.quantity}
              onChange={handleChange}
            />
          </section>
          <section className="editProduct__editProductItem">
            <label htmlFor="productCategories">Product Categories</label>
            <input
              name="categories"
              type="text"
              id="productCategories"
              placeholder=""
              value={cat.join(",")}
              onChange={handleCategories}
            />
          </section>
          <section className="editProduct__editProductItem">
            <label htmlFor="idstock">Stock</label>
            <select
              name="inStock"
              id="idstock"
              value={inputs.inStock.toString()}
              onChange={handleSelect}
            >
              <option value="true">true</option>
              <option value="false">false</option>
            </select>
          </section>
          <button
            onClick={handleClick}
            className="editProduct__editProductButton"
          >
            Update
          </button>
        </form>
        <section className="editProduct__updatedProduct">
          <div className="imageContainer">
            <img src={inputs.img} alt="product" className="fitImage" />
          </div>
          <section className="editProduct__productItem">
            <h3>Title:</h3>
            <p>{inputs.title}</p>
          </section>
          <section className="editProduct__productItem">
            <h3>Description:</h3>
            <p>{inputs.description}</p>
          </section>
          <section className="editProduct__productItem">
            <h3>Price:</h3>
            <p>{inputs.price}</p>
          </section>
          <section className="editProduct__productItem">
            <h3>Quantity:</h3>
            <p>{inputs.quantity}</p>
          </section>
          <section className="editProduct__productItem">
            <h3>Categories:</h3>
            <p>{cat.join(",")}</p>
          </section>
          <section className="editProduct__productItem">
            <h3>In Stock:</h3>
            <p>{inputs.inStock.toString()}</p>
          </section>
        </section>
      </main>
    </>
  );
};

export default EditProduct;
Type '(e: React.ChangeEvent<HTMLInputElement> | React.ChangeEventHandler<HTMLTextAreaElement>) => void' is not assignable to type 'ChangeEventHandler<HTMLTextAreaElement>'.
  Types of parameters 'e' and 'event' are incompatible.
    Type 'ChangeEvent<HTMLTextAreaElement>' is not assignable to type 'ChangeEvent<HTMLInputElement> | ChangeEventHandler<HTMLTextAreaElement>'.
      Type 'ChangeEvent<HTMLTextAreaElement>' is not assignable to type 'ChangeEvent<HTMLInputElement>'.
        Type 'HTMLTextAreaElement' is missing the following properties from type 'HTMLInputElement': accept, align, alt, capture, and 27 more.ts(2322)
index.d.ts(2511, 9): The expected type comes from property 'onChange' which is declared here on type 'DetailedHTMLProps<TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement>'