import React, { useEffect, useState } from "react";
import { useHistory, useParams } from "react-router";
import emptyProduct from "../emptProduct";
import Config from "../config";

const emptyForm = {
  ...emptyProduct,
  imageFile: "",
};

ProductForm.defaultProps = {
  product: { ...emptyForm },
};

export default function ProductForm(props) {
  const { method } = props;
  const [form, setForm] = useState({ ...emptyForm });
  const [imageMode, setImageMode] = useState("url");
  const [errors, setErrors] = useState([]);
  const history = useHistory();
  const { productId } = useParams("productId");

  useEffect(() => {
    fetch(`${Config.inventoryUrl}/${productId}/`).then((res) => {
      if (res.ok) {
        // console.log(res);
        res.json().then((data) => {
          Object.keys(data).forEach((key) => {
            if (data[key] === null) {
              data[key] = "";
            }
          });
          // console.log(data);
          setForm({ ...data });
        });
      }
    });
  }, [productId]);

  const validate = () => {
    setErrors([]);
    const errs = [];
    // console.log(form);
    if (form.sku.length < 3) {
      errs.push("SKU must be at least 3 characters");
    }
    if (form.upc.length < 3) {
      errs.push("UPC must be at least 3 characters");
    }
    if (form.productName.length === 0) {
      errs.push("Please enter a product name");
    }
    if (form.brand.length === 0) {
      errs.push("Please enter a brand");
    }
    if (form.category.length === 0) {
      errs.push("Please specify a category");
    }
    if (Number(form.price) <= 0) {
      errs.push("Price must be greater than 0");
    }
    if (Number(form.availableStock) <= 0) {
      errs.push("Stock must be greater than 0");
    }

    setErrors([...errs]);
  };

  const onSubmit = (e) => {
    e.preventDefault();
    validate();
    if (imageMode === "url") {
      delete form.imageFile;
    } else {
      delete form.prodImgUrl;
    }

    if (errors.length === 0) {
      // console.log(form);
      const url =
        method === "PUT"
          ? `${Config.inventoryUrl}/${productId}`
          : `${Config.inventoryUrl}`;
      fetch(url, {
        method,
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(form),
      })
        .then((res) => {
          if (res.ok) {
            // res.json().then((data) => console.log(data));
            history.push("/products");
          } else {
            setErrors([
              "The provided SKU was found on an existing object, please try another",
            ]);
          }
        })
        .catch((err) => {
          setErrors([err.message]);
        });
    }
  };

  return (
    <div className="container mt-3">
      {errors.length ? (
        <ul className="list-group">
          {errors.map((error, i) => (
            <li key={i} className="list-group-item list-group-item-danger">
              {error}
            </li>
          ))}
        </ul>
      ) : null}
      <form onSubmit={onSubmit}>
        <div className="row mt-3">
          <div className="col">
            <label htmlFor="productSku" className="form-label">
              SKU
            </label>
            <input
              disabled={method === "PUT" ? true : false}
              required
              name="sku"
              type="text"
              className="form-control"
              id="productSku"
              value={form.sku}
              onChange={(e) => setForm({ ...form, sku: e.target.value })}
            />
          </div>
          <div className="col">
            <label htmlFor="productUpc" className="form-label">
              UPC
            </label>
            <input
              required
              name="upc"
              type="text"
              className="form-control"
              id="productUpc"
              value={form.upc}
              onChange={(e) => setForm({ ...form, upc: e.target.value })}
            />
          </div>
        </div>
        <div className="row mt-3">
          <div className="col-6">
            <div>
              <label htmlFor="productName" className="form-label">
                Name
              </label>
              <input
                required
                name="productName"
                type="text"
                className="form-control"
                id="productName"
                value={form.productName}
                onChange={(e) =>
                  setForm({ ...form, productName: e.target.value })
                }
              />
            </div>
            <div>
              <label htmlFor="brand" className="form-label">
                Brand
              </label>
              <input
                required
                name="brand"
                type="text"
                className="form-control"
                id="brand"
                value={form.brand}
                onChange={(e) => setForm({ ...form, brand: e.target.value })}
              />
            </div>
            <div>
              <label htmlFor="category" className="form-label">
                Category
              </label>
              <input
                required
                name="category"
                type="text"
                className="form-control"
                id="category"
                value={form.category}
                onChange={(e) => setForm({ ...form, category: e.target.value })}
              />
            </div>
          </div>
          <div className="col-6">
            <label htmlFor="productDesc" className="form-label">
              Description
            </label>
            <textarea
              name="productDesciption"
              id="productDesc"
              cols="40"
              rows="7"
              className="form-control"
              value={form.productDescription}
              onChange={(e) =>
                setForm({ ...form, productDescription: e.target.value })
              }
            ></textarea>
          </div>
        </div>
        <div className="row mt-3">
          <div>
            <label htmlFor="price" className="form-label">
              Price
            </label>
            <input
              required
              name="price"
              type="number"
              className="form-control"
              id="price"
              value={form.price}
              onChange={(e) => setForm({ ...form, price: e.target.value })}
            />
          </div>
          <div>
            <label htmlFor="stock" className="form-label">
              Stock
            </label>
            <input
              disabled={method === "PUT" ? true : false}
              required
              name="availableStock"
              type="number"
              className="form-control"
              id="stock"
              value={form.availableStock}
              onChange={(e) =>
                setForm({ ...form, availableStock: e.target.value })
              }
            />
          </div>
        </div>
        {imageMode === "upload" ? (
          <div className="row mt-3">
            <div>
              <label htmlFor="productImage" className="form-label">
                Image File
              </label>
              <input
                id="productImage"
                name="imageFile"
                className="form-control form-control-lg"
                type="file"
                value={form.imageFile}
                onChange={(e) =>
                  setForm({ ...form, imageFile: e.target.value })
                }
              ></input>
              <button
                type="button"
                className="btn btn-outline-primary mt-3"
                onClick={() => {
                  setForm({ ...form, imageFile: "" });
                  setImageMode("url");
                }}
              >
                Specify Image URL
              </button>
            </div>
          </div>
        ) : null}
        {imageMode === "url" ? (
          <div className="row mt-3">
            <div>
              <label htmlFor="prodImgUrl" className="form-label">
                Image URL
              </label>
              <input
                name="productImageUrl"
                type="text"
                className="form-control"
                id="prodImgUrl"
                value={form.productImageUrl}
                onChange={(e) =>
                  setForm({ ...form, productImageUrl: e.target.value })
                }
              />
              <button
                type="button"
                className="btn btn-outline-primary mt-3"
                onClick={() => setImageMode("upload")}
              >
                Upload Image
              </button>
            </div>
          </div>
        ) : null}

        <div className="row mt-3">
          <div className="col-12">
            <button type="submit" className="btn btn-primary mt-3">
              Submit
            </button>
          </div>
        </div>
      </form>
    </div>
  );
}
