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 { FaTrashAlt, FaSpinner } from "react-icons/fa/index.esm.js";
import { O as OrderDetails } from "./OrderDetails-27b53aa0.js";
import Swal from "sweetalert2";
import imageCompression from "browser-image-compression";
function DyanamicOrderDetails({ orderDetailsData, fData, orderId, onDynamicFieldsChange, vueOnly }) {
  const data = fData;
  const [errors, setErrors] = useState({});
  const [OrdrId, setOrdrId] = useState("");
  const [clientId, seclientId] = useState("");
  const [options, setOptions] = useState([]);
  useState("");
  useState(false);
  const [readOnly, setReadOnly] = useState("false");
  const [inputFields, setInputFields] = useState(orderDetailsData || [
    {
      ID: "",
      Type: "",
      Quantity: "",
      Notes: "",
      Client_ID: clientId,
      Order_Number: data.ID
    }
  ]);
  useEffect(() => {
    setReadOnly(vueOnly);
    if (orderId != null) {
      setOrdrId(orderId);
    } else {
      setOrdrId(data.orderId);
    }
    seclientId(data.Client_ID);
  }, [readOnly]);
  const handleInputChange = (index, event) => {
    const updatedFields = [...inputFields];
    updatedFields[index][event.target.name] = event.target.value;
    setInputFields(updatedFields);
    onDynamicFieldsChange(updatedFields);
  };
  const handleAddField = () => {
    setInputFields([...inputFields, { ID: "", Type: "", Quantity: "", Notes: "", Client_ID: clientId, Order_ID: data.ID }]);
  };
  useEffect(() => {
    axios.get("/api/orders-types").then((response) => {
      const data2 = response.data;
      setOptions(data2);
    }).catch((error) => {
      console.error("Error fetching data:", error);
    });
  }, []);
  const handleRemoveField = (index) => {
    const updatedFields = [...inputFields];
    updatedFields.splice(index, 1);
    setInputFields(updatedFields);
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      "input",
      {
        type: "hidden",
        name: "Client_ID",
        value: data.Client_ID
      }
    ),
    /* @__PURE__ */ jsx(
      "input",
      {
        type: "hidden",
        name: "Order_ID",
        value: data.Order
      }
    ),
    inputFields.map((field, index) => /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs("div", { className: "row", children: [
      /* @__PURE__ */ jsx(
        "input",
        {
          type: "hidden",
          name: "ID",
          value: field.ID
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "col-sm-2 mb-2", children: [
        /* @__PURE__ */ jsx(InputLabel, { htmlFor: "Type", className: "form-lable", value: "Type" }),
        /* @__PURE__ */ jsxs(
          "select",
          {
            id: "dynamic-select",
            name: "Type",
            value: field.Type,
            onChange: (e) => handleInputChange(index, e),
            className: "mt-1 block w-full",
            required: true,
            readOnly,
            children: [
              /* @__PURE__ */ jsx("option", { value: "", readOnly, children: "Select an option" }),
              options.map((option) => /* @__PURE__ */ jsx("option", { value: option.Type_Name, readOnly, children: option.Type_Name }, option.Type_Name))
            ]
          }
        ),
        /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.Type })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "col-sm-4 mb-4", children: [
        /* @__PURE__ */ jsx(InputLabel, { htmlFor: "Quantity", className: "form-lable", value: "Quantity" }),
        /* @__PURE__ */ jsx(
          TextInput,
          {
            id: "Quantity",
            name: "Quantity",
            className: "mt-1 block w-full",
            value: field.Quantity,
            onChange: (e) => handleInputChange(index, e),
            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: "Notes", className: "form-lable", value: "Notes" }),
        /* @__PURE__ */ jsx(
          "textarea",
          {
            type: "textarea",
            id: "Notes",
            name: "Notes",
            className: "mt-1 block w-full",
            value: field.Notes,
            onChange: (e) => handleInputChange(index, e),
            autoComplete: "Notes",
            rows: 2,
            cols: 40,
            readOnly
          }
        ),
        /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.Notes })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "col-sm-2 mt-10", children: readOnly == false && /* @__PURE__ */ jsx("button", { onClick: () => handleRemoveField(index), children: /* @__PURE__ */ jsx(FaTrashAlt, { className: "text-blue-500 hover:text-red-600 text-lg hover:text-xl cursor-pointer" }) }) })
    ] }) }, index)),
    !readOnly && /* @__PURE__ */ jsx("div", { className: "row", children: /* @__PURE__ */ jsx("div", { className: "col-sm-12", children: /* @__PURE__ */ jsx("button", { type: "button", className: "initial float-right w-40 border border-red-950 text-red-500 hover:text-white hover:bg-blue-500 hover:border-blue-500 rounded transition", onClick: handleAddField, children: "Add" }) }) })
  ] });
}
function EditProduct({ orderData, className = "" }) {
  const user = usePage().props.auth.user;
  const postStatus = orderData.orderMain.Status;
  const clientId = user.Client_ID;
  useState("");
  useState([]);
  const [errors, setErrors] = useState({});
  const [editingProductId, setEditingProductId] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [imageData, setImageData] = useState(orderData.Image);
  const [image, setImage] = useState(null);
  const [insertProductDetails, setinsertProductDetails] = useState(false);
  const [readOnly, setReadOnly] = useState("true");
  const [mainOrdrData, setMainOrdrData] = useState(orderData.orderMain);
  const [orderDetailsData, setorderDetailsData] = useState(orderData.orderDetails);
  const [orderId, setorderId] = useState("");
  const [dynamicFields, setDynamicFields] = useState([]);
  const [base64ImageData, setBase64ImageData] = useState("");
  useEffect(() => {
    if (postStatus == "New") {
      setReadOnly(false);
    } else {
      setReadOnly(true);
    }
  }, [postStatus]);
  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 [formData, setFormData] = useState({
    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
  });
  useEffect(() => {
    if (orderData) {
      const mainOrdrData2 = orderData.orderMain;
      setFormData({
        ClientName: user.name,
        Order: mainOrdrData2.ID,
        EntryDate: formatDate(mainOrdrData2.Entry_Date),
        //currentDate,
        DeadlineDate: formatDate(mainOrdrData2.Deadline_Date),
        Collection: mainOrdrData2.Collection,
        Goldcolor: mainOrdrData2.Gold_Color,
        Quantity: mainOrdrData2.Quantity,
        Category: mainOrdrData2.Category,
        Size: mainOrdrData2.Size,
        Descriptions: mainOrdrData2.Description,
        Remarks: mainOrdrData2.Remarks,
        Order_Image: mainOrdrData2.Image,
        Client_ID: mainOrdrData2.Client_ID
      });
      setImage(mainOrdrData2.Image);
      setorderId(mainOrdrData2.ID);
      setorderDetailsData(orderData.orderDetails);
      setImageData(mainOrdrData2.Image);
      setEditingProductId(mainOrdrData2.ID);
    }
  }, []);
  const handleDynamicFieldsChange = (updatedFields) => {
    setDynamicFields(updatedFields);
    console.log("Updated Dynamic Fields:", updatedFields);
  };
  const handleInputChange = async (e) => {
    if (e.target.type === "file") {
      const file = e.target.files[0];
      const options = {
        maxSizeMB: 1,
        // 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];
          console.log(base64Image);
          setBase64ImageData(base64Image);
          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 handleSubmit = async (e) => {
    e.preventDefault();
    setErrors({});
    const dynamicFieldsData = [{}];
    dynamicFields.forEach((field, index) => {
      dynamicFieldsData[index] = {
        ID: field.ID,
        Order_Number: field.Order_Number,
        Client_ID: field.Client_ID,
        Type: field.Type,
        Quantity: field.Quantity,
        Notes: field.Notes
      };
    });
    const combinedData = {
      ...formData,
      dynamicFieldsData
    };
    await axios.post(`/api/product-update/${editingProductId}`, {
      combinedData
    }).then((data) => {
      if (data.status) {
        Swal.fire({
          title: "Success!",
          text: "Order data Updated successfully.",
          icon: "success",
          confirmButtonText: "OK"
        }).then((result) => {
          if (result.isConfirmed) {
            const url = `/orders`;
            window.location.replace(url);
          }
        });
      }
    }).catch((error) => {
      console.error(error);
    });
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__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__ */ jsxs("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,
                  required: true,
                  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",
                  readOnly
                }
              ),
              /* @__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/*" })
              ] }) : null,
              /* @__PURE__ */ jsx(InputError, { className: "mt-2", message: errors.Order_Image })
            ] }),
            /* @__PURE__ */ jsx("div", { className: "col-sm-4 mb-4", children: image && /* @__PURE__ */ jsx("img", { src: `data:${getImageMimeType(image)};base64,${image}`, className: "w-48 h-32 object-cover rounded-lg border-2 border-gray-300 shadow-lg", alt: "Preview" }) })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "row", children: /* @__PURE__ */ jsx(DyanamicOrderDetails, { orderDetailsData, fData: formData, orderId, onDynamicFieldsChange: handleDynamicFieldsChange, vueOnly: readOnly }) })
        ] }),
        !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"
        ] }) })
      ] })
    ] }) }),
    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 {
  EditProduct as default
};
