import { React, useState, useContext } 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 { Checkbox } from "primereact/checkbox";
import { useRef } from "react";
import { Controller, useForm } 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 { InputTextarea } from "primereact/inputtextarea";
import { authUser } from "@/Components/AuthProvider";
import { Calendar } from "primereact/calendar";
import { Dropdown } from "primereact/dropdown";

function Supplier({ auth }) {
    const { permission } = useContext(authUser);
    const [status, setStatus] = useState("create");
    const [visible, setVisible] = useState(false);
    const [supplier, setSupplier] = useState([]);
    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 {
        control,
        register,
        handleSubmit,
        formState: { errors },
        setValue,
        watch,
        reset,
    } = useForm({
        name: "",
        email: "",
        number: "",
        opening_date: "",
        opening_balance: "",
        proprietor: "",
        address: "",
        status: "",
    });

    useEffect(() => {
        axios.get(route("supplier.view")).then((response) => {
            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 ${
                    permission.includes("supplier_create")
                        ? "justify-between"
                        : "justify-end"
                } `}
            >
                {permission.includes("supplier_create") && (
                    <Button
                        type="button"
                        icon={<span className="pi pi-plus text-sm pr-1" />}
                        label="Add"
                        onClick={() => {
                            setVisible(true);
                            setStatus("create");
                            reset({
                                name: "",
                                email: "",
                                number: "",
                                opening_date: "",
                                opening_balance: "",
                                proprietor: "",
                                address: "",
                                status: "",
                            });
                        }}
                        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 footerContent = (
        <div className="flex justify-end">
            <Button
                label="Cancel"
                icon="pi pi-times"
                onClick={() => {
                    setVisible(false);
                    reset();
                }}
                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) => {
        axios.post(route("supplier.store", data)).then((response) => {
            toast.current.show({
                severity: "info",
                summary: "Confirmed",
                detail: response.data.success,
                life: 3000,
            });
            setSupplier(response.data.supplier);
            reset();
            setVisible(false);
        });
    };

    // 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("supplier.destroy", id))
                    .then((response) => {
                        setSupplier(response.data.supplier);
                        toast.current.show({
                            severity: "info",
                            summary: "Confirmed",
                            detail: response.data.success,
                            life: 3000,
                        });
                    })
                    .catch((error) => {
                        let errors = error.response.data.error;

                        toast.current.show({
                            severity: "warn",
                            summary: "Rejected",
                            detail: errors,
                            life: 3000,
                        });
                    });
            },
            reject() {
                toast.current.show({
                    severity: "warn",
                    summary: "Rejected",
                    detail: "You have rejected",
                    life: 3000,
                });
            },
        });
    };
    // Data Update
    const UpdateData = (data) => {
        axios.put(route("supplier.update", id), data).then((response) => {
            toast.current.show({
                severity: "info",
                summary: "Confirmed",
                detail: response.data.success,
                life: 3000,
            });
            setSupplier(response.data.supplier);
            reset();
            setVisible(false);
        });
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">Company</h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - Supplier
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            {/* View Table*/}
            <div className="card">
                <DataTable
                    className="defulattable"
                    value={supplier}
                    paginator
                    showGridlines
                    rows={10}
                    dataKey="id"
                    header={TableHeader}
                    filters={filters}
                    emptyMessage="No supplier found."
                >
                    <Column
                        field="name"
                        header="Name"
                        style={{ minWidth: "12rem" }}
                    />
                    <Column
                        field="email"
                        header="Email"
                        style={{ minWidth: "12rem" }}
                    />
                    <Column
                        field="number"
                        header="Number"
                        style={{ minWidth: "6rem" }}
                    />
                       <Column
                        field="opening_balance"
                        header="Opening Balance"
                        style={{ minWidth: "6rem" }}
                    />
                    <Column
                        field="address"
                        header="Address"
                        style={{ minWidth: "12rem" }}
                    />
                    <Column
                        header="Action"
                        body={(rowData) => (
                            <>
                                {" "}
                                <ConfirmPopup />{" "}
                                {permission.includes("supplier_edit") && (
                                    <Button
                                        icon="pi pi-pencil"
                                        onClick={() => {
                                            setVisible(true);
                                            setStatus("update");
                                            reset({
                                                name: rowData.name,
                                                email: rowData.email,
                                                number: rowData.number,
                                                address: rowData.address,
                                                opening_date: new Date(
                                                    rowData.opening_date
                                                ),
                                                opening_balance:
                                                    rowData.opening_balance,
                                                proprietor: rowData.proprietor,
                                                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"
                                    />
                                )}
                                {permission.includes("supplier_delete") && (
                                    <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: "50vw" }}
                onHide={() => {
                    setVisible(false);
                    reset();
                }}
                footer={footerContent}
            >
                <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 Requerd",
                                    })}
                                />
                                <label htmlFor="name">Name*</label>
                            </div>
                            {errors.name && (
                                <small
                                    id="name-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="proprietor"
                                    defaultValue={watch("proprietor")}
                                    className={`w-full ${
                                        errors.proprietor && "p-invalid"
                                    }`}
                                    {...register("proprietor")}
                                />
                                <label htmlFor="proprietor">Proprietor</label>
                            </div>
                            {errors.proprietor && (
                                <small
                                    id="name-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.proprietor.message}
                                </small>
                            )}
                        </div>
                        <div className=" col-span-6">
                            <div className="p-float-label mt-6">
                                <InputText
                                    id="email"
                                    defaultValue={watch("email")}
                                    className={`w-full ${
                                        errors.email && "p-invalid"
                                    }`}
                                    {...register("email", {
                                        pattern: {
                                            value: /[a-zA-Z0-9._+-]+\@[a-zA-Z0-9.-]+\.[a-zA-Z]+/,
                                            message: "Must need an email",
                                        },
                                    })}
                                />
                                <label htmlFor="email">Email</label>
                            </div>
                            {errors.email && (
                                <small
                                    id="email-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="number"
                                    defaultValue={watch("number")}
                                    className={`w-full ${
                                        errors.number && "p-invalid"
                                    }`}
                                    {...register("number", {
                                        required: "Number Field is Required",
                                    })}
                                />
                                <label htmlFor="number">Contact Number*</label>
                            </div>
                            {errors.number && (
                                <small
                                    id="number-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.number.message}
                                </small>
                            )}
                        </div>
                        <div className="col-span-6">
                            <div className="p-float-label mt-6">
                                <InputText
                                    id="opening_balance"
                                    defaultValue={watch("opening_balance")}
                                    className={`w-full ${
                                        errors.opening_balance && "p-invalid"
                                    }`}
                                    {...register("opening_balance", {
                                        pattern: {
                                            value: /[0-9]+/,
                                            message:
                                                "Please enter a valid number.",
                                        },
                                    })}
                                />
                                <label htmlFor="nid">Opening Balance</label>
                            </div>
                            {errors.opening_balance && (
                                <small
                                    id="number-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.opening_balance.message}
                                </small>
                            )}
                        </div>
                        <div className=" col-span-6">
                            <div className="p-float-label mt-6">
                                <Calendar
                                    id="opening_date"
                                    value={watch("opening_date")}
                                    className={`w-full ${
                                        errors.opening_date && "p-invalid"
                                    }`}
                                    {...register("opening_date", {
                                        pattern: {
                                            value: /[0-9]+/,
                                            message:
                                                "Please enter a valid number.",
                                        },
                                    })}
                                />
                                <label htmlFor="opening_date">
                                    Opening Date
                                </label>
                            </div>
                            {errors.opening_date && (
                                <small
                                    id="number-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.opening_date.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
                                            {...field}
                                            optionLabel="name"
                                            optionValue="id"
                                            className="w-full"
                                            options={[
                                                { name: "Active", id: "1" },
                                                { name: "Inactive", id: "0" },
                                            ]}
                                            placeholder="Select a status"
                                        />
                                    )}
                                />
                                <label htmlFor="status">Status*</label>
                            </div>
                            {errors.status && (
                                <small
                                    id="number-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.status.message}
                                </small>
                            )}
                        </div>
                        <div className=" col-span-12">
                            <div className="field col-12 md:col-4 mt-6">
                                <span className="p-float-label">
                                    <InputTextarea
                                        id="textarea"
                                        defaultValue={watch("address")}
                                        rows={3}
                                        {...register("address")}
                                        className="w-full"
                                    />
                                    <label htmlFor="textarea">Address</label>
                                </span>
                            </div>
                        </div>
                    </div>
                </form>
            </Dialog>
        </AuthenticatedLayout>
    );
}

export default Supplier;
