import React from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Column } from "primereact/column";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import { DataTable } from "primereact/datatable";
import { useEffect } from "react";
import axios from "axios";
import { useState } from "react";

import { Dropdown } from "primereact/dropdown";
import { Dialog } from "primereact/dialog";
import { useForm, Controller, useFieldArray } from "react-hook-form";
import { classNames } from "primereact/utils";
import { useRef } from "react";
import { Calendar } from "primereact/calendar";
import { Toast } from "primereact/toast";
import { AutoComplete } from "primereact/autocomplete";
import { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import { InputMask } from "primereact/inputmask";
import ProductDropdown from "@/Components/ProductDropdown";
import DynamicFieldGroup from "@/Components/DynamicFieldGroup";
import LocationDropdown from "@/Components/LocationDropdown";
function WarehouseTransfer({ auth, warehouse_transfer }) {
    const [warehouseTransfer, SetWarehouseTransfer] =
        useState(warehouse_transfer);
    const [modelShow, setModelShow] = useState(false);
    const [warehouseList, setWarehouses] = useState([]);
    const [categoryList, SetCategoryList] = useState([]);
    const [supplierList, SetSupplierList] = useState([]);
    const [existOpening, setExistOpening] = useState(false);
    const [id, setId] = useState(null);
    const [status, setStatus] = useState("create");
    const [search, setSearch] = useState({
        product: "",
    });
    const [product, setPriceProduct] = useState([]);

    const scroll = useRef();
    const toast = useRef();
    const FormSubmit = useRef();
    // Default view
    useEffect(() => {
        axios.get(route("warehouse-opening.view")).then((response) => {
            setWarehouses(response.data.warehouseList);
        });
    }, []);
    // Form Control forme React Form Hook
    const {
        control,
        register,
        formState: { errors },
        handleSubmit,
        reset,
        watch,
        setValue,
    } = useForm({
        from_warehouse_id: "",
        to_warehouse_id: "",
        list: [
            {
                product_name: "",
                product_id: "",
                attribute_id: "",
                quantity: "",
            },
        ],
    });
    const { fields, append, remove } = useFieldArray({
        control,
        name: "list",
    });
    //Model Hide
    const hideModel = () => {
        setModelShow(false);
        reset({
            warehouse_id: "",
            list: [
                {
                    product_id: "",
                    quantity: "",
                    price: "",
                    unit_id: "",
                    category_id: "",
                    total: 0,
                },
            ],
        });
    };

    // Table Header Component
    const renderHeader = () => {
        return (
            <div className="w-100% flex justify-between	">
                <Button
                    type="button"
                    icon={<span className="pi pi-plus text-sm pr-1" />}
                    label="Add"
                    onClick={() => {
                        setStatus("create");
                        reset({
                            list: [],
                        });
                        setModelShow(true);
                    }}
                    className="p-button-success h-[41px]  text-[14px] "
                />
            </div>
        );
    };
    const header = renderHeader();

    {
        /* Model Footer Content  */
    }
    const footerContent = (
        <div className="grid  grid-cols-12 ">
            <div className="col-span-12">
                <Button
                    label="Cancel"
                    icon="pi pi-times"
                    onClick={hideModel}
                    className="p-button-text w-13 text-sm"
                />
                {
                    <Button
                        label="Save"
                        type="submit"
                        onClick={() => {
                            FormSubmit.current.dispatchEvent(
                                new Event("submit", { bubbles: true })
                            );
                        }}
                        icon="pi pi-check"
                        className="p-button-text w-13 text-sm"
                    />
                }
            </div>
        </div>
    );
    {
        /* Model Footer Content  */
    }

    // 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 getFormErrorMessageSingle = (name) => {
        return errors[name] ? (
            <small className="p-error ">{errors[name]["message"]}</small>
        ) : (
            ""
        );
    };

    const productTemplateIOptionList = (option) => {
        return (
            <div className="country-item">
                <div>
                    {option.product.name} {option.sku ? "(" : null}
                    {option.sku}
                    {option.sku ? ")" : null}
                </div>
            </div>
        );
    };

    const filterProduct = (event) => {
        setTimeout(() => {
            axios
                .post(route("purchase.product.search"), {
                    data: event.query,
                    form_warehouse_id: watch("from_warehouse_id"),
                })
                .then((response) => {
                    setPriceProduct(response.data.produts);
                });
        }, 250);
    };

    //Set Selected Product
    const selectedItem = (item) => {
        setSearch((old) => {
            return {
                product: "",
            };
        });
        // Assuming "inputField" is the reference to your input field
        let inputValue = "";

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

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

        let list = watch("list");
        let find = list && list.find((e) => e.attribute_id == item.id);
        find = window.setting.business_id == 3 ? false : find;
        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: "",
                warehouse_quantity: Number(item?.warehouse?.quantity ?? 0),
                other: item,
            });
        }
    };

    const storeWareHouse = (data) => {
        if (data.list.length != 0) {
            axios
                .post(route("warehouse-transfer.store"), data)
                .then((response) => {
                    toast.current.show({
                        severity: "info",
                        summary: "Confirmed",
                        detail: response.data.success,
                        life: 3000,
                    });
                    reset({
                        warehouse_id: "",
                        list: [],
                    });
                    setModelShow(false);
                    SetWarehouseTransfer(response.data.warehouse_transfer);
                    SetSupplierList(response.data.supplier);
                });
        } else {
            toast.current.show({
                severity: "warn",
                summary: "Rejected",
                detail: "Must  need a product",
                life: 3000,
            });
        }
    };

    let list = watch("list");
    // easiest Product Store array for check
    const ProductCheck = [];

    const handelEdit = (id) => {
        axios.get(route("warehouse-transfer.edit", id)).then((response) => {
            reset({
                date: new Date(response.data.date),
                from_warehouse_id: Number(response.data.from_warehouse_id),
                to_warehouse_id: Number(response.data.to_warehouse_id),
                list: response.data.transfer_details.map((item) => {
                    return {
                        product_name:
                            item.product_attribute.product.name +
                            `(${item.product_attribute.sku})`,
                        product_id: Number(item.product_attribute.product_id),
                        attribute_id: Number(item.attribute_id),
                        warehouse_quantity:
                            item?.product_attribute?.batch.find(
                                (e) => e.batch_no == item.batch_no
                            )?.quantity ??
                            Number(
                                item?.product_attribute?.warehouse?.quantity ??
                                    0
                            ),
                        quantity: Number(item.qty),
                        other: item,
                        prv_quantity: Number(item.qty),
                        batch_no: item.batch_no,
                    };
                }),
            });
        });
    };
    // Update Warehouse Data  Opening Stock
    const updateWarehouse = (data) => {
        if (data.list.length != 0) {
            axios
                .put(route("warehouse-transfer.update", id), data)
                .then((response) => {
                    toast.current.show({
                        severity: "info",
                        summary: "Confirmed",
                        detail: response.data.success,
                        life: 3000,
                    });
                    reset({
                        warehouse_id: "",
                        list: [],
                    });
                    setModelShow(false);
                    SetWarehouseTransfer(response.data.warehouse_transfer);
                    SetSupplierList(response.data.supplier);
                });
        } else {
            toast.current.show({
                severity: "warn",
                summary: "Rejected",
                detail: "Must  need a product",
                life: 3000,
            });
        }
    };

    // Data Delete
    const handelDelete = (e) => {
        const id = e.currentTarget.getAttribute("data-id");

        confirmPopup({
            target: e.currentTarget,
            message: "Do you want to delete this record?",
            icon: "pi pi-info-circle",
            acceptClassName: "p-button-danger",
            accept() {
                axios
                    .delete(route("warehouse-transfer.destroy", id))
                    .then((response) => {
                        SetWarehouseTransfer(response.data.warehouse_transfer);

                        toast.current.show({
                            severity: "info",
                            summary: "Confirmed",
                            detail: response.data.success,
                            life: 3000,
                        });
                    })
                    .catch((error) => {
                        toast.current.show({
                            severity: "warn",
                            summary: "Rejected",
                            detail: error.response.data.error,
                            life: 3000,
                        });
                    });
            },
            reject() {
                toast.current.show({
                    severity: "warn",
                    summary: "Rejected",
                    detail: "You have rejected",
                    life: 3000,
                });
            },
        });
    };
    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Warehouse Transfer
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - WarehouseTransfer
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            {/* View Table*/}
            <div className="card">
                <DataTable
                    className="defulattable"
                    value={warehouseTransfer}
                    paginator
                    showGridlines
                    rows={10}
                    dataKey="id"
                    header={header}
                    emptyMessage="No warehouse found."
                >
                    <Column
                        body={(e) =>
                            new Date(e.date).toLocaleDateString("en-us")
                        }
                        header="Date"
                        className="text-left "
                    />
                    <Column
                        field="warehouse_form.name"
                        header="Warehouse Form"
                        className="text-left "
                    />
                    <Column
                        field="warehouse_to.name"
                        header="Warehouse To"
                        className="text-left "
                    />

                    <Column
                        header="Action"
                        body={(rowData) => (
                            <>
                                {" "}
                                <ConfirmPopup />{" "}
                                <Button
                                    icon="pi pi-pencil"
                                    onClick={() => {
                                        setModelShow(true);
                                        setStatus("update");
                                        setExistOpening(true);

                                        handelEdit(rowData.id);

                                        setId(rowData.id);
                                    }}
                                    className="p-button-rounded p-button-success mr-2 px-3 py-2  w-10 h-10 font-medium"
                                />
                                <Button
                                    icon="pi pi-trash"
                                    data-id={rowData.id}
                                    onClick={handelDelete}
                                    className="p-button-rounded p-button-warning px-3 py-2  w-10 h-10  font-medium"
                                />
                            </>
                        )}
                        dataType="boolean"
                        bodyClassName="text-center"
                    />
                </DataTable>
            </div>
            {/* View Table End*/}

            {/* Create Model*/}
            <Dialog
                header={
                    status == "update" ? " Update  Transfer " : " Add Transfer "
                }
                visible={modelShow}
                style={{ width: "80vw" }}
                footer={footerContent}
                onHide={hideModel}
            >
                <form
                    onSubmit={
                        status == "create"
                            ? handleSubmit(storeWareHouse)
                            : handleSubmit(updateWarehouse)
                    }
                    className="p-fluid"
                    method="POST"
                    ref={FormSubmit}
                ></form>
                <div className="grid grid-cols-12 gap-5 mt-5">
                    <div className="col-span-4">
                        <span className="p-float-label">
                            <Controller
                                name="date"
                                control={control}
                                rules={{ required: "Date is required." }}
                                render={({ field, fieldState }) => (
                                    <Calendar
                                        {...field}
                                        className="w-full h-11"
                                    />
                                )}
                            />
                            <label htmlFor="name"> Date</label>
                        </span>
                        {getFormErrorMessageSingle("date")}
                    </div>

                    <>
                        <div className="col-span-4">
                            <span className="p-float-label">
                                <Controller
                                    name="from_warehouse_id"
                                    control={control}
                                    rules={{
                                        required:
                                            "Warehouse Sender is required",
                                    }}
                                    render={({ field, fieldState }) => (
                                        // <span className="p-float-label">
                                        //     <Dropdown
                                        //         options={warehouseList}
                                        //         id={field.name}
                                        //         value={field.value}
                                        //         onChange={(e) => {
                                        //             reset({
                                        //                 date: watch("date"),
                                        //                 to_warehouse_id:
                                        //                     watch(
                                        //                         "to_warehouse_id"
                                        //                     ),
                                        //                 from_warehouse_id:
                                        //                     e.value,
                                        //                 list: [],
                                        //             });
                                        //         }}
                                        //         disabled={
                                        //             status == "update" ?? false
                                        //         }
                                        //         optionLabel="name"
                                        //         optionValue="id"
                                        //         className={
                                        //             classNames({
                                        //                 "p-invalid":
                                        //                     fieldState.invalid,
                                        //             }) +
                                        //             "multiselect-custom  w-full h-11"
                                        //         }
                                        //     />
                                        //     <label htmlFor={field.name}>
                                        //         Warehouse Sender
                                        //     </label>
                                        // </span>
                                        <LocationDropdown
                                            warehouses={warehouseList}
                                            field={field}
                                            onChange={(e) => {
                                                reset({
                                                    date: watch("date"),
                                                    to_warehouse_id:
                                                        watch(
                                                            "to_warehouse_id"
                                                        ),
                                                    from_warehouse_id: e.value,
                                                    list: [],
                                                });
                                            }}
                                            disabled={
                                                status == "update" ?? false
                                            }
                                            name="Warehouse/Shop Sender"
                                        />
                                    )}
                                />
                            </span>
                            {getFormErrorMessageSingle("from_warehouse_id")}
                        </div>
                        <div className="col-span-4">
                            <span className="p-float-label">
                                <Controller
                                    name="to_warehouse_id"
                                    control={control}
                                    rules={{
                                        required:
                                            "Warehouse Receiver is required",
                                    }}
                                    render={({ field, fieldState }) => (
                                        <LocationDropdown
                                            warehouses={warehouseList}
                                            field={field}
                                            disabled={
                                                status == "update" ?? false
                                            }
                                            onChange={(e) => {
                                                field.onChange(e.value);
                                            }}
                                            name="Warehouse/Shop Receiver"
                                        />
                                    )}
                                />
                                {getFormErrorMessageSingle("to_warehouse_id")}
                            </span>
                        </div>
                        <div className="field col-span-12 md:col-span-12 mx-[25%] mt-5">
                            <Controller
                                name="product_id"
                                control={control}
                                render={({ field, fieldState }) => (
                                    <ProductDropdown
                                        field={field}
                                        filterColumn={{
                                            form_warehouse_id:
                                                watch("from_warehouse_id"),
                                        }}
                                        selectedItem={selectedItem}
                                    />
                                )}
                            />
                        </div>
                    </>
                </div>
                <div className="grid grid-cols-12 gap-6 mt-8" ref={scroll}>
                    {fields.map((item, index) => {
                        {
                            ProductCheck.push(
                                watch(`list.${index}.product_id`)
                            );
                        }
                        return (
                            <DynamicFieldGroup
                                key={item.id}
                                control={control}
                                watch={watch}
                                setValue={setValue}
                                remove={remove}
                                index={index}
                                getFormErrorMessageMultiple={
                                    getFormErrorMessageMultiple
                                }
                                mode="transfer"
                                readOnlyFields={["product_name"]}
                            />
                        );
                    })}
                </div>
                <hr />
                <div className="grid grid-cols-12 ">
                    <div className="col-span-6 text-right mr-3">
                        {list && (
                            <b>
                                Total QTY:{" "}
                                {list.reduce(
                                    (acc, item) => acc + Number(item.quantity),
                                    0
                                )}
                            </b>
                        )}
                    </div>
                </div>
            </Dialog>
            {/* Create Model End*/}
        </AuthenticatedLayout>
    );
}

export default WarehouseTransfer;
