import React 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";
function CheckMaker({ auth }) {
    const [purhchase, SetPurchase] = useState([]);
    const [product, SetProduct] = useState([]);
    const [unit, SetUnit] = useState([]);
    const [category, SetCaegory] = useState([]);
    const [Warehouse, SetWarehouse] = useState([]);
    const toast = useRef();

    // From Controll
    const {
        control,
        register,
        formState: { errors },
        handleSubmit,
        reset,
        watch,
        setValue,
    } = useForm({
        purchase_id: "",
        warehouse_id: "",
        list: [
            {
                product_id: "",
                quantity: "",
                price: "",
                unit_id: "",
                category_id: "",
                total: 0,
            },
        ],
    });
    const { fields, remove } = useFieldArray({
        control,
        name: "list",
    });
    useEffect(() => {
        axios.get(route("purchase-checker-maker.view")).then((response) => {
            SetPurchase(response.data.purchases);
            SetProduct(response.data.product);
            SetUnit(response.data.unit);
            SetCaegory(response.data.category);
            SetWarehouse(response.data.warehouse);
        });
    }, []);
    // Get Purchase List
    const GetPurchaseDetiles = (id) => {
        const getdata = purhchase.find((data) => {
            return data.id == id;
        });

        reset({
            purchase_id: watch("purchase_id"),
            warehouse_id: watch("warehouse_id"),
            list: getdata.purchase_detalis.map((e) => {
                return {
                    product_id: Number(e.product_id),
                    quantity: e.quantity,
                    price: e.price,
                    unit_id: Number(e.unit_id),
                    category_id: Number(e.category_id),
                    total: e.total,
                };
            }),
        });
    };
    // 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
                .put(
                    route("purchase-checker-maker.update", data.purchase_id),
                    data
                )
                .then((response) => {
                    toast.current.show({
                        severity: "info",
                        summary: "Confirmed",
                        detail: response.data.success,
                        life: 3000,
                    });
                    SetPurchase(response.data.purchases);
                    reset({
                        purchase_id: "",
                        warehouse_id: "",
                        list: [
                            {
                                product_id: "",
                                quantity: "",
                                price: "",
                                unit_id: "",
                                category_id: "",
                                total: 0,
                            },
                        ],
                    });
                });
        } else {
            toast.current.show({
                severity: "warn",
                summary: "Rejected",
                detail: "Must  need a product",
                life: 3000,
            });
        }
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        {" "}
                        Checker Maker
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - Checker Maker
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            <ConfirmDialog />
            <form onSubmit={handleSubmit(StoreData)}>
                {/* Single Field */}
                <div className="flex justify-center gap-5 my-6">
                    <div className="field">
                        <span className="p-float-label">
                            <Controller
                                name="purchase_id"
                                rules={{
                                    required: "Invoice no field is required",
                                }}
                                control={control}
                                render={({ field }) => (
                                    <Dropdown
                                        options={purhchase}
                                        value={watch("purchase_id")}
                                        onChange={(e) => {
                                            setValue("purchase_id", e.value);
                                            GetPurchaseDetiles(e.value);
                                        }}
                                        optionLabel="invoice_no"
                                        optionValue="id"
                                        placeholder="Select Maker list"
                                        filter
                                        showClear
                                        className="multiselect-custom w-80  h-11"
                                    />
                                )}
                            />
                            <label htmlFor="purchase_id">Select Invoice</label>
                        </span>
                        {getFormErrorMessageSingel("purchase_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}
                                        {...field}
                                        optionLabel="name"
                                        optionValue="id"
                                        placeholder="Select Maker list"
                                        filter
                                        showClear
                                        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  gap-5  my-10 px-14">
                    {fields.map((item, index) => {
                        return (
                            <>
                                <div className="field col-span-3">
                                    <Controller
                                        name={`list.${index}.product_id`}
                                        control={control}
                                        rules={{
                                            required:
                                                "Product field is required",
                                        }}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <Dropdown
                                                    options={product}
                                                    id={field.name}
                                                    {...field}
                                                    showClear
                                                    optionLabel="name"
                                                    optionValue="id"
                                                    placeholder="Select Maker list"
                                                    filter
                                                    disabled
                                                    className="multiselect-custom  opacity-[10.06] w-full h-11 "
                                                />
                                                <label htmlFor={field.name}>
                                                    Product
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `product_id`,
                                        index
                                    )}
                                </div>
                                <div className="field col-span-1">
                                    <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"
                                                    id={field.name}
                                                    value={field.value}
                                                    onChange={(e) => {
                                                        let current =
                                                            e.target.value
                                                                .length != 0
                                                                ? e.target.value
                                                                : 0;
                                                        setValue(
                                                            `list.${index}.quantity`,
                                                            e.target.value
                                                        );
                                                        let price = watch(
                                                            `list.${index}.price`
                                                        );
                                                        price =
                                                            price != undefined
                                                                ? price
                                                                : 0;

                                                        current =
                                                            price * current;
                                                        setValue(
                                                            `list.${index}.total`,
                                                            current
                                                        );
                                                    }}
                                                    className={
                                                        classNames({
                                                            "p-invalid":
                                                                fieldState.invalid,
                                                        }) +
                                                        "multiselect-custom  w-full h-11"
                                                    }
                                                />
                                                <label htmlFor="calendar">
                                                    Qty
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `quantity`,
                                        index
                                    )}
                                </div>
                                <div className="field col-span-2">
                                    <Controller
                                        name={`list.${index}.price`}
                                        control={control}
                                        rules={{
                                            required: "Price Field is required",
                                            min: {
                                                value: 0,
                                                message:
                                                    "nagative value not allow",
                                            },
                                        }}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <InputText
                                                    type="number"
                                                    id={field.name}
                                                    value={field.value}
                                                    onChange={(e) => {
                                                        let current =
                                                            e.target.value
                                                                .length != 0
                                                                ? e.target.value
                                                                : 0;
                                                        setValue(
                                                            `list.${index}.price`,
                                                            e.target.value
                                                        );
                                                        let qty = watch(
                                                            `list.${index}.quantity`
                                                        );

                                                        qty =
                                                            qty != undefined
                                                                ? qty
                                                                : 0;
                                                        current = current * qty;
                                                        setValue(
                                                            `list.${index}.total`,
                                                            current
                                                        );
                                                    }}
                                                    className={
                                                        classNames({
                                                            "p-invalid":
                                                                fieldState.invalid,
                                                        }) +
                                                        "multiselect-custom w-full h-11"
                                                    }
                                                />
                                                <label htmlFor="calendar">
                                                    Price
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `price`,
                                        index
                                    )}
                                </div>
                                <div className="field col-span-2">
                                    <Controller
                                        name={`list.${index}.unit_id`}
                                        control={control}
                                        rules={{
                                            required: "Unit Field is required",
                                        }}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <Dropdown
                                                    options={unit}
                                                    id={field.name}
                                                    value={field.value}
                                                    {...field}
                                                    optionLabel="name"
                                                    optionValue="id"
                                                    placeholder="Select Maker list"
                                                    filter
                                                    className="multiselect-custom w-full h-11"
                                                    disabled
                                                />
                                                <label htmlFor={field.name}>
                                                    Unit
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `unit_id`,
                                        index
                                    )}
                                </div>
                                <div className="field col-span-2">
                                    <Controller
                                        name={`list.${index}.category_id`}
                                        rules={{
                                            required:
                                                "Category Field is required",
                                        }}
                                        control={control}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label">
                                                <Dropdown
                                                    options={category}
                                                    id={field.name}
                                                    value={field.value}
                                                    {...field}
                                                    optionLabel="name"
                                                    optionValue="id"
                                                    placeholder="Select Maker list"
                                                    filter
                                                    className="multiselect-custom w-full h-11"
                                                    disabled
                                                />
                                                <label htmlFor={field.name}>
                                                    Category
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `category_id`,
                                        index
                                    )}
                                </div>
                                <div className="field col-span-1 ">
                                    <Controller
                                        name={`list.${index}.total`}
                                        rules={{
                                            required: "Total Field is required",
                                        }}
                                        control={control}
                                        render={({ field, fieldState }) => (
                                            <span className="p-float-label  p-inputtext-sm  ">
                                                <InputText
                                                    readOnly
                                                    value={field.value}
                                                    {...field}
                                                    className="h-11 w-full"
                                                />
                                                <label htmlFor="total">
                                                    Total
                                                </label>
                                            </span>
                                        )}
                                    />
                                    {getFormErrorMessageMultiple(
                                        `total`,
                                        index
                                    )}
                                </div>

                                <div className="field col-span-1   flex gap-2  w-5  mb-3 ">
                                    <span className="p-float-label  p-inputtext-sm  ">
                                        <Button
                                            icon="pi pi-trash"
                                            onClick={(event) => {
                                                event.preventDefault();
                                                confirmDialog({
                                                    message:
                                                        "Do you want to delete this record?",
                                                    header: "Delete Confirmation",
                                                    icon: "pi pi-info-circle",
                                                    acceptClassName:
                                                        "p-button-danger",
                                                    accept: () => {
                                                        remove(index);
                                                        let lists =
                                                            watch("list");
                                                        reset({
                                                            purchase_id:
                                                                watch(
                                                                    "purchase_id"
                                                                ),
                                                            warehouse_id:
                                                                watch(
                                                                    "warehouse_id"
                                                                ),
                                                            list: lists.map(
                                                                (e) => {
                                                                    return {
                                                                        product_id:
                                                                            e[
                                                                                "product_id"
                                                                            ],
                                                                        quantity:
                                                                            e[
                                                                                "quantity"
                                                                            ],
                                                                        price: e[
                                                                            "price"
                                                                        ],
                                                                        unit_id:
                                                                            e[
                                                                                "unit_id"
                                                                            ],
                                                                        category_id:
                                                                            e[
                                                                                "category_id"
                                                                            ],
                                                                        total: e[
                                                                            "total"
                                                                        ],
                                                                    };
                                                                }
                                                            ),
                                                        });
                                                        toast.current.show({
                                                            severity: "info",
                                                            summary:
                                                                "Confirmed",
                                                            detail: "You have accepted",
                                                            life: 3000,
                                                        });
                                                    },
                                                    reject: () => {
                                                        toast.current.show({
                                                            severity: "warn",
                                                            summary: "Rejected",
                                                            detail: "You have rejected",
                                                            life: 3000,
                                                        });
                                                    },
                                                });
                                            }}
                                            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="Save" className="text-xs " />
                </div>
            </form>
        </AuthenticatedLayout>
    );
}

export default CheckMaker;
