import React, { useContext } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { useForm, Controller, useFieldArray } from "react-hook-form";
import { Dropdown } from "primereact/dropdown";
import { InputText } from "primereact/inputtext";
import { classNames } from "primereact/utils";
import { useEffect } from "react";
import axios from "axios";
import { Button } from "primereact/button";
import { useState } from "react";
import { Toast } from "primereact/toast";
import { useRef } from "react";
import { ConfirmDialog, confirmDialog } from "primereact/confirmdialog";
import { Link, useForm as nagative } from "@inertiajs/react";
import { authUser } from "@/Components/AuthProvider";

function CheckMaker({ auth, old_shipment }) {
    const { permission } = useContext(authUser);
    const [purhchase, SetPurchase] = useState([]);
    const [requsituion, SetRequsituion] = useState([]);
    const [product, SetProduct] = useState([]);
    const [unit, SetUnit] = useState([]);
    const [category, SetCaegory] = useState([]);
    const [Warehouse, SetWarehouse] = useState([]);
    const [shop, setShop] = useState([]);
    const [id, setId] = useState();
    const toast = useRef();
    const { get } = nagative();


    // From Controll
    const {
        control,
        register,
        formState: { errors },
        handleSubmit,
        reset,
        watch,
        setValue,
    } = useForm({
        invoice_no: "",
        warehouse_id: "",
        shop_id: "",
        list: [
            {
                product_id: "",
                quantity: "",
                stock: "",
                send_qty: "",
            },
        ],
    });
    const { fields, remove } = useFieldArray({
        control,
        name: "list",
    });
    useEffect(() => {
        axios.get(route("product-shifting.view")).then((response) => {
      

            SetRequsituion(response.data.requsition);
            SetWarehouse(response.data.warehouse);
            setShop(response.data.shop);

            if (old_shipment != undefined) {
                setId(old_shipment.shiping.id);
                SetRequsituion([old_shipment.shiping.requsition]);

                let warehouse_master = response.data.warehouse.find(
                    (item) => item.id == old_shipment.shiping.warehouse_id
                );
                let stock = [];
                warehouse_master.warehouse_details.forEach((element) => {
                    stock[element.product_id] = element.quantity;
                });
                reset({
                    invoice_no: Number(old_shipment.shiping.reqsition_id),
                    warehouse_id: Number(old_shipment.shiping.warehouse_id),
                    shop_id: Number(old_shipment.shiping.shop_id),
                    list: old_shipment.shiping.shipping_details.map((e) => {
                        return {
                            product_id: Number(e.product_id),
                            product_name: e.attribute.product.name,
                            quantity:
                                old_shipment.shiping.requsition.requsition_detailes.find(
                                    (product) =>
                                        product.product_id == e.product_id
                                ).quantity,
                            stock:
                                e.product_id in stock ? stock[e.product_id] : 0,
                            send_qty: e.sending_qty,
                            attribute_id: e.attribute_id,
                            attribute: e.attribute,
                            batch_no: e.batch_no,
                        };
                    }),
                });
            } else {
                SetRequsituion(response.data.requisition);

                setShop(response.data.shop);
            }
        });
    }, []);

    // set Error Message Multiple field
    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>
        ) : (
            ""
        );
    };
    // set Error Message Multiple single Field
    const getFormErrorMessageSingel = (name) => {
        return errors[name] ? (
            <small className="p-error ">{errors[name]["message"]}</small>
        ) : (
            ""
        );
    };
    // Data store on Database
    const StoreData = (data) => {
        if (data.list.length != 0) {
            axios
                .post(route("product-shifting.store", data.invoice_no), data)
                .then((response) => {
                    toast.current.show({
                        severity: "info",
                        summary: "Confirmed",
                        detail: response.data.success,
                        life: 3000,
                    });
                    SetRequsituion(response.data.requsition);
                    reset({
                        invoice_no: "",
                        warehouse_id: "",
                        shop_id: "",
                        list: [],
                    });
                });
        } else {
            toast.current.show({
                severity: "error",
                summary: "Need List",
                detail: "Must need mimimum 1",
                life: 3000,
            });
        }
    };
    const GetPurchaseDetiles = (id) => {
        const req = requsituion.find((data) => data.id == id);


        reset({
            invoice_no: watch("invoice_no"),
            warehouse_id: watch("warehouse_id"),
            shop_id: Number(req.shop_id),
            warehouse_id: Number(req.location_id),

            list: req.requsition_detailes.map((list, key) => {
                return {
                    product_id: Number(list.product_id),
                    attribute_id: list.attribute.id,
                    product_name: list.attribute.product.name,
                    quantity: list.quantity,
                    stock: "",
                    send_qty: 0,
                    attribute: list.attribute,
                };
            }),
        });

        if (req.location_id) {
            GetStockQty(req.location_id);
        }
    };

    // Warehouse Wise Stock Qty }
    const GetStockQty = (id) => {
        let warehouse_master = Warehouse.find((item) => item.id == id);
        let stock = [];
        warehouse_master.warehouse_details.forEach((element) => {
            stock[element.attribute_id] = element.quantity;
        });

        let seleted_id = watch("invoice_no");
        let array_list = watch("list");
        reset({
            invoice_no: watch("invoice_no"),
            warehouse_id: watch("warehouse_id"),
            shop_id: watch("shop_id"),
            list: array_list.map((list, key) => {
                return {
                    stock: Number(
                        list.attribute_id in stock
                            ? stock[list.attribute_id]
                            : 0
                    ), // Use the actual value from your form
                    product_id: Number(list.product_id),
                    attribute_id: list.attribute_id,
                    product_name: list.product_name,
                    quantity: list.quantity,
                    attribute: list.attribute,
                    send_qty: 0,
                    batch_no: list.batch_no,
                };
            }),
        });
    };

    const handelEdit = (data) => {
        axios
            .put(route("shipment-product.update", id), data)
            .then((response) => {
                toast.current.show({
                    severity: "info",
                    summary: "Confirmed",
                    detail: response.data.success,
                    life: 3000,
                });
                get(route("shipment-product.edit", id));
            });
    };
    const productTemplateIOptionList = (option) => {
        const brand = option?.attribute?.brand?.name;
        const color = option?.attribute?.color?.name;
        const size = option?.attribute?.size?.name;
        const model = option?.attribute?.model?.name;

        return (
            <div className="country-item">
                <div>
                    Product
                    {option.sku ? "(" : null}
                    {option.sku}
                    {option.sku ? ")" : null} {brand ? "Brand:" + brand : ""}{" "}
                    {color ? "Color:" + color : ""} {size ? "Size:" + size : ""}{" "}
                    {model ? "Model:" + model : ""}
                </div>
            </div>
        );
    };
    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium "> Shipping</h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - Product Shipping
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            <ConfirmDialog />
            <form
                onSubmit={
                    old_shipment == undefined
                        ? handleSubmit(StoreData)
                        : handleSubmit(handelEdit)
                }
            >
                {/* Single Field */}
                <div className="flex justify-center gap-5 my-6">
                    <div className="field">
                        <span className="p-float-label">
                            <Controller
                                name="invoice_no"
                                rules={{
                                    required: "Invoice no field is required",
                                }}
                                control={control}
                                render={({ field }) => (
                                    <Dropdown
                                        options={requsituion}
                                        value={watch("invoice_no")}
                                        onChange={(e) => {
                                            setValue("invoice_no", e.value);
                                            GetPurchaseDetiles(e.value);
                                        }}
                                        optionLabel="invoice_no"
                                        optionValue="id"
                                        placeholder="Select Maker list"
                                        filter
                                        className="multiselect-custom w-80  h-11"
                                    />
                                )}
                            />
                            <label htmlFor="invoice_no">Select Invoice</label>
                        </span>
                        {getFormErrorMessageSingel("invoice_no")}
                    </div>
                    <div className="field">
                        <span className="p-float-label">
                            <Controller
                                name="shop_id"
                                rules={{
                                    required: "Shop  field is required",
                                }}
                                control={control}
                                render={({ field }) => (
                                    <Dropdown
                                        options={shop}
                                        {...field}
                                        optionLabel="name"
                                        optionValue="id"
                                        placeholder="Select Maker list"
                                        filter
                                        disabled
                                        className="multiselect-custom w-80  h-11"
                                    />
                                )}
                            />
                            <label htmlFor="shop_id">Selected Shop</label>
                        </span>
                        {getFormErrorMessageSingel("shop_id")}
                    </div>
                    <div className="field">
                        <span className="p-float-label">
                            <Controller
                                name="warehouse_id"
                                rules={{
                                    required: " Warehouse field is required",
                                }}
                                control={control}
                                render={({ field }) => (
                                    <Dropdown
                                        options={Warehouse}
                                        value={field.value}
                                        onChange={(e) => {
                                            setValue("warehouse_id", e.value);
                                            GetStockQty(e.value);
                                        }}
                                        optionLabel="name"
                                        optionValue="id"
                                        placeholder="Select Maker list"
                                        filter
                                        showClear
                                        disabled={
                                            !permission.includes(
                                                "transfer_super_admin_access"
                                            )
                                        }
                                        className="multiselect-custom w-80  h-11"
                                    />
                                )}
                            />
                            <label htmlFor="warehouse_id">
                                Select warehouse
                            </label>
                        </span>
                        {getFormErrorMessageSingel("warehouse_id")}
                    </div>
                </div>
                {/* Multiple Filed */}
                <div className="grid grid-cols-12 justify-items-stretch  gap-5  my-10 px-2">
                    {fields.map((item, index) => {
                     
                        
                        return (
                            <>
                                <div className="field lg:col-span-3 md:col-span-2 mt-2 w-full">
                                    <Controller
                                        name={`list.${index}.product_name`}
                                        control={control}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <InputText
                                                    value={item.product_name}
                                                    className={
                                                        classNames({
                                                            "p-invalid":
                                                                fieldState.invalid,
                                                        }) + " w-full h-11"
                                                    }
                                                />
                                                <label htmlFor={field.name}>
                                                    <span>
                                                        {productTemplateIOptionList(
                                                            item
                                                        )}
                                                    </span>
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `product_name`,
                                        index
                                    )}
                                </div>
                                {window.setting.business_id == 3 &&               
                                <div className="field lg:col-span-2 md:col-span-2 mt-2 w-full">
                                    <Controller
                                        name={`list.${index}.batch_no`}
                                        control={control}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <Dropdown
                                                    value={field.value}
                                                    options={item?.attribute?.batch}
                                                    onChange={(e)=>{
                                                        field.onChange(e.value)
                                                        let item2= item?.attribute?.batch.find((batch) => batch.batch_no == e.value);
                                         
                                                        
                                                        setValue(
                                                            `list.${index}.stock`,
                                                            item2?.quantity
                                                        );
                                                    }}
                                                    optionLabel="batch_no"
                                                    optionValue="batch_no"
                                                    placeholder="Select a one"
                                                    className="w-full md:w-14rem"
                                                />
                                                <label
                                                    htmlFor={field.name}
                                                >
                                                   Batch No 
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `batch_no`,
                                        index
                                    )}
                                </div> }
                  
                                <div className="field lg:col-span-2 md:col-span-3 mt-2">
                                    <Controller
                                        name={`list.${index}.stock`}
                                        control={control}
                                        rules={{
                                            required: " required",
                                            min: {
                                                value: 0,
                                                message:
                                                    "nagative value not allow",
                                            },
                                        }}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <InputText
                                                    type="number"
                                                    {...field}
                                                    className={
                                                        classNames({
                                                            "p-invalid":
                                                                fieldState.invalid,
                                                        }) +
                                                        "multiselect-custom w-full h-11"
                                                    }
                                                    readOnly
                                                />
                                                <label htmlFor="calendar">
                                                    Stock
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `stock`,
                                        index
                                    )}
                                </div>
                                <div className="field lg:col-span-2 md:col-span-2 mt-2">
                                    <Controller
                                        name={`list.${index}.quantity`}
                                        rules={{
                                            required: "Required",
                                            min: {
                                                value: 0,
                                                message: "not Valid",
                                            },
                                        }}
                                        control={control}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <InputText
                                                    type="number"
                                                    {...field}
                                                    className={
                                                        classNames({
                                                            "p-invalid":
                                                                fieldState.invalid,
                                                        }) +
                                                        "multiselect-custom  w-full h-11"
                                                    }
                                                    readOnly
                                                />
                                                <label htmlFor="calendar">
                                                    Qty
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `quantity`,
                                        index
                                    )}
                                </div>
                                <div className="field lg:col-span-2 md:col-span-3 mt-2">
                                    <Controller
                                        name={`list.${index}.send_qty`}
                                        control={control}
                                        rules={{
                                            required: "Qty Field is required",
                                            min: {
                                                value: 1,
                                                message: "1 qty minimum",
                                            },
                                            max: {
                                                value: item.stock,
                                                message: "Stock is Limited",
                                            },
                                        }}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <InputText
                                                    type="number"
                                                    {...field}
                                                    className={
                                                        classNames({
                                                            "p-invalid":
                                                                fieldState.invalid,
                                                        }) +
                                                        "multiselect-custom  w-full h-11"
                                                    }
                                                />
                                                <label htmlFor="calendar">
                                                    Sending Qty
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `send_qty`,
                                        index
                                    )}
                                </div>

                                <div className="field lg:col-span-1 md:col-span-2 flex gap-2  w-5  mb-3 ">
                                    <span className="p-float-label  p-inputtext-sm  ">
                                        <Button
                                            icon="pi pi-trash"
                                            onClick={(e) => {
                                                e.preventDefault();
                                                remove(index);
                                                let lists = watch("list");
                                                reset({
                                                    invoice_no:
                                                        watch("invoice_no"),
                                                    warehouse_id:
                                                        watch("warehouse_id"),
                                                    shop_id: watch("shop_id"),
                                                    list: lists.map(
                                                        (list, key) => {
                                                            return {
                                                                product_id:
                                                                    list.product_id,
                                                                attribute_id:
                                                                    list.attribute_id,
                                                                quantity:
                                                                    list.quantity,
                                                                stock: list.stock, // Use the actual value from your form
                                                                send_qty:
                                                                    list.send_qty, // Use the actual value from your form

                                                                total: list.total,
                                                            };
                                                        }
                                                    ),
                                                });
                                            }}
                                            className="p-button-rounded p-button-warning px-3 py-2  w-10 h-10  font-medium"
                                        />
                                    </span>
                                </div>
                            </>
                        );
                    })}
                </div>
                <div className="flex justify-center -mt-4">
                    <Button label="Transfer" className="text-xs " />
                </div>
            </form>
        </AuthenticatedLayout>
    );
}

export default CheckMaker;
