import { jsxs, Fragment, jsx } from "react/jsx-runtime";
import { useState, useEffect } from "react";
import { I as InputError } from "./InputError-4ef2eb93.js";
import { I as InputLabel } from "./InputLabel-747c5b8a.js";
import { P as PrimaryButton } from "./PrimaryButton-eeb7392f.js";
import { T as TextInput } from "./TextInput-1224a4d9.js";
import { usePage } from "@inertiajs/react";
/* empty css                           */import { FaSpinner } from "react-icons/fa/index.esm.js";
import { O as OrderDetails } from "./OrderDetails-27b53aa0.js";
import Swal from "sweetalert2";
import { L as LoadingSpinner } from "./LoadingSpinner-1e6a98f0.js";
import imageCompression from "browser-image-compression";
import "react-loader-spinner";
function AddProdcts({ orderData, className = "" }) {
  const user = usePage().props.auth.user;
  const clientId = user.Client_ID;
  const [selectedDate, setSelectedDate] = useState("");
  useState([]);
  const [errors, setErrors] = useState({});
  const [editingProductId, setEditingProductId] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [imageData, setImageData] = useState(null);
  const [image, setImage] = useState(null);
  const [insertProductDetails, setinsertProductDetails] = useState(false);
  const [readOnly, setReadOnly] = useState(false);
  const [orderDetailsData, setorderDetailsData] = useState(null);
  const [orderId, setorderId] = useState("");
  const formatDate = (dateString) => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  };
  const getImageMimeType = (imageData2) => {
    if (imageData2.startsWith("/9j/")) {
      return "image/jpeg";
    } else if (imageData2.startsWith("iVBORw0KG")) {
      return "image/png";
    } else if (imageData2.startsWith("R0lGODlh")) {
      return "image/gif";
    }
    return "image/jpeg";
  };
  const currentDate = /* @__PURE__ */ new Date();
  const formattedDate = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, "0")}-${currentDate.getDate().toString().padStart(2, "0")}`;
  const handleInputChange = async (e) => {
    if (e.target.type === "file") {
      const file = e.target.files[0];
      const options = {
        maxSizeMB: 0.8,
        // Maximum size in megabytes
        maxWidthOrHeight: 1024,
        // Maximum width or height
        useWebWorker: true
        // Use a web worker for compression (recommended for large images)
      };
      try {
        let base64Image = "";
        const compressedFile = await imageCompression(file, options);
        const reader = new FileReader();
        reader.onload = () => {
          base64Image = reader.result.split(",")[1];
          setImageData(base64Image);
          setImage(base64Image);
          setFormData({ ...formData, Order_Image: base64Image });
        };
        reader.readAsDataURL(compressedFile);
      } catch (error) {
        console.error("Image compression error:", error);
      }
    } else {
      setFormData({
        ...formData,
        [e.target.name]: e.target.value
      });
    }
  };
  const [formData, setFormData] = useState({
    ClientName: user.name,
    Order: "",
    EntryDate: formattedDate,
    DeadlineDate: selectedDate,
    Collection: "",
    Goldcolor: "",
    Quantity: "",
    Category: "",
    Size: "",
    Descriptions: "",
    Remarks: "",
    Order_Image: null,
    Client_ID: clientId
  });
  useEffect(() => {
    if (orderData) {
      const mainOrdrData = orderData.orderMain;
      setFormData({
        ClientName: user.name,
        Order: mainOrdrData.ID,
        EntryDate: formatDate(mainOrdrData.Entry_Date),
        //currentDate,
        DeadlineDate: formatDate(mainOrdrData.Deadline_Date),
        Collection: mainOrdrData.Collection,
        Goldcolor: mainOrdrData.Gold_Color,
        Quantity: mainOrdrData.Quantity,
        Category: mainOrdrData.Category,
        Size: mainOrdrData.Size,
        Descriptions: mainOrdrData.Description,
        Remarks: mainOrdrData.Remarks,
        Order_Image: mainOrdrData.Image,
        Client_ID: mainOrdrData.Client_ID
      });
      setorderId(mainOrdrData.ID);
      setorderDetailsData(orderData.orderDetails);
      setImageData(mainOrdrData.Image);
      setEditingProductId(mainOrdrData.ID);
    }
  }, []);
  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    setErrors({});
    if (editingProductId) {
      await axios.post(`/api/product-update/${editingProductId}`, formData).then((data) => {
        if (data.status) {
          setIsLoading(false);
          Swal.fire({
            title: "Success!",
            text: "Order data Updated successfully.",
            icon: "success",
            confirmButtonText: "OK"
          }).then((result) => {
            if (result.isConfirmed) {
              setReadOnly(true);
              setinsertProductDetails(true);
            }
          });
        }
      }).catch((error) => {
        setIsLoading(false);
        console.error(error);
      });
    } else {
      const formDataToSend = new FormData();
      for (const key in formData) {
        formDataToSend.append(key, formData[key]);
      }
      await fetch("/api/product-store", {
        method: "POST",
        body: formDataToSend
      }).then((response) => response.json()).then((data) => {
        if (data.status) {
          setIsLoading(false);
          setorderId(data.ID);
          Swal.fire({
            title: "Success!",
            text: "Order data Updated successfully.",
            icon: "success",
            confirmButtonText: "OK"
          }).then((result) => {
            if (result.isConfirmed) {
              setReadOnly(true);
              setinsertProductDetails(true);
            }
          });
        } else {
          setIsLoading(false);
          setErrors(data.errors);
        }
      }).catch((error) => {
        setIsLoading(false);
        console.error(error);
      });
    }
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    !isLoading ? /* @__PURE__ */ jsx("div", { className: "p-4 sm:p-8 bg-white shadow sm:rounded-lg", children: /* @__PURE__ */ jsxs("section", { className: "max", children: [
      /* @__PURE__ */ jsxs("header", { className: "mb-3", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-medium text-gray-900", children: "Order Main Details" }),
        /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-gray-600", children: "Add your order informations." })
      ] }),
      /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, encType: "multipart/form-data", children: [
        /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs("div", { className: "row", children: [
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "hidden",
              id: "ClientName",
              name: "Client_ID",
              value: clientId
            }
          ),
          /* @__PURE__ */ jsxs("div", { className: "col-sm-4 mb-4", children: [
            /* @__PURE__ */ jsx(InputLabel, { htmlFor: "ClientName", className: "form-lable", value: "Client Name" }),
            /* @__PURE__ */ jsx(
              TextInput,
              {
                id: "ClientName",
                name: "ClientName",
                className: "mt-1 block w-full",
                value: formData.ClientName,
                onChange: handleInputChange,
                isFocused: true,
                autoComplete: "ClientName",
                readOnly: true
              }
            ),
            /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.ClientName })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-sm-4 mb-4 ", children: [
            /* @__PURE__ */ jsx(InputLabel, { htmlFor: "EntryDate", value: "Entry Date" }),
            /* @__PURE__ */ jsx(
              "input",
              {
                type: "date",
                className: "mt-1 block w-full",
                name: "EntryDate",
                value: formattedDate,
                readOnly: true
              }
            ),
            /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.EntryDate })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-sm-4 mb-4 ", children: [
            /* @__PURE__ */ jsx(InputLabel, { htmlFor: "DeadlineDate", value: "Deadline Date" }),
            /* @__PURE__ */ jsx(
              "input",
              {
                type: "date",
                className: "mt-1 block w-full",
                name: "DeadlineDate",
                value: formData.DeadlineDate,
                onChange: handleInputChange,
                readOnly
              }
            ),
            /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.DeadlineDate })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-sm-4 mb-4 ", children: [
            /* @__PURE__ */ jsx(InputLabel, { htmlFor: "Category", value: "Category" }),
            /* @__PURE__ */ jsx(
              TextInput,
              {
                id: "Category",
                name: "Category",
                className: "mt-1 block w-full",
                value: formData.Category,
                onChange: handleInputChange,
                autoComplete: "Category"
              }
            ),
            /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.Category })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-sm-4 mb-4", children: [
            /* @__PURE__ */ jsx(InputLabel, { htmlFor: "Collection", value: "Collection" }),
            /* @__PURE__ */ jsx(
              TextInput,
              {
                id: "Collection",
                name: "Collection",
                className: "mt-1 block w-full",
                value: formData.Collection,
                onChange: handleInputChange,
                autoComplete: "Collection",
                readOnly
              }
            ),
            /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.Collection })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-sm-4 mb-4 ", children: [
            /* @__PURE__ */ jsx(InputLabel, { htmlFor: "Goldcolor", value: "Gold Color" }),
            /* @__PURE__ */ jsx(
              TextInput,
              {
                id: "Goldcolor",
                name: "Goldcolor",
                className: "mt-1 block w-full",
                value: formData.Goldcolor,
                onChange: handleInputChange,
                autoComplete: "Goldcolor",
                readOnly
              }
            ),
            /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.Goldcolor })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-sm-4 mb-4", children: [
            /* @__PURE__ */ jsx(InputLabel, { htmlFor: "Size", value: "Size" }),
            /* @__PURE__ */ jsx(
              TextInput,
              {
                id: "Size",
                name: "Size",
                className: "mt-1 block w-full",
                value: formData.Size,
                onChange: handleInputChange,
                autoComplete: "Size",
                readOnly
              }
            ),
            /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.Size })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-sm-4 mb-4", children: [
            /* @__PURE__ */ jsx(InputLabel, { htmlFor: "Quantity", value: "Quantity" }),
            /* @__PURE__ */ jsx(
              TextInput,
              {
                id: "Quantity",
                name: "Quantity",
                className: "mt-1 block w-full",
                value: formData.Quantity,
                onChange: handleInputChange,
                autoComplete: "Quantity",
                readOnly
              }
            ),
            /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.Quantity })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-sm-4 mb-4", children: [
            /* @__PURE__ */ jsx(InputLabel, { htmlFor: "Remarks", value: "Remarks" }),
            /* @__PURE__ */ jsx(
              "textarea",
              {
                type: "textarea",
                id: "Remarks",
                name: "Remarks",
                className: "mt-1 block w-full resize-none border rounded-md p-2 h-10 focus:outline-none focus:ring focus:border-blue-500",
                value: formData.Remarks,
                onChange: handleInputChange,
                autoComplete: "Remarks",
                rows: 2,
                cols: 40,
                readOnly
              }
            ),
            /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.Remarks })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-sm-4 mb-4", children: [
            /* @__PURE__ */ jsx(InputLabel, { htmlFor: "Order_Image", value: "Image" }),
            !readOnly ? /* @__PURE__ */ jsxs("label", { htmlFor: "Order_Image", className: "mt-1 block w-half bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded cursor-pointer inline-flex items-center", children: [
              /* @__PURE__ */ jsx("svg", { className: "w-4 h-4 mr-2", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: "2", d: "M12 6v6m0 0v6m0-6h6m-6 0H6" }) }),
              "Upload Image",
              /* @__PURE__ */ jsx("input", { type: "file", id: "Order_Image", className: "hidden", name: "Order_Image", onChange: handleInputChange, accept: "image/*", readOnly })
            ] }) : null,
            /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.Order_Image })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "col-sm-4 mb-4", children: imageData && /* @__PURE__ */ jsx("img", { className: "w-48 h-32 object-cover rounded-lg border-2 border-gray-300 shadow-lg", src: `data:${getImageMimeType(imageData)};base64,${imageData}`, alt: "Preview" }) })
        ] }) }),
        !readOnly && /* @__PURE__ */ jsx("div", { className: "items-center", children: /* @__PURE__ */ jsxs(PrimaryButton, { disabled: readOnly, className: "btn btnDark mt-4", children: [
          isLoading ? /* @__PURE__ */ jsx(FaSpinner, { className: "spinner" }) : "",
          editingProductId ? "Update Order" : "Save Order"
        ] }) })
      ] })
    ] }) }) : /* @__PURE__ */ jsx(LoadingSpinner, {}),
    insertProductDetails && /* @__PURE__ */ jsx("div", { className: "p-4 sm:p-8 bg-white shadow sm:rounded-lg", children: /* @__PURE__ */ jsxs("section", { className: "max", children: [
      /* @__PURE__ */ jsxs("header", { className: "mb-3", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-medium text-gray-900", children: "Products Details" }),
        /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-gray-600", children: "Add More Product details." })
      ] }),
      /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(OrderDetails, { orderDetailsData, fData: formData, orderId }) })
    ] }) })
  ] });
}
export {
  AddProdcts as default
};
