import { React, useState } from "react";
import { DataTable } from "primereact/datatable";
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 { useRef } from "react";
import { useForm, Controller } from "react-hook-form";
import axios from "axios";
import { Toast } from "primereact/toast";
import { useEffect } from "react";
import { FilterMatchMode } from "primereact/api";
import { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import { Dropdown } from "primereact/dropdown";
function Role({ auth }) {
    const [status, setStatus] = useState("create");
    const [shop, setShop] = useState([]);
    const [role, setRole] = useState([]);
    const [user, setUser] = useState([]);
    const [supplier, setSupplier] = useState([]);
    const [visible, setVisible] = useState(false);
    const [id, setId] = useState();
    const formSubmit = useRef(null);
    const toast = useRef(null);
    const [filters, setFilters] = useState({
        global: { value: null, matchMode: FilterMatchMode.CONTAINS },
        name: { value: null, matchMode: FilterMatchMode.STARTS_WITH },
    });

    const [globalFilterValue, setGlobalFilterValue] = useState("");

    const {
        register,
        control,
        handleSubmit,
        formState: { errors },
        setValue,
        watch,
        reset,
        setError,
    } = useForm({
        name: "",
        email: "",
        password: "",
        nid: "",
        number: "",
        supplier_id: "",
        status: "",
        role_id: "",
        shop_id: "",
        image: "",
    });

    const formData = watch();

    useEffect(() => {
        axios.get(route("user.view")).then((response) => {
            setShop(response.data.shop);
            setRole(response.data.role);
            setUser(response.data.user);
            setSupplier(response.data.supplier);
            
        });
    }, []);

    {
        /* Table Data Search */
    }
    const onGlobalFilterChange = (e) => {
        const value = e.target.value;
        let _filters = { ...filters };

        _filters["global"].value = value;

        setFilters(_filters);
        setGlobalFilterValue(value);
    };
    {
        /*Table Header*/
    }
    const TableHeader = () => {
        return (
            <div className="w-100% flex justify-between	">
                <Button
                    type="button"
                    icon={<span className="pi pi-plus text-sm pr-1" />}
                    label="Add"
                    onClick={() => {
                        setVisible(true);
                        setStatus("create");
                    }}
                    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"
                        value={globalFilterValue}
                        onChange={onGlobalFilterChange}
                        placeholder="Search"
                    />
                </span>
            </div>
        );
    };

    {
        /*Dilog Model Footer*/
    }
    const userFooterContent = (
        <div className="flex justify-end">
            <Button
                label="Cancel"
                icon="pi pi-times"
                onClick={() => {
                    setVisible(false);
                    reset({
                        name: "",
                        email: "",
                        password: "",
                        nid: "",
                        number: "",
                        supplier_id: "",
                        status: "",
                        role_id: "",
                        shop_id: "",
                        image: "",
                    });
                }}
                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>
    );

    // Store Data
    const StoreData = (data) => {
        let form = new FormData();
        form.append("image", data.image[0] ? data.image[0] : null);
        form.append("name", data.name);
        form.append("email", data.email);
        form.append("password", data.password);
        if (data.shop_id) {
            form.append("shop_id", data.shop_id);
        }

        form.append("role_id", data.role_id);
        if (data.supplier_id) {
            form.append("supplier_id", data.supplier_id);
        }

        form.append("number", data.number);
        form.append("status", data.status);
        form.append("nid", data.nid);
        axios
            .post(route("user.store"), form)
            .then((response) => {
                toast.current.show({
                    severity: "info",
                    summary: "Confirmed",
                    detail: response.data.success,
                    life: 3000,
                });
                setUser(response.data.user);
                reset({
                    name: "",
                    email: "",
                    password: "",
                    nid: "",
                    number: "",
                    supplier_id: "",
                    status: "",
                    role_id: "",
                    shop_id: "",
                    image: "",
                });
                setVisible(false);
            })
            .catch((error) => {
                let errors = error.response.data.errors;
                Object.keys(errors).forEach((field) => {
                    setError(field, {
                        type: "manual",
                        message: errors[field][0],
                    });
                });
            });
    };

    // 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("user.destroy", id))
                    .then((response) => {
                        setUser(response.data.user);
                        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,
                });
            },
        });
    };
    // Data Update
    const UpdateData = (data) => {
        let form = new FormData();
        form.append("image", data.image[0] ? data.image[0] : null);
        form.append("name", data.name);
        form.append("email", data.email);
        form.append("password", data.password);
        if (data.shop_id) {
            form.append("shop_id", data.shop_id);
        }

        form.append("role_id", data.role_id);
        if (data.supplier_id) {
            form.append("supplier_id", data.supplier_id);
        }

        form.append("number", data.number);
        form.append("status", data.status);
        form.append("nid", data.nid);
        form.append("number", data.number);
        form.append("status", data.status);
        form.append("nid", data.nid);
        form.append("_method", "put");
        axios
            .post(route("user.update", id), form)
            .then((response) => {
                toast.current.show({
                    severity: "info",
                    summary: "Confirmed",
                    detail: response.data.success,
                    life: 3000,
                });
                setUser(response.data.user);
                reset({
                    name: "",
                    email: "",
                    password: "",
                    nid: "",
                    number: "",
                    supplier_id: "",
                    status: "",
                    role_id: "",
                    shop_id: "",
                    image: "",
                });
                setVisible(false);
            })
            .catch((error) => {
                let errors = error.response.data.errors;
                Object.keys(errors).forEach((field) => {
                    setError(field, {
                        type: "manual",
                        message: errors[field][0],
                    });
                });
            });
    };

    const validateImage = (file) => {
        if (file && file[0]) {
            const fileName = file[0].name;

            // Perform null/undefined check for fileName.split(".")
            const fileExtension = (
                fileName.split(".").pop() || ""
            ).toLowerCase();

            const allowedExtensions = ["jpg", "jpeg", "png", "gif"];
            const maxSizeInBytes = 500000;

            if (!allowedExtensions.includes(fileExtension)) {
                return "Only image files with allowed extensions are allowed";
            } else if (file[0].size >= maxSizeInBytes) {
                return "Image size should be less than 500KB";
            }
        }

        return true; // Return true for valid cases
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">User/SR</h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - User/SR
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            {/* View Table*/}
            <div className="card">
                <DataTable
                    className="defulattable"
                    value={user}
                    paginator
                    showGridlines
                    rows={10}
                    dataKey="id"
                    header={TableHeader}
                    filters={filters}
                    emptyMessage="No roles found."
                >
                    <Column field="name" header="Name" />
                    <Column field="email" header="Email" />
                    <Column
                        field="Shop"
                        header="Counter"
                        body={(item) => {
                            return item.shop ? item.shop.name : "---";
                        }}
                    />
                    {/* <Column
                        field="supplier_Id"
                        header="Company"
                        body={(item) => {
                            return item.supplier ? item.supplier.name : "---";
                        }}
                    /> */}
                    <Column
                        field="Role"
                        header="role"
                        body={(item) => {
                            return item.role ? item.role.name : "---";
                        }}
                    />

                    <Column
                        header="Action"
                        body={(rowData) => (
                            <>
                                {" "}
                                <ConfirmPopup />{" "}
                                <Button
                                    icon="pi pi-pencil"
                                    onClick={() => {
                                        setVisible(true);
                                        setStatus("update");
                                        reset({
                                            name: rowData.name,
                                            email: rowData.email,
                                            number: rowData.number
                                                ? Number(rowData.number)
                                                : null,
                                            nid: rowData.nid
                                                ? Number(rowData.nid)
                                                : null,
                                            shop_id:
                                                Number(rowData.shop_id) ?? null,
                                            role_id: Number(rowData.role_id),
                                            supplier_id:
                                                Number(rowData.supplier_id) ??
                                                null,
                                            status: rowData.status,
                                        });

                                        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"
                        style={{ minWidth: "8rem" }}
                    />
                </DataTable>
            </div>
            {/* View Table End*/}
            <Dialog
                header={() => (status == "create" ? "Create" : "Update")}
                visible={visible}
                style={{ width: "45vw" }}
                onHide={() => {
                    setVisible(false);
                    reset({
                        name: "",
                        email: "",
                        password: "",
                        role_id: "",
                        shop_id: "",
                        image: "",
                    });
                }}
                footer={userFooterContent}
            >
                <form
                    onSubmit={
                        status == "create"
                            ? handleSubmit(StoreData)
                            : handleSubmit(UpdateData)
                    }
                    ref={formSubmit}
                >
                    <div className=" grid grid-cols-12 gap-2">
                        <div className=" col-span-6 ">
                            <div className="p-float-label mt-6">
                                <InputText
                                    id="name"
                                    defaultValue={watch("name")}
                                    className={`w-full ${
                                        errors.name && "p-invalid"
                                    }`}
                                    {...register("name", {
                                        required: "Name Field is Required",
                                    })}
                                />
                                <label htmlFor="name">
                                    Name <span className="text-red-500">*</span>
                                </label>
                            </div>
                            {errors.name && (
                                <small
                                    id="username2-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.name.message}
                                </small>
                            )}
                        </div>
                        <div className=" col-span-6">
                            <div className="p-float-label mt-6">
                                <InputText
                                    id="email"
                                    type="email"
                                    defaultValue={watch("email")}
                                    className={`w-full ${
                                        errors.email && "p-invalid"
                                    }`}
                                    {...register("email", {
                                        required: "Email Field is Required",
                                    })}
                                />
                                <label htmlFor="email">
                                    Email<span className="text-red-500">*</span>
                                </label>
                            </div>
                            {errors.email && (
                                <small
                                    id="username2-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.email.message}
                                </small>
                            )}
                        </div>

                        <div className=" col-span-6">
                            <div className="p-float-label mt-6">
                                <InputText
                                    id="password"
                                    type="password"
                                    {...register("password")}
                                    defaultValue={watch("password")}
                                    className={`w-full ${
                                        errors.password && "p-invalid"
                                    }`}
                                />
                                <label htmlFor="password">Password </label>
                            </div>
                            {errors.password && (
                                <small
                                    id="username2-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.password.message}
                                </small>
                            )}
                        </div>
                        <div className=" col-span-6">
                            <div className="p-float-label mt-6">
                                <InputText
                                    id="nid"
                                    type="number"
                                    defaultValue={watch("nid")}
                                    className={`w-full ${
                                        errors.nid && "p-invalid"
                                    }`}
                                    {...register("nid")}
                                />
                                <label htmlFor="nid">NID</label>
                            </div>
                            {errors.nid && (
                                <small
                                    id="username2-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.nid.message}
                                </small>
                            )}
                        </div>
                        <div className=" col-span-6">
                            <div className="p-float-label mt-6">
                                <InputText
                                    id="number"
                                    type="number"
                                    defaultValue={watch("number")}
                                    className={`w-full ${
                                        errors.nid && "p-invalid"
                                    }`}
                                    {...register("number", {
                                        min: {
                                            value: 11,
                                            message: "Number must be 11 digit ",
                                        },
                                    })}
                                />
                                <label htmlFor="number">Contact Number</label>
                            </div>
                            {errors.number && (
                                <small
                                    id="username2-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.number.message}
                                </small>
                            )}
                        </div>
                        <div className=" col-span-6">
                            <div className="p-float-label mt-6">
                                <Controller
                                    name="shop_id"
                                    control={control}
                                    render={({ field }) => (
                                        <>
                                            <Dropdown
                                                id={field.name}
                                                options={shop}
                                                optionLabel="name"
                                                optionValue="id"
                                                {...field}
                                                filter
                                                showClear
                                                className="w-full"
                                                placeholder="Select a Counter"
                                            />
                                            <label htmlFor={field.name}>
                                                Counter
                                            </label>
                                        </>
                                    )}
                                />
                            </div>
                        </div>

                        {/* <div className=" col-span-6">
                            <div className="p-float-label mt-6">
                                <Controller
                                    name="supplier_id"
                                    control={control}
                                    render={({ field }) => (
                                        <>
                                            <Dropdown
                                                id={field.name} // Use field.name for the id
                                                className="w-full"
                                                onChange={(e) => {
                                                    if (e.value) {
                                                        field.onChange(e.value); // Update form state with selected value
                                                    } else {
                                                        field.onChange(""); // Update form state with empty string
                                                    }
                                                }}
                                                options={supplier}
                                                optionLabel="name"
                                                filter
                                                showClear
                                                optionValue="id"
                                                placeholder="Select a supplier"
                                                value={field.value} // Ensure field.value is used
                                            />
                                            <label htmlFor={field.name}>
                                                Company
                                            </label>{" "}
                                        </>
                                    )}
                                />
                            </div>
                        </div> */}
                        <div className=" col-span-6">
                            <div className="p-float-label mt-6">
                                <Controller
                                    name="role_id"
                                    control={control}
                                    rules={{
                                        required: "Role field is required",
                                    }}
                                    render={({ field }) => (
                                        <>
                                            <Dropdown
                                                id={field.name}
                                                className="w-full"
                                                {...field}
                                                options={role}
                                                optionLabel="name"
                                                filter
                                                showClear
                                                optionValue="id"
                                                placeholder="Select a Role*"
                                            />
                                            <label htmlFor={field.name}>
                                                Role
                                                <span className="text-red-500">
                                                    *
                                                </span>
                                            </label>
                                        </>
                                    )}
                                />
                            </div>
                            {errors.role_id && (
                                <small
                                    id="username2-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.role_id.message}
                                </small>
                            )}
                        </div>
                        <div className=" col-span-6">
                            <div className="p-float-label mt-6">
                                <Controller
                                    name="status"
                                    control={control}
                                    rules={{
                                        required: "Status field is required",
                                    }}
                                    render={({ field }) => (
                                        <>
                                            <Dropdown
                                                id={field.name}
                                                className="w-full"
                                                {...field}
                                                options={[
                                                    { name: "Active", id: "1" },
                                                    {
                                                        name: "Inactive",
                                                        id: "0",
                                                    },
                                                ]}
                                                optionLabel="name"
                                                filter
                                                showClear
                                                optionValue="id"
                                                placeholder="Select a Role*"
                                            />
                                            <label htmlFor={field.name}>
                                                Status
                                                <span className="text-red-500">
                                                    *
                                                </span>
                                            </label>
                                        </>
                                    )}
                                />
                            </div>
                            {errors.status && (
                                <small
                                    id="username2-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.status.message}
                                </small>
                            )}
                        </div>
                        <div className=" col-span-6">
                            <div className="field mt-7">
                                <div className="file-input-container">
                                    <input
                                        type="file"
                                        id="file-input"
                                        className="real-file-input"
                                        accept="image/*"
                                        {...register("image", {
                                            validate: validateImage,
                                            onChange: (e) => {
                                                if (errors.image) {
                                                    reset((e) => {
                                                        return {
                                                            ...e,
                                                            image: e.target
                                                                .files[0],
                                                        };
                                                    });
                                                }
                                            },
                                        })}
                                    />
                                    <label
                                        for="file-input"
                                        className="custom-file-label"
                                    >
                                        <span>
                                            {" "}
                                            <i className="bx bx-plus"></i>{" "}
                                            Choose a Photo
                                        </span>
                                    </label>
                                    {errors.image && (
                                        <small className="p-error block  m-1 absolute">
                                            {errors.image.message}
                                        </small>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </Dialog>
        </AuthenticatedLayout>
    );
}

export default Role;
