import React, { useState, useEffect, useRef, 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 { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import { useForm, Controller } from "react-hook-form";
import axios from "axios";
import { Toast } from "primereact/toast";
import { authUser } from "@/Components/AuthProvider";
import { FilterMatchMode } from "primereact/api";
import { Dropdown } from "primereact/dropdown";

function Designation({ auth }) {
    const { permission } = useContext(authUser);
    const [status, setStatus] = useState("create");
    const [visible, setVisible] = useState(false);
    const [designations, setDesignations] = useState([]);
    const [id, setId] = useState(null);
    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,
        handleSubmit,
        formState: { errors },
        setValue,
        watch,
        reset,
        control,
        setError,
    } = useForm({
        name: "",
        description: "",
        status: "1",
    });

    useEffect(() => {
        loadDesignations();
    }, []);

    const loadDesignations = () => {
        axios
            .get(route("designation.view"))
            .then((response) => {
                setDesignations(response.data.designations || []);
            })
            .catch((error) => {
                console.error("Error loading designations:", error);
            });
    };

    const onGlobalFilterChange = (e) => {
        const value = e.target.value;
        let _filters = { ...filters };
        _filters["global"].value = value;
        setFilters(_filters);
        setGlobalFilterValue(value);
    };

    const TableHeader = () => {
        return (
            <div
                className={`w-100% flex ${
                    permission.includes("designation_create")
                        ? "justify-between"
                        : "justify-end"
                } `}
            >
                {permission.includes("designation_create") && (
                    <Button
                        type="button"
                        icon={<span className="pi pi-plus text-sm pr-1" />}
                        label="Add Designation"
                        onClick={() => {
                            setVisible(true);
                            setStatus("create");
                            reset({
                                name: "",
                                description: "",
                                status: "1",
                            });
                            setId(null);
                        }}
                        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>
        );
    };

    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>
    );

    const StoreData = (data) => {
        axios
            .post(route("designation.store"), data)
            .then((response) => {
                setDesignations(response.data.designations || []);
                toast.current.show({
                    severity: "success",
                    summary: "Success",
                    detail: response.data.success,
                    life: 3000,
                });
                reset();
                setVisible(false);
            })
            .catch((error) => {
                const errors = error.response?.data?.errors;
                if (errors) {
                    Object.keys(errors).forEach((field) => {
                        setError(field, {
                            type: "manual",
                            message: errors[field][0],
                        });
                    });
                }
            });
    };

    const UpdateData = (data) => {
        axios
            .put(route("designation.update", id), data)
            .then((response) => {
                setDesignations(response.data.designations || []);
                toast.current.show({
                    severity: "success",
                    summary: "Success",
                    detail: response.data.success,
                    life: 3000,
                });
                reset();
                setVisible(false);
                setId(null);
            })
            .catch((error) => {
                const errors = error.response?.data?.errors;
                if (errors) {
                    Object.keys(errors).forEach((field) => {
                        setError(field, {
                            type: "manual",
                            message: errors[field][0],
                        });
                    });
                }
            });
    };

    const handelDelete = (e) => {
        const designationId = e.currentTarget.getAttribute("data-id");
        confirmPopup({
            target: e.currentTarget,
            message: "Do you want to delete this designation?",
            icon: "pi pi-info-circle",
            acceptClassName: "p-button-danger",
            accept() {
                axios
                    .delete(route("designation.destroy", designationId))
                    .then((response) => {
                        setDesignations(response.data.designations || []);
                        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?.message ||
                                "Error deleting designation",
                            life: 3000,
                        });
                    });
            },
            reject() {
                toast.current.show({
                    severity: "warn",
                    summary: "Rejected",
                    detail: "You have rejected",
                    life: 3000,
                });
            },
        });
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Designations
                    </h2>
                    <p className="text-skin-sub-header font-semibold text-xs">
                        Home - Designations
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            <div className="card">
                <DataTable
                    className="defulattable"
                    value={designations}
                    paginator
                    showGridlines
                    rows={10}
                    dataKey="id"
                    header={TableHeader}
                    filters={filters}
                    emptyMessage="No designation found."
                    paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown"
                    rowsPerPageOptions={[10, 25, 50, 100]}
                >
                    <Column field="name" header="Name" sortable />
                    <Column field="description" header="Description" />
                    <Column
                        field="status"
                        header="Status"
                        body={(data) => (
                            <span
                                className={
                                    data.status === "1"
                                        ? "text-green-600 font-semibold"
                                        : "text-red-600 font-semibold"
                                }
                            >
                                {data.status === "1" ? "Active" : "Inactive"}
                            </span>
                        )}
                        style={{ minWidth: "8rem" }}
                    />
                    <Column
                        header="Action"
                        body={(rowData) => (
                            <>
                                <ConfirmPopup />
                                {permission.includes("designation_edit") && (
                                    <Button
                                        icon="pi pi-pencil"
                                        onClick={() => {
                                            setVisible(true);
                                            setStatus("update");
                                            setId(rowData.id);
                                            reset({
                                                name: rowData.name,
                                                description: rowData.description,
                                                status: rowData.status,
                                            });
                                        }}
                                        className="p-button-rounded p-button-success mr-2 px-3 py-2 w-10 h-10 font-medium"
                                    />
                                )}
                                {permission.includes("designation_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"
                                    />
                                )}
                            </>
                        )}
                        bodyClassName="text-center"
                        style={{ minWidth: "10rem" }}
                    />
                </DataTable>
            </div>

            <Dialog
                header={() =>
                    status === "create" ? "Create Designation" : "Update Designation"
                }
                visible={visible}
                className="md:w-[40vw] w-full"
                onHide={() => {
                    setVisible(false);
                    reset();
                    setId(null);
                }}
                footer={footerContent}
            >
                <form
                    onSubmit={
                        status === "create"
                            ? handleSubmit(StoreData)
                            : handleSubmit(UpdateData)
                    }
                    ref={formSubmit}
                >
                    <div className="grid grid-cols-12 gap-2">
                        <div className="col-span-12">
                            <div className="p-float-label mt-6">
                                <InputText
                                    id="name"
                                    defaultValue={watch("name")}
                                    className={`w-full ${
                                        errors.name && "p-invalid"
                                    }`}
                                    {...register("name", {
                                        required: "Name is required",
                                    })}
                                />
                                <label htmlFor="name">Designation Name*</label>
                            </div>
                            {errors.name && (
                                <small className="p-error block m-1">
                                    {errors.name.message}
                                </small>
                            )}
                        </div>

                        <div className="col-span-12">
                            <div className="p-float-label mt-6">
                                <InputText
                                    id="description"
                                    defaultValue={watch("description")}
                                    className="w-full"
                                    {...register("description")}
                                />
                                <label htmlFor="description">Description</label>
                            </div>
                        </div>

                        <div className="col-span-12">
                            <div className="p-float-label mt-6">
                                <Controller
                                    name="status"
                                    control={control}
                                    rules={{
                                        required: "Status is required",
                                    }}
                                    render={({ field }) => (
                                        <Dropdown
                                            {...field}
                                            optionLabel="name"
                                            optionValue="id"
                                            className={`w-full ${
                                                errors.status && "p-invalid"
                                            }`}
                                            options={[
                                                { name: "Active", id: "1" },
                                                { name: "Inactive", id: "0" },
                                            ]}
                                            placeholder="Select status"
                                        />
                                    )}
                                />
                                <label htmlFor="status">Status*</label>
                            </div>
                            {errors.status && (
                                <small className="p-error block m-1">
                                    {errors.status.message}
                                </small>
                            )}
                        </div>
                    </div>
                </form>
            </Dialog>
        </AuthenticatedLayout>
    );
}

export default Designation;
