import React, { useState, useEffect, useRef, useContext } from "react";
import { Column } from "primereact/column";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import { Dialog } from "primereact/dialog";
import { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import { classNames } from "primereact/utils";
import { useForm, Controller, useFieldArray } from "react-hook-form";
import { Calendar } from "primereact/calendar";
import axios from "axios";
import { Toast } from "primereact/toast";
import { Dropdown } from "primereact/dropdown";
import { authUser } from "@/Components/AuthProvider";
import ProductDropdown from "@/Components/ProductDropdown";
import DynamicFieldGroup from "@/Components/DynamicFieldGroup";
import ServerSideDataTable from "@/Components/ServerSideDataTable";


function StockAdjustment({ auth }) {
    const { permission, warehouseList } = useContext(authUser);
    const [status, setStatus] = useState("create");
    const [visible, setVisible] = useState(false);
    const scroll = useRef(null);
    const FormSubmit = useRef(null);
    const toast = useRef(null);

    const [reference_no, setReference_no] = useState();
    const [id, setId] = useState();
    const [refreshTrigger, setRefreshTrigger] = useState(0);

    const {
        control,
        handleSubmit,
        formState: { errors },
        setValue,
        watch,
        reset,
    } = useForm({
        reference_no: "",
        adjustment_date: "",
        location_id: "",
        remark: "",
        list: [],
    });

    const { fields, append, remove } = useFieldArray({
        control,
        name: "list",
    });

    // Fetch reference number on component mount
    useEffect(() => {
        axios.get(route("stock-adjustment.view"), {
            params: { page: 1, perPage: 1 }
        }).then((response) => {
            setReference_no(response.data.reference);
            setValue("reference_no", response.data.reference);
        });

        !permission.includes("adjustment_super_admin_access")
            ? setValue("location_id", Number(auth.user.shop_id))
            : "";
    }, []);

    // Refresh data table
    const refreshData = () => {
        setRefreshTrigger(prev => prev + 1);
    };

    const TableHeader = ({ search, setSearch }) => {
        return (
          <>
                {permission.includes("adjustment_create") && (
                    <Button
                        type="button"
                        icon={<span className="pi pi-plus text-sm pr-1" />}
                        label="Add"
                        onClick={() => {
                            setStatus("create");
                            formReset();
                            setVisible(true);
                        }}
                        className="p-button-success h-[41px] text-[14px]"
                    />
                )}
                <span className="p-input-icon-left h-10">
                    <i className="pi pi-search" />
                    <InputText 
                        className="h-[41px] w-48" 
                        placeholder="Search" 
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                    />
                </span>
           </>
        );
    };

    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>
        ) : (
            ""
        );
    };
    // form Reset
    const formReset = () => {
        // Reset form immediately with default values
        const defaultLocationId = !permission.includes("adjustment_super_admin_access")
            ? Number(auth.user.shop_id)
            : "";
        
        // Set current date
        const currentDate = new Date();
        const utcDate = new Date(
            Date.UTC(
                currentDate.getFullYear(),
                currentDate.getMonth(),
                currentDate.getDate(),
                0,
                0,
                0
            )
        );
        
        reset({
            reference_no: reference_no || "",
            adjustment_date: utcDate,
            location_id: defaultLocationId,
            remark: "",
            list: [],
        });
        
        // Fetch fresh reference number and update
        axios.get(route("stock-adjustment.view"), {
            params: { page: 1, perPage: 1 }
        }).then((response) => {
            const freshRef = response.data.reference;
            setReference_no(freshRef);
            setValue("reference_no", freshRef);
        });
    };

    const footerContent = (
        <div className="grid  grid-cols-12 ">
            <div className="col-span-7 flex justify-end"></div>
            <div className="col-span-5">
                <Button
                    label="Cancel"
                    icon="pi pi-times"
                    onClick={() => {
                        setVisible(false);
                        formReset();
                    }}
                    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>
    );

    // Data Store
    const DataStore = (data) => {
        if (data.list.length != 0) {
            axios
                .post(route("stock-adjustment.store", data))
                .then((response) => {
                    // Fetch new reference number from view endpoint
                    axios.get(route("stock-adjustment.view"), {
                        params: { page: 1, perPage: 1 }
                    }).then((refResponse) => {
                        const newRef = refResponse.data.reference;
                        setReference_no(newRef);
                        setValue("reference_no", newRef);
                    });
                    
                    formReset();
                    refreshData();
                    setVisible(false);

                    toast.current.show({
                        severity: "success",
                        summary: response.data.success,
                        detail: "Data Insterted ",
                        life: 3000,
                        className: "custom-toast-class",
                    });
                });
        } else {
            toast.current.show({
                severity: "error",
                summary: "Select any item",
                detail: "Proccess faield ",
                life: 3000,
                className: "custom-toast-class",
            });
        }
    };

    // Prodcut Edit
    const handleEdit = (data) => {
        setVisible(true);
        setStatus("update");
        setId(data.id);

        reset({
            reference_no: data.reference_no,
            adjustment_date: new Date(data.adjustment_date),
            location_id: Number(data.location_id),
            note: data.note || "",
            list: data.details.map((item) => {
                // Format product display name
                let productDisplay = "";
                if (item.product) {
                    productDisplay = item.product.name;
                    if (item.attribute) {
                        productDisplay += ` (SKU: ${item.attribute.sku})`;
                    }
                }
                return {
                    product_name: productDisplay,
                    product_id: Number(item.product_id),
                    attribute_id: Number(item.attribute_id),
                    adjust_qty: item.adjust_qty,
                    adjust_type: item.adjust_type, // 'increase' or 'decrease'
                    note: item.note || "",
                };
            }),
        });
    };
    //  Product Update
    const DataUpdate = (data) => {
        axios
            .put(route("stock-adjustment.update", id), data)
            .then((response) => {
                refreshData();

                toast.current.show({
                    severity: "success",
                    summary: response.data.success,
                    detail: "Data Updated ",
                    life: 3000,
                    className: "custom-toast-class",
                });
                setVisible(false);
            });
    };

    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 alrady add ",
                life: 3000,
            });
        } else {
            append({
                product_name: inputValue,
                product_id: Number(item.product.id),
                attribute_id: Number(item.id),
                adjust_qty: "",
                adjust_type: "increase",
                note: "",
            });
        }
    };

    const handelDelete = (e, id) => {
        confirmPopup({
            target: e.currentTarget,
            message: "Are you sure you want to delete this item?",
            icon: "pi pi-exclamation-triangle",
            accept: () => {
                axios
                    .delete(route("stock-adjustment.destroy", id))
                    .then((response) => {
                        refreshData();
                        toast.current.show({
                            severity: "success",
                            summary: response.data.success,
                            detail: "Data Deleted ",
                            life: 3000,
                            className: "custom-toast-class",
                        });
                    });
            },
            reject: () => {
                toast.current.show({
                    severity: "info",
                    summary: "Cancelled",
                    detail: "You have cancelled the delete operation",

                    life: 3000,
                    className: "custom-toast-class",
                });
            },
        });
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Stock Adjustment
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - Stock Adjustment{" "}
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            {/* View Table*/}
            <div className="card">
                <ServerSideDataTable
                    key={refreshTrigger}
                    fetchUrl={route("stock-adjustment.view")}
                    emptyMessage="No stock-adjustment found."
                    headerActions={TableHeader}
                >
                    <Column
                        field="reference_no"
                        body={(data) => {
                            return <b>{data.reference_no} </b>;
                        }}
                        header="Reference No"
                    />
                    <Column
                        field="return_date"
                        body={(date) => {
                            return new Date(
                                date.adjustment_date
                            ).toLocaleDateString("en-US");
                        }}
                        header="Date"
                    />

                    <Column
                        header="Warehouse/Shop"
                        body={(data) => {
                            return data.warehouse ? data.warehouse.name : "N/A";
                        }}
                    />
                    <Column
                        header="Action"
                        body={(rowData) => (
                            <>
                                <ConfirmPopup />
                                <Button
                                    icon="pi pi-eye"
                                    className="p-button-rounded p-button-info px-3 py-2 w-10 h-10 font-medium"
                                    onClick={() => {
                                        window.location.href = route("stock-adjustment.show", rowData.id);
                                    }}
                                />
                                <Button
                                    icon="pi pi-pencil"
                                    className="p-button-rounded p-button-success px-3 py-2 w-10 h-10 font-medium"
                                    onClick={() => handleEdit(rowData)}
                                />
                                <Button
                                    icon="pi pi-trash"
                                    onClick={(e) => handelDelete(e, rowData.id)}
                                    className="p-button-rounded p-button-warning px-3 py-2 w-10 h-10 font-medium"
                                />
                            </>
                        )}
                        bodyClassName="text-center"
                        style={{ minWidth: "10rem" }}
                        className="space-x-1"
                    />
                </ServerSideDataTable>
            </div>
            {/* View Table End*/}

            <Dialog
                header={() => (status == "create" ? "Create" : "Update")}
                visible={visible}
                style={{ width: "85vw", height: "100vh" }}
                onHide={() => {
                    setVisible(false);
                    formReset();
                }}
                footer={footerContent}
            >
                <form
                    onSubmit={
                        status == "create"
                            ? handleSubmit(DataStore)
                            : handleSubmit(DataUpdate)
                    }
                    ref={FormSubmit}
                    onKeyPress={(event) => {
                        if (event.key === "Enter") {
                            event.preventDefault();
                        }
                    }}
                >
                    <div className=" grid grid-cols-12 gap-6 mt-6  ">
                        <div className="field col-span-12 md:col-span-4">
                            <Controller
                                name="reference_no"
                                control={control}
                                rules={{
                                    required: "Reference No field is required",
                                }}
                                render={({ field, fieldState }) => (
                                    <>
                                        <span className="p-float-label">
                                            <InputText
                                                id={field.name}
                                                readOnly
                                                {...field}
                                                value={
                                                    status == "create"
                                                        ? reference_no || field.value
                                                        : field.value
                                                }
                                                className={
                                                    classNames({
                                                        "p-invalid":
                                                            fieldState.invalid,
                                                    }) + " w-full h-11"
                                                }
                                            />
                                            <label htmlFor={field.name}>
                                                Reference No *
                                            </label>
                                        </span>
                                        {getFormErrorMessageSingel("reference_no")}
                                    </>
                                )}
                            />
                        </div>
                        <div className="field col-span-12 md:col-span-4">
                            <Controller
                                name="adjustment_date"
                                control={control}
                                rules={{ required: "Date field is required" }}
                                render={({ field, fieldState }) => (
                                    <span className="p-float-label">
                                        <Calendar
                                            className="w-full h-11"
                                            id="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);
                                            }}
                                            dateFormat="mm/dd/yy"
                                            showIcon
                                        />
                                        <label htmlFor="calendar">
                                            Entry Date *
                                        </label>
                                    </span>
                                )}
                            />
                            {getFormErrorMessageSingel("adjustment_date")}
                        </div>
                        <div className="field col-span-3">
                            <Controller
                                name="location_id"
                                rules={{
                                    required:
                                        "Warehouse/Shop field is required",
                                }}
                                control={control}
                                render={({ field, fieldState }) => (
                                    <span className="p-float-label">
                                        <Dropdown
                                            options={warehouseList}
                                            id={field.name}
                                            onChange={(e) => {
                                                field.onChange(e.value);
                                                reset({
                                                    ...watch(),
                                                    list: [],
                                                });
                                            }}
                                            optionLabel="name"
                                            optionValue="id"
                                            placeholder="Select Maker list"
                                            filter
                                            value={
                                                field.value ??
                                                (!permission.includes(
                                                    "adjustment_super_admin_access"
                                                )
                                                    ? Number(auth.user.shop_id)
                                                    : "")
                                            }
                                            className="multiselect-custom w-full h-11"
                                            disabled={
                                                !permission.includes(
                                                    "adjustment_super_admin_access"
                                                )
                                            }
                                        />
                                        <label htmlFor={field.name}>
                                            Warehouse/Shop *
                                        </label>
                                    </span>
                                )}
                            />
                            {getFormErrorMessageSingel("location_id")}
                        </div>
                        <div className="field col-span-12 md:col-span-12 mt-5 mx-[25%]">
                            <Controller
                                name="remark"
                                control={control}
                                render={({ field }) => (
                                    <ProductDropdown
                                        field={field}
                                        selectedItem={selectedItem}
                                        filterColumn={{
                                            form_warehouse_id: watch("location_id"),
                                        }}
                                    />
                                )}
                            />
                        </div>
                    </div>
                    <div
                        className=" grid grid-cols-12 gap-6 mt-10 "
                        ref={scroll}
                    >
                        {fields.map((item, index) => (
                            <DynamicFieldGroup
                                key={item.id}
                                control={control}
                                watch={watch}
                                setValue={setValue}
                                remove={remove}
                                index={index}
                                getFormErrorMessageMultiple={
                                    getFormErrorMessageMultiple
                                }
                                mode="stockadjustment"
                                readOnlyFields={["product_name", "total"]}
                            />
                        ))}
                    </div>
                </form>
            </Dialog>
        </AuthenticatedLayout>
    );
}

export default StockAdjustment;
