import React, { useContext, useTransition } 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 { ColumnGroup } from "primereact/columngroup";
import { Row } from "primereact/row";
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 { convertDate } from "@/Utils/helper";
import { authUser } from "@/Components/AuthProvider";
import LocationDropdown from "@/Components/LocationDropdown";

import { ProgressSpinner } from "primereact/progressspinner";
import VirtuosoDynamicFieldGroup from "@/Components/VirtuosoDynamicFieldGroup";
function WarehousesOpening({ auth }) {
    const { permission } = useContext(authUser);
    const [warehouse, SetWarehouse] = useState([]);
    const [modelShow, setModelShow] = useState(false);
    const [warehouseList, setWarehouses] = useState([]);
    const [categoryList, SetCategoryList] = useState([]);
    const [supplierList, SetSupplierList] = useState([]);
    const [existOpening, setExistOpening] = useState(false);
    const [status, setStatus] = useState("create");

    const [search, setSearch] = useState({
        product: "",
    });
    const virtuosoRef = useRef(null);

    const [process, setProcess] = useState(false);
    const toast = useRef();
    const FormSubmit = useRef();
    // Default view
    useEffect(() => {
        axios.get(route("warehouse-opening.view")).then((response) => {
            SetWarehouse(response.data.warehouse);
            setWarehouses(response.data.warehouseList);
            SetCategoryList(response.data.categoryList);
            SetSupplierList(response.data.supplier);
        });
    }, []);
    // Form Control forme React Form Hook
    const {
        control,
        register,
        formState: { errors },
        handleSubmit,
        reset,
        watch,
        setValue,
    } = useForm({
        opening_date: "",
        warehouse_id: "",
        company_id: "",
        list: [
            {
                product_name: "",
                product_id: "",
                attribute_id: "",
                quantity: "",
                unit_price: "",
                unit_price: "",
                mrp_price: "",
                tp_price: "",
                total: 0,
            },
        ],
    });
    const { fields, append, remove } = useFieldArray({
        control,
        name: "list",
    });
    //Model Hide
    const hideModel = () => {
        setModelShow(false);
        useTransition(() => {
            reset({
                opening_date: "",
                warehouse_id: "",
                list: [],
            });
        });
    };

    // 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({
                            opening_date: "",
                            company_id: "",
                            warehouse_id: !permission.includes(
                                "opening_super_admin_access"
                            )
                                ? Number(auth.user.shop_id)
                                : "",
                            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"
                />
                {process ? (
                    <ProgressSpinner
                        style={{ width: "30px", height: "30px" }}
                        strokeWidth="3"
                        fill="var(--surface-ground)"
                        animationDuration=".5s"
                    />
                ) : (
                    <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>
        ) : (
            ""
        );
    };

    //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,
            });

            const index = list.indexOf(find);

            virtuosoRef.current?.scrollToIndex({
                index: index,
                align: "center", // 'start' | 'center' | 'end' | 'auto'
                behavior: "smooth", // optional: smooth scroll
            });
        } else {
            append({
                product_name: inputValue,
                product_id: Number(item.product.id),
                attribute_id: Number(item.id),
                quantity: "",
                unit_price: Number(item.unit_price),
                tp_price: Number(item.tp),
                mrp_price: Number(item.mrp),
                total: "",
                other: item,
                mfg_date: item.mfg_date
                    ? convertDate(new Date(item.mfg_date))
                    : convertDate(),
                exp_date: item.exp_date
                    ? convertDate(new Date(item.exp_date))
                    : convertDate(),
            });
        }
    };

    const storeWareHouse = (data) => {
        const invalidIndex = data.list.findIndex((item) => item.quantity < 1);

        if (invalidIndex !== -1) {
            toast.current.show({
                severity: "warn",
                summary: "Rejected",
                detail: `Quantity must be greater than 0 (Row ${
                    invalidIndex + 1
                })`,
                life: 3000,
            });
            return;
        }
        if (window.setting.business_id == 3) {
            let duplicate = getFirstDuplicateByKey(data.list, "batch_no");
            if (duplicate) {
                toast.current.show({
                    severity: "warn",
                    summary: "Rejected",
                    detail: `Batch No ${duplicate} duplicate Entry.`,
                    life: 3000,
                });
                return;
            }
        }

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

    function getFirstDuplicateByKey(arr, key) {
        const seen = new Set();

        for (const item of arr) {
            const val = item[key];
            if (seen.has(val)) {
                return val; // first duplicate value
            }
            seen.add(val);
        }

        return null; // no duplicates
    }

    let list = watch("list");
    // easiest Product Store array for check
    const ProductCheck = [];
    // Update Warehouse Data  Opening Stock
    const updateWarehouse = (data) => {
        const invalidIndex = data.list.findIndex((item) => item.quantity < 1);

        if (invalidIndex !== -1) {
            toast.current.show({
                severity: "warn",
                summary: "Rejected",
                detail: `Quantity must be greater than 0 (Row ${
                    invalidIndex + 1
                })`,
                life: 3000,
            });
            return;
        }

        if (window.setting.business_id == 3) {
            let duplicate = getFirstDuplicateByKey(data.list, "batch_no");
            if (duplicate) {
                toast.current.show({
                    severity: "warn",
                    summary: "Rejected",
                    detail: `Batch No ${duplicate} duplicate Entry.`,
                    life: 3000,
                });
                return;
            }
        }

        if (data.list.length != 0) {
            setProcess(true);
            axios
                .put(route("warehouse-store.update", data.warehouse_id), data)
                .then((response) => {
                    toast.current.show({
                        severity: "info",
                        summary: "Confirmed",
                        detail: response.data.success,
                        life: 3000,
                    });
                    reset({
                        opening_date: "",
                        warehouse_id: "",
                        list: [],
                    });
                    setModelShow(false);
                    SetWarehouse(response.data.warehouse);

                    setProcess(false);
                });
        } else {
            toast.current.show({
                severity: "warn",
                summary: "Rejected",
                detail: "Must  need a product",
                life: 3000,
            });
        }
    };

    // Data Delete
    const handelDelete = (e, 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-store.destroy", id))
                    .then((response) => {
                        SetWarehouse(response.data.warehouse);
                        SetSupplierList(response.data.supplier);
                        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,
                });
            },
        });
    };

    const onDelete = (e, remove, index, data, allData) => {
        e.preventDefault();

        if (!confirm("Are you sure you want to delete this item?")) {
            return;
        }

        axios
            .post(
                route("opening.attr.delete", [
                    data.other.attribute_id,
                    allData.warehouse_id,
                ])
            )
            .then((response) => {
                toast.current.show({
                    severity: "info",
                    summary: "Confirmed",
                    detail: response.data.success,
                    life: 3000,
                });

                remove(index);
            })
            .catch((error) => {
                toast.current.show({
                    severity: "warn",
                    summary: "Rejected",
                    detail: error.response?.data?.error || "Delete failed",
                    life: 3000,
                });
            });
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Warehouse Opening
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - WarehouseOpening
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            {/* View Table*/}
            <div className="card">
                <DataTable
                    className="defulattable"
                    value={warehouse}
                    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.name"
                        header="Warehouse"
                        className="text-left "
                    />

                    <Column
                        header="Action"
                        body={(rowData) => (
                            <>
                                {" "}
                                <ConfirmPopup />{" "}
                                <Button
                                    icon="pi pi-pencil"
                                    onClick={() => {
                                        setModelShow(true);
                                        setStatus("update");
                                        setExistOpening(true);
                                        reset({
                                            opening_date: new Date(
                                                rowData.date
                                            ), // Converts date string to Date object
                                            warehouse_id: Number(
                                                rowData.warehouse_id
                                            ), // Converts warehouse_id to number
                                            company_id: Number(
                                                rowData.supplier_id
                                            ), // Converts supplier_id to number
                                            list: rowData.details.map(
                                                (item) => {
                                                    // Mapping over rowData.details
                                                    return {
                                                        product_name:
                                                            item.attribute
                                                                .product.name, // Adjust according to your data
                                                        product_id: Number(
                                                            item.product_id
                                                        ),
                                                        attribute_id: Number(
                                                            item.attribute_id
                                                        ),
                                                        quantity: Number(
                                                            item.opening_stock
                                                        ),
                                                        batch_no:
                                                            item?.batch_no,
                                                        unit_price: parseFloat(
                                                            item.unit_price
                                                        ).toFixed(2),
                                                        tp_price: Number(
                                                            item.tp_price
                                                        ),
                                                        mrp_price: Number(
                                                            item.mrp_price
                                                        ),
                                                        pack_price: Number(
                                                            item.pack_price || 0
                                                        ),
                                                        pack_qty: Number(
                                                            item.pack_qty || 0
                                                        ),
                                                        mfg_date: item.mfg_date
                                                            ? new Date(
                                                                  item.mfg_date
                                                              )
                                                            : "",
                                                        exp_date: item.exp_date
                                                            ? new Date(
                                                                  item.exp_date
                                                              )
                                                            : "",
                                                        mfg_date: item.mfg_date
                                                            ? convertDate(
                                                                  new Date(
                                                                      item.mfg_date
                                                                  )
                                                              )
                                                            : convertDate(),
                                                        other: item,
                                                        exp_date: item.exp_date
                                                            ? convertDate(
                                                                  new Date(
                                                                      item.exp_date
                                                                  )
                                                              )
                                                            : convertDate(),

                                                        total: (
                                                            Number(
                                                                item.unit_price
                                                            ) *
                                                            Number(
                                                                item.opening_stock
                                                            )
                                                        ).toFixed(2),
                                                    };
                                                }
                                            ),
                                        });
                                    }}
                                    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.warehouse_id}
                                    onClick={(e) => {
                                 
                                        handelDelete(e, rowData.details[0].id);
                                    }}
                                    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="Opening Stock "
                visible={modelShow}
                style={{ width: "80vw" }}
                footer={footerContent}
                onHide={hideModel}
            >
                <form
                    onSubmit={
                        status == "create"
                            ? handleSubmit(storeWareHouse)
                            : handleSubmit(updateWarehouse)
                    }
                    className="p-fluid relative"
                    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="opening_date"
                                control={control}
                                rules={{ required: "Date is required." }}
                                render={({ field, fieldState }) => (
                                    <Calendar
                                        inputId={field.name}
                                        value={field.value}
                                        onChange={(e) => {
                                            // Convert to UTC date at midnight to prevent timezone shift
                                            const utcDate = new Date(
                                                Date.UTC(
                                                    e.value.getFullYear(),
                                                    e.value.getMonth(),
                                                    e.value.getDate(),
                                                    0,
                                                    0,
                                                    0
                                                )
                                            );

                                            field.onChange(utcDate);
                                        }}
                                        className="w-full h-11"
                                    />
                                )}
                            />
                            <label htmlFor="name">Opening Stock Date</label>
                        </span>
                        {getFormErrorMessageSingle("opening_date")}
                    </div>

                    <>
                        <div className="col-span-4">
                            <span className="p-float-label">
                                <Controller
                                    name="warehouse_id"
                                    control={control}
                                    rules={{
                                        required: "Warehouse Field is required",
                                    }}
                                    render={({ field, fieldState }) => (
                                        // <span className="p-float-label">
                                        //     <Dropdown
                                        //         options={warehouseList}
                                        //         id={field.name}
                                        //         value={field.value}

                                        //         optionLabel="name"
                                        //         optionValue="id"
                                        //         className={
                                        //             classNames({
                                        //                 "p-invalid":
                                        //                     fieldState.invalid,
                                        //             }) +
                                        //             "multiselect-custom  w-full h-11"
                                        //         }
                                        //     />
                                        //     <label htmlFor={field.name}>
                                        //         Select Warehouse/Shop
                                        //     </label>
                                        // </span>

                                        <LocationDropdown
                                            warehouses={warehouseList}
                                            field={field}
                                            disabled={
                                                !permission.includes(
                                                    "opening_super_admin_access"
                                                )
                                                    ? true
                                                    : status === "update"
                                            }
                                            onChange={(e) => {
                                                let data = warehouse.find(
                                                    (data) =>
                                                        data.warehouse_id ==
                                                        e.value
                                                );

                                                if (data) {
                                                    toast.current.show({
                                                        severity: "warn",

                                                        detail: "The warehouse opening is complete. To add products, simply edit and manage them",
                                                        life: 3000,
                                                    });
                                                } else {
                                                    field.onChange(e.value);
                                                }
                                            }}
                                        />
                                    )}
                                />
                            </span>
                            {getFormErrorMessageSingle("warehouse_id")}
                        </div>
                        <div className="field col-span-12 md:col-span-12 mx-[25%] mt-5">
                            <Controller
                                name=""
                                control={control}
                                render={({ field, fieldState }) => (
                                    <ProductDropdown
                                        field={field}
                                        selectedItem={selectedItem}
                                    />
                                )}
                            />
                        </div>
                    </>
                </div>

               <VirtuosoDynamicFieldGroup
                 ref={virtuosoRef}
                 fields={fields}
                readOnlyFields={["product_name", "total"]}
                    deleteColumn={5}
                    mode="opening_stock"
                    control={control}
                    watch={watch}
                    setValue={setValue}
                    remove={remove}
                    onDelete={onDelete}
                  errors={errors}
               
               
               />


              
                <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 className="col-span-4 text-right mr-3">
                        {list && (
                            <b>
                                Total Unit Price:{" "}
                                {list
                                    .reduce(
                                        (acc, item) => acc + Number(item.total),
                                        0
                                    )
                                    .toFixed(2)}
                            </b>
                        )}
                    </div>
                </div>
            </Dialog>
            {/* Create Model End*/}
        </AuthenticatedLayout>
    );
}

export default WarehousesOpening;
