import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import React from "react";

import axios from "axios";
import { Toast } from "primereact/toast";
import { useRef } from "react";
import { AutoComplete } from "primereact/autocomplete";
import { useState } from "react";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import { classNames } from "primereact/utils";
import { useForm, Controller, useFieldArray, set } from "react-hook-form";
import { useMemo } from "react";
import { useEffect } from "react";
import { Calendar } from "primereact/calendar";
import { Link } from "@inertiajs/react";
import { InputTextarea } from "primereact/inputtextarea";

export default function OrderConfirm({ auth, orders }) {
    const toast = useRef();
    const [client, setClient] = useState([]);
    const [road, setRoad] = useState("");
    const [invoiceType, setInvoiceType] = useState();
    const [clientId, setClientId] = useState();
    const FormSubmit = useRef(null);
    const [product, setProduct] = useState([]);
    const [status, setStatus] = useState("create");
    const [order, setOrders] = useState(orders);
    const [button, setButton] = useState(true);

    const [search, setSearchValue] = useState({
        product: null,
        client: null,
        road: null,
    });
    const scroll = useRef(null);
    const {
        register,
        control,
        handleSubmit,
        formState: { errors },
        setValue,
        watch,
        reset,
    } = useForm({
        reference_no: "",
        date: "",
        list: [],
    });

    useEffect(() => {
        if (order.client) {
            setSearchValue((old) => {
                return {
                    ...old,
                    client: order.client.name
                        ? order.client.name +
                          " (" +
                          order.client.number +
                          ")" +
                          " (" +
                          order.client.user_type +
                          ")"
                        : "",
                };
            });
        } else {
            setSearchValue((old) => {
                return {
                    ...old,
                    client: "",
                };
            });
        }

        if (order.status == 2) {
            setButton(false);
        }
        setTimeout(() => {
            reset({
                discount_first: order.discount_first,
                discount_second: order.discount_second,
                discount_second: order.discount_second,
                grand_total: order.grand_total,
                date: new Date(order.date),
                sr_id: order.sr.id,
                supplier_id: order.sr.supplier_id,
                costomer_id: order.client_id,
                order_id: order.id,
                total: order.total,
                note: order.note,
                list: order.order_details.map((e) => {
                    return {
                        attribute_id: e.attribute_id,
                        product_id: e.product_id,
                        seal_qty: Number(e?.sales_sum?.qty ?? 0),
                        quantity:
                            Number(e.quantity) - Number(e?.sales_sum?.qty ?? 0),
                        stock_qty: e?.attribute?.warehouse?.quantity ?? 0,
                        need_qty: e.quantity,
                        discount: e.discount,
                        discount: e.discount,
                        total:
                            e.quantity - Number(e?.sales_sum?.qty ?? 0) > 0
                                ? e.total
                                : 0,
                        price: e.price,
                        order_details_id: e.id,
                        product_name:
                            e.attribute.product.name + ` (${e.attribute.sku})`,
                    };
                }),
            });
        }, 1000);
    }, []);

    const { fields, append, prepend, remove } = useFieldArray({
        control,
        name: "list",
    });
    // Calculating the total value by summing up the total from each item
    let total = fields.reduce(
        (acc, item, index) => acc + Number(watch(`list.${index}.total`) || 0),
        0
    );

    // Watch discount fields
    const dis_1st = Number(watch("discount_first") || 0); // Default to 0 if undefined
    const dis_2nd = Number(watch("discount_second") || 0); // Default to 0 if undefined

    useMemo(() => {
        // Calculate the first discount
        const firstDiscount = total * (dis_1st / 100);

        // Calculate the total after applying the first discount
        const totalAfterFirstDiscount = total - firstDiscount;

        // Calculate the second discount based on the reduced total
        const secondDiscount = totalAfterFirstDiscount * (dis_2nd / 100);

        // Calculate the grand total after applying both discounts
        const grandTotal = totalAfterFirstDiscount - secondDiscount;

        // Set the calculated total and grand total in the form values
        setValue("total", total);
        setValue("grand_total", grandTotal.toFixed(2));
    }, [total, dis_1st, dis_2nd, setValue]); // Include setValue in dependencies

    // Road Template
    const roadTemplateIOptionList = (option) => {
        return (
            <div className="country-item">
                <div>{option.road_name}</div>
            </div>
        );
    };

    const filterRoad = (event) => {
        setTimeout(() => {
            axios
                .post(route("road-search"), { data: event.query })
                .then((response) => {
                    setRoad(response.data);
                });
        }, 250);
    };

    const filterClient = (event) => {
        setTimeout(() => {
            if (!search.road) {
                axios
                    .post(route("customer-search"), { data: event.query })
                    .then((response) => {
                        setClient(response.data.customer);
                    });
            } else {
                setClient([...client]);
            }
        }, 250);
    };

    // Client Template
    const clientTemplateIOptionList = (option) => {
        return (
            <div className="country-item">
                <div>
                    {option.name} ({option.number}) ({option.user_type})
                </div>
            </div>
        );
    };

    const productTemplateIOptionList = (option) => {
        return (
            <div className="country-item">
                <div>
                    {option.product.name} ({option.sku})
                </div>
            </div>
        );
    };
    const filterProduct = (event) => {
        setTimeout(() => {
            axios
                .post(route("purchase.product.search"), {
                    data: event.query,
                    supplier_id: auth.user.supplier_id,
                })
                .then((response) => {
                    setProduct(response.data.produts);
                });
        }, 250);
    };

    const selectedItem = (item) => {
        let inputValue = "";

        if (item.product) {
            inputValue += item.product.name + " ";

            if (item.sku) inputValue += "(" + item.sku + ")";
        }

        let list = watch("list");
        let find = list && list.find((e) => e.attribute_id == item.id);

        if (find) {
            toast.current.show({
                severity: "warn",
                summary: "Rejected",
                detail: "Your Product is already add ",
                life: 3000,
            });
        } else {
            append({
                product_name: inputValue,
                product_id: Number(item.product.id),
                attribute_id: Number(item.id),
                quantity: "",
                price: item.warehouse
                    ? invoiceType === "TP"
                        ? item.warehouse.tp_price
                        : item.warehouse.mrp_price
                    : invoiceType === "TP"
                    ? item.tp
                    : item.mrp,

                total: "",
            });
        }
    };

    const getFormErrorMessageMultiple = (name, index = null) => {
        return errors["list"] &&
            errors["list"][index] &&
            errors["list"][index][name] ? (
            <small className="p-error ">
                {errors["list"][index][name]["message"]}
            </small>
        ) : (
            ""
        );
    };
    const getFormErrorMessageSingel = (name) => {
        return errors[name] ? (
            <small className="p-error ">{errors[name]["message"]}</small>
        ) : (
            ""
        );
    };

    const DataUpdate = (data) => {
        if (data.list.length != 0) {
            axios
                .post(route("order.confirm.store", order.id), data)
                .then((res) => {
                    let order = res.data.order;
                    if (res.data.order.status == 2) {
                        setButton(false);
                    }
                    reset({
                        discount_first: order.discount_first,
                        discount_second: order.discount_second,
                        discount_second: order.discount_second,
                        grand_total: order.grand_total,
                        date: new Date(order.date),
                        sr_id: order.sr.id,
                        supplier_id: order.sr.supplier_id,
                        costomer_id: order.client_id,
                        order_id: order.id,
                        total: order.total,
                        list: order.order_details.map((e) => {
                            return {
                                attribute_id: e.attribute_id,
                                product_id: e.product_id,
                                seal_qty: Number(e?.sales_sum?.qty ?? 0),
                                quantity:
                                    Number(e.quantity) -
                                    Number(e?.sales_sum?.qty ?? 0),
                                stock_qty:
                                    e?.attribute?.warehouse?.quantity ?? 0,
                                need_qty: e.quantity,
                                discount: e.discount,
                                discount: e.discount,
                                total:
                                    e.quantity -
                                        Number(e?.sales_sum?.qty ?? 0) >
                                    0
                                        ? e.total
                                        : 0,
                                price: e.price,
                                order_details_id: e.id,
                                product_name:
                                    e.attribute.product.name +
                                    ` (${e.attribute.sku})`,
                            };
                        }),
                    });
                    toast.current.show({
                        severity: "success",
                        summary: res.data.success,
                        detail: "Data Inserted ",
                        life: 3000,
                        className: "custom-toast-class",
                    });
                });
        } else {
            toast.current.show({
                severity: "error",
                summary: "Must need a Product",
                detail: "Not update",
                life: 3000,
                className: "custom-toast-class",
            });
        }
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">Order</h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - order{" "}
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            <h6 className="text-center font-bold">{order.sr.name}</h6>
            <p className="text-center text-sm">Order</p>
            <form
                onSubmit={status == "create" ? handleSubmit(DataUpdate) : ""}
                ref={FormSubmit}
            >
                <div className="grid grid-cols-12 gap-6  px-2 mx-0 md:mx-10  mt-5">
                    <div className=" col-span-12 md:col-span-6 ">
                        <Controller
                            name="Road"
                            control={control}
                            render={({ field, fieldState }) => (
                                <span className="p-float-label">
                                    <AutoComplete
                                        dropdown
                                        value={search.road}
                                        suggestions={road}
                                        completeMethod={filterRoad}
                                        aria-label="Coustomer"
                                        itemTemplate={roadTemplateIOptionList}
                                        onChange={(e) => {
                                            if (e.value.id) {
                                                setClient(e.value.clients);
                                            }
                                            setSearchValue((old) => {
                                                return {
                                                    ...old,
                                                    road: e.value.road_name
                                                        ? e.value.road_name
                                                        : e.value,
                                                };
                                            });
                                        }}
                                        className="w-full h-11"
                                    />
                                    <label htmlFor={field.id}>
                                        {" "}
                                        {!search.road && "Search Road"}{" "}
                                    </label>
                                </span>
                            )}
                        />
                    </div>
                    <div className=" col-span-12 md:col-span-6 ">
                        <Controller
                            name="costomer_id"
                            control={control}
                            render={({ field, fieldState }) => (
                                <span className="p-float-label ">
                                    <AutoComplete
                                        dropdown
                                        value={search.client}
                                        suggestions={client}
                                        completeMethod={filterClient}
                                        aria-label="Customer"
                                        itemTemplate={clientTemplateIOptionList}
                                        onChange={(e) => {
                                            if (e.value.invoice_type) {
                                                setInvoiceType(
                                                    e.value.invoice_type
                                                );
                                                setValue(
                                                    "costomer_id",
                                                    e.value.id
                                                );
                                                setClientId(e.value.id);
                                            } else {
                                                setInvoiceType(false);
                                                setClientId(false);
                                                setValue(
                                                    "costomer_id",
                                                    e.value.id
                                                );
                                            }

                                            setSearchValue((old) => {
                                                return {
                                                    ...old,
                                                    client: e.value.name
                                                        ? e.value.name +
                                                          " (" +
                                                          e.value.number +
                                                          ")" +
                                                          " (" +
                                                          e.value.user_type +
                                                          ")"
                                                        : e.value,
                                                };
                                            });
                                        }}
                                        className="w-full h-11"
                                    />
                                    <label htmlFor={field.id}>
                                        {" "}
                                        {!search.client &&
                                            "Search Retailer/Client"}{" "}
                                    </label>
                                </span>
                            )}
                        />
                    </div>
                    <div className=" col-span-12 md:col-span-6 ">
                        <Controller
                            name="product_id"
                            control={control}
                            render={({ field, fieldState }) => (
                                <span className="p-float-label">
                                    <AutoComplete
                                        value={search.product}
                                        suggestions={product}
                                        completeMethod={filterProduct}
                                        aria-label="Product"
                                        dropdown
                                        itemTemplate={
                                            productTemplateIOptionList
                                        }
                                        onChange={(e) => {
                                            if (e.value.product) {
                                                selectedItem(e.value);
                                            }
                                            setSearchValue((old) => {
                                                return {
                                                    ...old,
                                                    product: e.value.product
                                                        ? e.value.product.name +
                                                          " (" +
                                                          e.value.sku +
                                                          ")"
                                                        : e.value,
                                                };
                                            });
                                        }}
                                        dropdownAriaLabel="Select Coustomer"
                                        className="w-full h-11"
                                    />

                                    <label htmlFor={field.name}>
                                        Search Product
                                    </label>
                                </span>
                            )}
                        />
                    </div>
                    <div className=" col-span-12 md:col-span-6 ">
                        <Controller
                            name="date"
                            control={control}
                            rules={{
                                required: "Date field is required",
                            }}
                            render={({ field, fieldState }) => (
                                <span className="p-float-label">
                                    <Calendar
                                        {...field}
                                        className=" w-full h-11"
                                    ></Calendar>

                                    <label htmlFor={field.name}>Date</label>
                                </span>
                            )}
                        />
                        {getFormErrorMessageSingel(`date`)}
                    </div>
                </div>
                <div
                    className=" grid grid-cols-12 gap-6 mt-10 mx-0 md:mx-10  "
                    ref={scroll}
                >
                    {fields.map((item, index) => {
                        return (
                            <>
                                <div className="field col-span-12 md:col-span-3">
                                    <Controller
                                        name={`list.${index}.product_name`}
                                        control={control}
                                        rules={{
                                            required:
                                                "Product field is required",
                                        }}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <InputText
                                                    readOnly
                                                    value={field.value}
                                                    {...field}
                                                    className="h-11 w-full"
                                                />
                                                <label
                                                    className="mb-5"
                                                    htmlFor={field.value}
                                                >
                                                    Item{"  "}
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `product_id`,
                                        index
                                    )}
                                </div>
                                <div className="field col-span-6 md:col-span-2">
                                    <Controller
                                        name={`list.${index}.stock_qty`}
                                        control={control}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <InputText
                                                    readOnly
                                                    type="number"
                                                    id={field.name}
                                                    value={field.value}
                                                    {...field}
                                                    className={
                                                        classNames({
                                                            "p-invalid":
                                                                fieldState.invalid,
                                                        }) +
                                                        "multiselect-custom  w-full h-11"
                                                    }
                                                />
                                                <label htmlFor="calendar">
                                                    Stock Qty
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `seal_qty`,
                                        index
                                    )}
                                </div>

                                <div className="field col-span-6 md:col-span-2">
                                    <Controller
                                        name={`list.${index}.quantity`}
                                        rules={{
                                            required: "Field is required",
                                            min: {
                                                value: 0,
                                                message: "not Valid",
                                            },

                                            validate: () => {
                                                if (
                                                    Number(
                                                        watch(
                                                            `list.${index}.stock_qty`
                                                        )
                                                    ) <
                                                    Number(
                                                        watch(
                                                            `list.${index}.quantity`
                                                        )
                                                    )
                                                ) {
                                                    return "Quantity  not valid";
                                                }
                                                // You can add more custom validations as needed
                                                // Return true if valid, otherwise return an error message string
                                                return true;
                                            },
                                        }}
                                        control={control}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <InputText
                                                    type="number"
                                                    id={field.name}
                                                    value={field.value}
                                                    onChange={(e) => {
                                                        let current =
                                                            e.target.value
                                                                .length != 0
                                                                ? e.target.value
                                                                : 0;
                                                        setValue(
                                                            `list.${index}.quantity`,
                                                            e.target.value
                                                        );

                                                        let price = watch(
                                                            `list.${index}.price`
                                                        );

                                                        current =
                                                            current * price -
                                                            (watch(
                                                                `list.${index}.discount`
                                                            ) ?? 0);

                                                        current =
                                                            current.toFixed(2);
                                                        setValue(
                                                            `list.${index}.total`,
                                                            Math.round(current)
                                                        );
                                                    }}
                                                    className={
                                                        classNames({
                                                            "p-invalid":
                                                                fieldState.invalid,
                                                        }) +
                                                        "multiselect-custom  w-full h-11"
                                                    }
                                                />
                                                <label htmlFor="calendar">
                                                    Seal Qty{" "}
                                                    <span className="text-[10px] text-green-500">
                                                        Prv SL:{" "}
                                                        {watch(
                                                            `list.${index}.seal_qty`
                                                        ) ?? 0}
                                                    </span>
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `quantity`,
                                        index
                                    )}
                                </div>
                                
                                <div className="field col-span-6 md:col-span-2">
                                    <Controller
                                        name={`list.${index}.need_qty`}
                                        readOnly
                                        control={control}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <InputText
                                                    readOnly
                                                    type="number"
                                                    id={field.name}
                                                    value={field.value}
                                                    {...field}
                                                    className={
                                                        classNames({
                                                            "p-invalid":
                                                                fieldState.invalid,
                                                        }) +
                                                        "multiselect-custom  w-full h-11"
                                                    }
                                                />
                                                <label htmlFor="calendar">
                                                    Need Qty
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `seal_qty`,
                                        index
                                    )}
                                </div>

                                <div className="field col-span-6 md:col-span-2">
                                    <Controller
                                        name={`list.${index}.price`}
                                        rules={{
                                            required: "Price Field is required",
                                            min: {
                                                value: 0,
                                                message:
                                                    "negative value not allow",
                                            },
                                        }}
                                        control={control}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label  p-inputtext-sm  ">
                                                <InputText
                                                    value={field.value}
                                                    {...field}
                                                    onChange={(e) => {
                                                        field.onChange(
                                                            e.target.value
                                                        );
                                                        let current =
                                                            e.target.value
                                                                .length != 0
                                                                ? e.target.value
                                                                : 0;

                                                        let qty = watch(
                                                            `list.${index}.quantity`
                                                        );

                                                        qty =
                                                            qty != undefined
                                                                ? qty
                                                                : 0;
                                                        current =
                                                            current * qty -
                                                            (watch(
                                                                `list.${index}.discount`
                                                            ) ?? 0);

                                                        current =
                                                            current.toFixed(2);
                                                        setValue(
                                                            `list.${index}.total`,
                                                            current
                                                        );
                                                    }}
                                                    className="h-11 w-full"
                                                />
                                                <label htmlFor="total">
                                                    Price
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `price`,
                                        index
                                    )}
                                </div>
                                <div className="field col-span-6 md:col-span-2">
                                    <Controller
                                        name={`list.${index}.discount`}
                                        control={control}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <InputText
                                                    type="number"
                                                    id={field.name}
                                                    value={field.value}
                                                    onChange={(e) => {
                                                        if (
                                                            (watch(
                                                                `list.${index}.quantity`
                                                            ) || 0) *
                                                                (watch(
                                                                    `list.${index}.price`
                                                                ) || 0) >=
                                                                e.target
                                                                    .value &&
                                                            e.target.value > 0
                                                        ) {
                                                            let current =
                                                                e.target.value
                                                                    .length != 0
                                                                    ? e.target
                                                                          .value
                                                                    : 0;
                                                            setValue(
                                                                `list.${index}.discount`,
                                                                e.target.value
                                                            );
                                                            setValue(
                                                                `list.${index}.total`,
                                                                (watch(
                                                                    `list.${index}.quantity`
                                                                ) || 0) *
                                                                    (watch(
                                                                        `list.${index}.price`
                                                                    ) || 0) -
                                                                    Number(
                                                                        e.target
                                                                            .value ||
                                                                            0
                                                                    )
                                                            );
                                                        }
                                                    }}
                                                    className={
                                                        classNames({
                                                            "p-invalid":
                                                                fieldState.invalid,
                                                        }) +
                                                        "multiselect-custom  w-full h-11"
                                                    }
                                                />
                                                <label htmlFor="calendar">
                                                    Discount
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `discount`,
                                        index
                                    )}
                                </div>

                                <div className="field col-span-6 md:col-span-2">
                                    <Controller
                                        name={`list.${index}.total`}
                                        rules={{
                                            required: "Total Field is required",
                                        }}
                                        control={control}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label  p-inputtext-sm  ">
                                                <InputText
                                                    readOnly
                                                    value={field.value}
                                                    {...field}
                                                    className="h-11 w-full"
                                                />
                                                <label htmlFor="total">
                                                    Total
                                                </label>
                                            </span>
                                        )}
                                    />
                                </div>
                                <div className="field col-span-12 md:col-span-8 flex gap-2  w-5  mb-3 ">
                                    <span className="p-float-label  p-inputtext-sm  ">
                                        {watch(`list.${index}.seal_qty`) ? (
                                            ""
                                        ) : (
                                            <Button
                                                icon="pi pi-trash"
                                                onClick={(e) => {
                                                    e.preventDefault();
                                                    remove(index);
                                                    let lists = watch("list");
                                                    reset({
                                                        date: watch("date"),

                                                        list: lists.map((e) => {
                                                            return {
                                                                product_name:
                                                                    e[
                                                                        "product_name"
                                                                    ],
                                                                product_id:
                                                                    e[
                                                                        "product_id"
                                                                    ],
                                                                attribute_id:
                                                                    e[
                                                                        "attribute_id"
                                                                    ],

                                                                quantity:
                                                                    e[
                                                                        "quantity"
                                                                    ],
                                                                discount:
                                                                    e[
                                                                        "discount"
                                                                    ],
                                                                price: e[
                                                                    "price"
                                                                ],
                                                                total: e[
                                                                    "total"
                                                                ],
                                                            };
                                                        }),
                                                    });
                                                }}
                                                className="p-button-rounded p-button-warning px-3 py-2  w-10 h-10  font-medium"
                                            />
                                        )}
                                    </span>
                                </div>
                            </>
                        );
                    })}
                </div>
                <div className="h-100 w-ful flex flex-wrap gap-2 mt-2  justify-between  px-10">
                    <div className="w-full md:w-[50%]">
                        <label htmlFor="">Note</label>
                        <Controller
                            name='note'
                            control={control}
                            render={({ field, fieldState }) => (
                                <span className="p-float-label  p-inputtext-sm  ">
                                    <InputTextarea
                                        rows={3}
                                        className="w-full"
                                        {...field}
                                    />
                                </span>
                            )}
                        />
                    </div>
                    <div className=" flex flex-col items-end gap-4 justify-end">
                        <div className="field flex gap-5 items-center">
                            <label htmlFor="total" className="text-[10px]">
                                Total value
                            </label>
                            <Controller
                                name={"total"}
                                rules={{
                                    required: "Total Field is required",
                                }}
                                control={control}
                                render={({ field, fieldState }) => (
                                    <span className="p-float-label  p-inputtext-sm  ">
                                        <InputText
                                            readOnly
                                            {...field}
                                            className="h-11 w-full"
                                        />
                                    </span>
                                )}
                            />
                        </div>
                        <div className="field flex gap-5 items-center">
                            <label htmlFor="total " className="text-[10px]">
                                Discount 1st
                            </label>
                            <Controller
                                name={"discount_first"}
                                control={control}
                                render={({ field, fieldState }) => (
                                    <span className="  p-inputtext-sm  ">
                                        <InputText
                                            {...field}
                                            type="number"
                                            max="100" // Setting the maximum value
                                            onChange={(e) => {
                                                let value = Number(
                                                    e.target.value
                                                );
                                                if (value > 100) {
                                                    value = 0; // Reset the value if greater than 100
                                                }
                                                field.onChange(value); // Update the form state with the new value
                                            }}
                                            placeholder="0"
                                            className="h-11 w-full"
                                        />
                                    </span>
                                )}
                            />
                        </div>
                        <div className="field flex gap-5 items-center">
                            <label htmlFor="total" className="text-[10px]">
                                Discount 2nd
                            </label>
                            <Controller
                                name={"discount_second"}
                                control={control}
                                render={({ field, fieldState }) => (
                                    <span className=" p-inputtext-sm  ">
                                        <InputText
                                            {...field}
                                            type="number"
                                            max="100" // Setting the maximum value
                                            onChange={(e) => {
                                                let value = Number(
                                                    e.target.value
                                                );
                                                if (value > 100) {
                                                    value = 0; // Reset the value if greater than 100
                                                }
                                                field.onChange(value); // Update the form state with the new value
                                            }}
                                            placeholder="0"
                                            className="h-11 w-full"
                                        />
                                    </span>
                                )}
                            />
                        </div>
                        <div className="field flex gap-5 items-center">
                            <label htmlFor="total" className="text-[10px]">
                                Grand Total
                            </label>
                            <Controller
                                name={"grand_total"}
                                control={control}
                                rules={{
                                    required:
                                        "The Grand total field is required",
                                    min: {
                                        value: 0,
                                        message:
                                            "The Grand total must be at least 0",
                                    },
                                }}
                                render={({ field, fieldState }) => (
                                    <span className=" p-inputtext-sm  ">
                                        <InputText
                                            readOnly
                                            {...field}
                                            className="h-11 w-full"
                                        />
                                    </span>
                                )}
                            />
                        </div>
                        {getFormErrorMessageSingel(`grand_total`)}
                    </div>
                </div>

                <div className="mt-5 px-10 flex gap-3">
                    {button && (
                        <Button
                            type="submit"
                            label="Submit"
                            className="text-[11px] w-20"
                        />
                    )}

                    <Link href={route("order-view")} className="block">
                        <Button
                            type="submit"
                            label="Back"
                            className="text-[11px] w-20 bg-red-600"
                        />
                    </Link>
                </div>
            </form>
        </AuthenticatedLayout>
    );
}
