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 Cnf({ auth }) {
    const { permission } = useContext(authUser);
    const [status, setStatus] = useState("create");
    const [visible, setVisible] = useState(false);
    const [cnf, setCnf] = 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({
        company_name: "",
        contact_person_name: "",
        designation: "",
        contact_number: "",
        address: "",
        email: "",
        status: "",
    });

    useEffect(() => {
        axios.get(route("cnf.view")).then((response) => {
            setCnf(response.data.cnf);
        });
    }, []);

    {
        /* 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("cnf_create")
                        ? "justify-between"
                        : "justify-end"
                } `}
            >
                {permission.includes("cnf_create") && (
                    <Button
                        type="button"
                        icon={<span className="pi pi-plus text-sm pr-1" />}
                        label="Add"
                        onClick={() => {
                            setVisible(true);
                            setStatus("create");
                            reset({
                                company_name: "",
                                contact_person_name: "",
                                designation: "",
                                contact_number: "",
                                address: "",
                                email: "",
                                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) => {
        console.log("Data being sent:", data);
        axios.post(route("cnf.store"), data)
            .then((response) => {
                console.log("Response:", response);
                toast.current.show({
                    severity: "info",
                    summary: "Confirmed",
                    detail: response.data.success,
                    life: 3000,
                });
                setCnf(response.data.cnf);
                reset();
                setVisible(false);
            })
            .catch((error) => {
                console.error("Error:", error);
                console.error("Error response:", error.response);
                toast.current.show({
                    severity: "error",
                    summary: "Error",
                    detail: error.response?.data?.message || "Failed to save data",
                    life: 3000,
                });
            });
    };

    // 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("cnf.destroy", id))
                    .then((response) => {
                        setCnf(response.data.cnf);
                        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("cnf.update", id), data).then((response) => {
            toast.current.show({
                severity: "info",
                summary: "Confirmed",
                detail: response.data.success,
                life: 3000,
            });
            setCnf(response.data.cnf);
            reset();
            setVisible(false);
        });
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">C&F Directory</h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - C&F
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            {/* View Table*/}
            <div className="card">
                <DataTable
                    className="defulattable"
                    value={cnf}
                    paginator
                    showGridlines
                    rows={10}
                    dataKey="id"
                    header={TableHeader}
                    filters={filters}
                    emptyMessage="No C&F found."
                >
                    <Column
                        field="company_name"
                        header="Company Name"
                        style={{ minWidth: "12rem" }}
                    />
                    <Column
                        field="contact_person_name"
                        header="Contact Person's Name"
                        style={{ minWidth: "12rem" }}
                    />
                    <Column
                        field="contact_number"
                        header="Contact Number"
                        style={{ minWidth: "6rem" }}
                    />
                    <Column
                        field="address"
                        header="Address"
                        style={{ minWidth: "12rem" }}
                    />
                    <Column
                        field="email"
                        header="Email"
                        style={{ minWidth: "12rem" }}
                    />
                    <Column
                        header="Action"
                        body={(rowData) => (
                            <>
                                {" "}
                                <ConfirmPopup />{" "}
                                {permission.includes("cnf_edit") && (
                                    <Button
                                        icon="pi pi-pencil"
                                        onClick={() => {
                                            setVisible(true);
                                            setStatus("update");
                                            reset({
                                                company_name: rowData.company_name,
                                                contact_person_name: rowData.contact_person_name,
                                                designation: rowData.designation,
                                                contact_number: rowData.contact_number,
                                                address: rowData.address,
                                                email: rowData.email,
                                                status: String(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("cnf_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="company_name"
                                    defaultValue={watch("company_name")}
                                    className={`w-full ${
                                        errors.company_name && "p-invalid"
                                    }`}
                                    {...register("company_name", {
                                        required: "Company Name Field is Required",
                                    })}
                                />
                                <label htmlFor="company_name">Company Name*</label>
                            </div>
                            {errors.company_name && (
                                <small
                                    id="company_name-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.company_name.message}
                                </small>
                            )}
                        </div>

                        <div className="col-span-6">
                            <div className="p-float-label mt-6">
                                <InputText
                                    id="contact_person_name"
                                    defaultValue={watch("contact_person_name")}
                                    className={`w-full ${
                                        errors.contact_person_name && "p-invalid"
                                    }`}
                                    {...register("contact_person_name", {
                                        required: "Contact Person Name Field is Required",
                                    })}
                                />
                                <label htmlFor="contact_person_name">Contact Person's Name*</label>
                            </div>
                            {errors.contact_person_name && (
                                <small
                                    id="contact_person_name-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.contact_person_name.message}
                                </small>
                            )}
                        </div>
                        <div className=" col-span-6">
                            <div className="p-float-label mt-6">
                                <InputText
                                    id="designation"
                                    defaultValue={watch("designation")}
                                    className={`w-full ${
                                        errors.designation && "p-invalid"
                                    }`}
                                    {...register("designation")}
                                />
                                <label htmlFor="designation">Designation</label>
                            </div>
                            {errors.designation && (
                                <small
                                    id="designation-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.designation.message}
                                </small>
                            )}
                        </div>
                        <div className=" col-span-6">
                            <div className="p-float-label mt-6">
                                <InputText
                                    id="contact_number"
                                    defaultValue={watch("contact_number")}
                                    className={`w-full ${
                                        errors.contact_number && "p-invalid"
                                    }`}
                                    {...register("contact_number", {
                                        required: "Contact Number Field is Required",
                                    })}
                                />
                                <label htmlFor="contact_number">Contact Number*</label>
                            </div>
                            {errors.contact_number && (
                                <small
                                    id="contact_number-help"
                                    className="p-error block  m-1 "
                                >
                                    {errors.contact_number.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">
                                <Controller
                                    name="status"
                                    control={control}
                                    rules={{
                                        required: "Status field is required",
                                    }}
                                    render={({ field }) => (
                                        <Dropdown
                                            {...field}
                                            optionLabel="name"
                                            optionValue="value"
                                            className="w-full"
                                            options={[
                                                { name: "Active", value: "1" },
                                                { name: "Inactive", value: "0" },
                                            ]}
                                            placeholder="Select a status"
                                        />
                                    )}
                                />
                                <label htmlFor="status">Status*</label>
                            </div>
                            {errors.status && (
                                <small
                                    id="status-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 Cnf;
