import { React, useState, useMemo } 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 { Checkbox } from "primereact/checkbox";

function Role({ auth }) {
    const [status, setStatus] = useState("create");
    const [visible, setVisible] = useState(false);
    const [roles, setroles] = useState([]);
    const [id, setId] = useState();
    const [roleId, setRoleId] = useState();
    const formSubmit = useRef(null);
    const toast = useRef(null);
    const Submitpermisstion = useRef(null);
    const [productStatus, setRoleStatus] = useState(false);
    const [permissionModel, setPermissionModel] = useState(false);
    const [permission, setPermission] = useState([]);
    const [getPermission, SetGetPermission] = useState([]);
    const [permissionSearch, setPermissionSearch] = useState("");
    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: "",
    });

    const formData = watch();

    useEffect(() => {
        axios.get(route("roles.view")).then((response) => {
            setroles(response.data.roles);
            setPermission(response.data.permissions);
        });
    }, []);

    {
        /* 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 rolefooterContent = (
        <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 PermissionfooterContent = (
        <div className="flex justify-end">
            <Button
                label="Cancel"
                icon="pi pi-times"
                onClick={() => {
                    setPermissionModel(false);
                    SetGetPermission([]);
                    reset();
                }}
                className="p-button-text w-13 text-sm"
            />
            <Button
                label="Save"
                type="submit"
                onClick={() => {
                    Submitpermisstion.current.dispatchEvent(
                        new Event("submit", { bubbles: true })
                    );
                }}
                icon="pi pi-check"
                className="p-button-text w-13 text-sm"
            />
        </div>
    );

    // Store Data
    const StoreData = (Role) => {
        axios
            .post(route("role.store"), Role)
            .then((response) => {
                toast.current.show({
                    severity: "info",
                    summary: "Confirmed",
                    detail: response.data.success,
                    life: 3000,
                });
                setroles(response.data.roles);
                reset({
                    name: "",
                });
                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("role.destroy", id))
                    .then((response) => {
                        setroles(response.data.roles);
                        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) => {
        axios
            .put(route("role.update", id), data)
            .then((response) => {
                toast.current.show({
                    severity: "info",
                    summary: "Confirmed",
                    detail: response.data.success,
                    life: 3000,
                });
                setroles(response.data.roles);
                reset({
                    name: "",
                });
                setVisible(false);
            })
            .catch((error) => {
                let errors = error.response.data.errors;
                Object.keys(errors).forEach((field) => {
                    setError(field, {
                        type: "manual",
                        message: errors[field][0],
                    });
                });
            });
    };

    const permissionSet = () => {
        axios
            .post(route("permission.set", roleId), getPermission)
            .then((response) => {
                toast.current.show({
                    severity: "info",
                    summary: "Confirmed",
                    detail: response.data.success,
                    life: 3000,
                });
                setroles(response.data.roles);
                setPermissionModel(false);
                SetGetPermission([]);
                setPermissionSearch("");
            });
    };

    // Filter permissions based on search
    const filteredPermissions = useMemo(() => {
        if (!permissionSearch) return permission;
        const searchLower = permissionSearch.toLowerCase();
        return permission.filter(item => {
            const parentMatch = item.parent.toLowerCase().includes(searchLower);
            const permissionMatch = item.permissions.some(p => 
                p.name.toLowerCase().includes(searchLower)
            );
            return parentMatch || permissionMatch;
        });
    }, [permission, permissionSearch]);

    // Select all permissions
    const selectAllPermissions = () => {
        const allIds = permission.flatMap(item => item.permissions.map(p => p.id));
        SetGetPermission(allIds);
    };

    // Deselect all permissions
    const deselectAllPermissions = () => {
        SetGetPermission([]);
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">Role</h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - Role
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            {/* View Table*/}
            <div className="card">
                <DataTable
                    className="defulattable"
                    value={roles}
                    paginator
                    showGridlines
                    rows={10}
                    dataKey="id"
                    header={TableHeader}
                    filters={filters}
                    emptyMessage="No roles found."
                >
                    <Column
                        field="name"
                        header="Role Name"
                        className="w-[60%]"
                    />

                    <Column
                        header="Action"
                        body={(rowData) => (
                            <>
                                {" "}
                                <ConfirmPopup />{" "}
                                <Button
                                    icon="pi pi-pencil"
                                    onClick={() => {
                                        setVisible(true);
                                        setStatus("update");
                                        reset({
                                            name: rowData.name,
                                        });
                                        rowData.type == "Row Product"
                                            ? setRoleStatus(false)
                                            : setRoleStatus(true);
                                        setId(rowData.id);
                                    }}
                                    className="p-button-rounded p-button-success mr-2 px-3 py-2  w-10 h-10 font-medium"
                                />
                                <Button
                                    icon="bx bxs-universal-access"
                                    data-id={rowData.id}
                                    title="permission"
                                    onClick={() => {
                                        SetGetPermission([]);
                                        rowData.permissions.forEach((item) => {
                                            SetGetPermission((old) => {
                                                return [...old, item.id];
                                            });
                                        });
                                        setPermissionModel(true);
                                        setRoleId(rowData.id);
                                        setPermissionSearch("");
                                    }}
                                    className="p-button-rounded p-button-info px-3 mr-2 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: "450px" }}
                onHide={() => {
                    setVisible(false);
                    reset({
                        name: "",
                    });
                }}
                footer={rolefooterContent}
            >
                <form
                    onSubmit={
                        status == "create"
                            ? handleSubmit(StoreData)
                            : handleSubmit(UpdateData)
                    }
                    ref={formSubmit}
                >
                    <div className="p-float-label mt-6">
                        <InputText
                            id="Role"
                            defaultValue={watch("name")}
                            className={`w-full ${errors.name && "p-invalid"}`}
                            {...register("name", {
                                required: "Name Field is Requerd",
                            })}
                        />
                        <label htmlFor="Role">Role 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>
                    )}
                </form>
            </Dialog>
<Dialog
  header="Manage Permissions"
  visible={permissionModel}
  className="md:w-[80vw] w-full max-w-6xl"
  onHide={() => {
    setPermissionModel(false);
    SetGetPermission([]);
    setPermissionSearch("");
  }}
  footer={PermissionfooterContent}
>
  <form onSubmit={permissionSet} ref={Submitpermisstion}>
    {/* Search and Actions Bar */}
    <div className="mb-4 flex flex-col sm:flex-row gap-3 items-center justify-between sticky top-0 bg-white z-20 pb-3 border-b">
      <div className="relative flex-1 w-full sm:w-auto">
        <i className="pi pi-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
        <InputText
          value={permissionSearch}
          onChange={(e) => setPermissionSearch(e.target.value)}
          placeholder="Search permissions..."
          className="w-full pl-10 pr-4 py-2"
        />
      </div>
      <div className="flex gap-2">
        <Button
          type="button"
          label="Select All"
          icon="pi pi-check-square"
          onClick={selectAllPermissions}
          className="p-button-sm p-button-outlined"
        />
        <Button
          type="button"
          label="Deselect All"
          icon="pi pi-times"
          onClick={deselectAllPermissions}
          className="p-button-sm p-button-outlined"
        />
      </div>
    </div>

    {/* Permissions Count */}
    <div className="mb-3 text-sm text-gray-600">
      <span className="font-semibold">
        {getPermission.length} of {permission.reduce((sum, item) => sum + item.permissions.length, 0)} permissions selected
      </span>
    </div>

    {/* Permissions List */}
    <div className="relative overflow-y-auto max-h-[60vh] pr-2">
      <div className="overflow-x-auto">
        <table className="min-w-full text-sm text-left text-gray-600">
          <thead className="text-xs text-gray-700 uppercase bg-gray-50 sticky top-0 z-10">
            <tr>
              <th scope="col" className="px-4 py-3 w-48 font-semibold">Module</th>
              <th scope="col" className="px-4 py-3 font-semibold">Permissions</th>
            </tr>
          </thead>
          <tbody>
            {filteredPermissions.map((item, idx) => {
              const allChecked =
                item.permissions.length &&
                item.permissions.every((p) => getPermission.includes(p.id));
              const groupIds = item.permissions.map((p) => p.id);

              return (
                <tr
                  className="bg-white border-b last:border-0 hover:bg-gray-50 transition"
                  key={idx}
                >
                  <th
                    scope="row"
                    className="px-4 py-4 font-semibold text-gray-900 whitespace-nowrap capitalize align-top"
                  >
                    {item.parent
                      .replace(/_/g, " ")
                      .replace(/^\w/, (c) => c.toUpperCase())}
                  </th>
                  <td className="px-4 py-4">
                    <div className="flex flex-col sm:flex-row flex-wrap gap-3 items-start sm:items-center">
                      {item.permissions.map((permission) => {
                        const checked = getPermission.includes(permission.id);
                        return (
                          <div
                            className="flex items-center space-x-2 min-w-[140px]"
                            key={permission.id}
                          >
                            <Checkbox
                              inputId={permission.name}
                              value={permission.id}
                              onChange={() => {
                                if (!checked) {
                                  SetGetPermission((prev) => [...prev, permission.id]);
                                } else {
                                  SetGetPermission((prev) =>
                                    prev.filter((id) => id !== permission.id)
                                  );
                                }
                              }}
                              checked={checked}
                              className="permission"
                            />
                            <label
                              htmlFor={permission.name}
                              className="text-gray-700 text-sm select-none cursor-pointer hover:text-blue-600 transition"
                            >
                              {permission.name.replace(/_/g, " ")}
                            </label>
                          </div>
                        );
                      })}
                      {/* Group Select All */}
                      <div className="flex items-center space-x-2 ml-0 sm:ml-4 mt-2 sm:mt-0 border-l pl-3">
                        <Checkbox
                          inputId={`${item.parent}-all`}
                          onChange={() => {
                            if (allChecked) {
                              SetGetPermission((prev) =>
                                prev.filter((id) => !groupIds.includes(id))
                              );
                            } else {
                              SetGetPermission((prev) => {
                                const newIds = groupIds.filter(id => !prev.includes(id));
                                return [...prev, ...newIds];
                              });
                            }
                          }}
                          checked={allChecked}
                          className="permission"
                        />
                        <label
                          htmlFor={`${item.parent}-all`}
                          className="text-gray-700 font-medium text-sm select-none cursor-pointer"
                        >
                          All
                        </label>
                      </div>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {filteredPermissions.length === 0 && (
        <div className="text-center py-8 text-gray-500">
          <i className="pi pi-search text-4xl mb-2" />
          <p>No permissions found matching "{permissionSearch}"</p>
        </div>
      )}
    </div>
  </form>
</Dialog>



        </AuthenticatedLayout>
    );
}

export default Role;
