"use client";
import React, { useState, useEffect } from "react";
import { Eye, Trash2, ChevronDown, ChevronUp, X, Pencil, Plus, Search, CheckSquare, Square, MinusSquare, Archive, Undo2 } from "lucide-react";
import { Role, Permission } from "@/types";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchRoles, createRoleApi, updateRoleApi, deleteRoleApi, toggleArchiveRoleApi } from "@/store/slices/roleSlice";
import DataTable from "react-data-table-component";
import { useModal } from "@/hooks/useModal";
import { Modal } from "@/components/common/modal";
import axiosInstance from "@/lib/axios";
import { useForm } from "react-hook-form";
import { toast } from "react-toastify";

const AVAILABLE_MODULES = [
  "dashboard",
  "user",
  "role",
  "permission",
  "client",
  "project",
  "milestone",
  "sprint",
  "task",
  "taskUpdate",
  "taskTimeLog",
  "costing",
  "notification",
  "notificationTemplate",
  "emailLog",
  "job",
  "report",
  "activityLog",
  "dailyReport",
  "leave",
  "calendar",
  "symbol"
];

const DEFAULT_PERMISSION = (moduleName: string): Permission => ({
  module: moduleName,
  read: false,
  create: false,
  update: false,
  delete: false
});

const formatModuleName = (name: string) => {
  return name.replace(/([A-Z])/g, ' $1').replace(/^./, (str) => str.toUpperCase());
};

export default function RolesManagementPage() {
  const dispatch = useAppDispatch();
  const { roles, isLoading, total } = useAppSelector((state) => state.roles);

  const [allPermissions, setAllPermissions] = useState<any[]>([]);

  const { isOpen, openModal, closeModal } = useModal();
  const [formData, setFormData] = useState<Partial<Role>>({});

  const { register, handleSubmit, reset, setValue, formState: { errors } } = useForm<{ name: string }>();

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [roleToDelete, setRoleToDelete] = useState<Role | null>(null);

  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [selectedRole, setSelectedRole] = useState<Role | null>(null);

  const [searchText, setSearchText] = useState("");
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  const [resetPaginationToggle, setResetPaginationToggle] = useState(false);
  const [expandedModules, setExpandedModules] = useState<string[]>([]);
  const [isArchiveView, setIsArchiveView] = useState(false);

  const [isArchiveModalOpen, setIsArchiveModalOpen] = useState(false);
  const [isUndoArchiveModalOpen, setIsUndoArchiveModalOpen] = useState(false);
  const [roleToArchive, setRoleToArchive] = useState<Role | null>(null);
  const [roleToUndoArchive, setRoleToUndoArchive] = useState<Role | null>(null);

  useEffect(() => {
    axiosInstance.get('/api/permissions?limit=100').then((res) => {
      if (res.data?.data?.permissions) {
        setAllPermissions(res.data.data.permissions);
      }
    }).catch(console.error);
  }, []);

  useEffect(() => {
    const timer = setTimeout(() => {
      dispatch(fetchRoles({ page: currentPage, limit: rowsPerPage, search: searchText, archived: isArchiveView }));
    }, 500);
    return () => clearTimeout(timer);
  }, [dispatch, currentPage, rowsPerPage, searchText, isArchiveView]);

  const toggleModuleAccordion = (moduleName: string) => {
    setExpandedModules(prev =>
      prev.includes(moduleName)
        ? prev.filter(m => m !== moduleName)
        : [...prev, moduleName]
    );
  };

  const handleOpenModal = (role?: Role) => {
    if (role) {
      const mergedPermissions = AVAILABLE_MODULES.map(moduleName => {
        const existing = role.permissions?.find(p => p.module === moduleName);
        return existing ? { ...existing } : DEFAULT_PERMISSION(moduleName);
      });

      setFormData({
        ...JSON.parse(JSON.stringify(role)),
        permissions: mergedPermissions
      });
      setValue('name', role.name);
      setExpandedModules(role.permissions.filter(p => p.read || p.create || p.update || p.delete).map(p => p.module));
    } else {
      setFormData({
        name: "",
        permissions: AVAILABLE_MODULES.map(DEFAULT_PERMISSION)
      });
      reset({ name: '' });
      setExpandedModules(AVAILABLE_MODULES.slice(0, 5));
    }
    openModal();
  };

  const handleCloseModal = () => {
    setFormData({});
    reset({ name: '' });
    setExpandedModules([]);
    closeModal();
  };

  const handlePermissionChange = (moduleName: string, action: keyof Omit<Permission, 'module'>) => {
    setFormData(prev => {
      const currentPermissions = prev.permissions || AVAILABLE_MODULES.map(DEFAULT_PERMISSION);

      // Ensure all modules exist
      const allModules = AVAILABLE_MODULES.map(m => {
        const existing = currentPermissions.find(p => p.module === m);
        return existing ? { ...existing } : DEFAULT_PERMISSION(m);
      });

      const updatedPermissions = allModules.map(p => {
        if (p.module === moduleName) {
          return { ...p, [action]: !p[action] };
        }
        return p;
      });
      return { ...prev, permissions: updatedPermissions };
    });
  };

  const handleSelectAllModule = (moduleName: string, selectAll: boolean) => {
    setFormData(prev => {
      const currentPermissions = prev.permissions || AVAILABLE_MODULES.map(DEFAULT_PERMISSION);

      const allModules = AVAILABLE_MODULES.map(m => {
        const existing = currentPermissions.find(p => p.module === m);
        return existing ? { ...existing } : DEFAULT_PERMISSION(m);
      });

      const updatedPermissions = allModules.map(p => {
        if (p.module === moduleName) {
          return { ...p, read: selectAll, create: selectAll, update: selectAll, delete: selectAll };
        }
        return p;
      });
      return { ...prev, permissions: updatedPermissions };
    });
  };

  const onSaveRole = (data: { name: string }) => {
    // Map frontend grouped permissions to actual permission CUIDs
    const selectedIds: string[] = [];
    (formData.permissions || []).forEach(p => {
      if (p.read) {
        const perm = allPermissions.find(ap => ap.module === p.module && ap.action === 'view');
        if (perm) selectedIds.push(perm.id);
      }
      if (p.create) {
        const perm = allPermissions.find(ap => ap.module === p.module && ap.action === 'create');
        if (perm) selectedIds.push(perm.id);
      }
      if (p.update) {
        const perm = allPermissions.find(ap => ap.module === p.module && ap.action === 'update');
        if (perm) selectedIds.push(perm.id);
      }
      if (p.delete) {
        const perm = allPermissions.find(ap => ap.module === p.module && ap.action === 'delete');
        if (perm) selectedIds.push(perm.id);
      }
    });

    if (formData.id) {
      dispatch(updateRoleApi({ id: formData.id, data: { name: data.name, permissionIds: selectedIds } })).then((resultAction: any) => {
        if (updateRoleApi.fulfilled.match(resultAction)) {
          toast.success("Role updated successfully");
          dispatch(fetchRoles({ page: currentPage, limit: rowsPerPage, search: searchText }));
          handleCloseModal();
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to update role");
        }
      });
    } else {
      dispatch(createRoleApi({ name: data.name, permissionIds: selectedIds })).then((resultAction: any) => {
        if (createRoleApi.fulfilled.match(resultAction)) {
          toast.success("Role created successfully");
          dispatch(fetchRoles({ page: currentPage, limit: rowsPerPage, search: searchText }));
          handleCloseModal();
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to create role");
        }
      });
    }
  };

  const handleDeleteRole = (role: Role) => {
    setRoleToDelete(role);
    setIsDeleteModalOpen(true);
  };

  const closeDeleteModal = () => {
    setIsDeleteModalOpen(false);
    setRoleToDelete(null);
  };

  const handleViewRole = (role: Role) => {
    setSelectedRole(role);
    setIsViewModalOpen(true);
  };

  const closeViewModal = () => {
    setIsViewModalOpen(false);
    setSelectedRole(null);
  };

  const confirmDelete = () => {
    if (roleToDelete) {
      dispatch(deleteRoleApi(roleToDelete.id)).then((resultAction: any) => {
        if (deleteRoleApi.fulfilled.match(resultAction)) {
          toast.success("Role deleted successfully");
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to delete role");
        }
      });
    }
    closeDeleteModal();
  };

  const handleArchiveRole = (role: Role) => {
    setRoleToArchive(role);
    setIsArchiveModalOpen(true);
  };

  const handleUndoArchiveRole = (role: Role) => {
    setRoleToUndoArchive(role);
    setIsUndoArchiveModalOpen(true);
  };

  const confirmArchive = () => {
    if (roleToArchive) {
      dispatch(toggleArchiveRoleApi(roleToArchive.id)).then((resultAction: any) => {
        if (toggleArchiveRoleApi.fulfilled.match(resultAction)) {
          toast.success("Role archived successfully");
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to archive role");
        }
      });
    }
    closeArchiveModal();
  };

  const confirmUndoArchive = () => {
    if (roleToUndoArchive) {
      dispatch(toggleArchiveRoleApi(roleToUndoArchive.id)).then((resultAction: any) => {
        if (toggleArchiveRoleApi.fulfilled.match(resultAction)) {
          toast.success("Role un-archived successfully");
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to un-archive role");
        }
      });
    }
    closeUndoArchiveModal();
  };

  const closeArchiveModal = () => {
    setIsArchiveModalOpen(false);
    setRoleToArchive(null);
  };

  const closeUndoArchiveModal = () => {
    setIsUndoArchiveModalOpen(false);
    setRoleToUndoArchive(null);
  };

  const columns = [
    {
      name: 'S.No',
      width: '80px',
      cell: (row: Role, index: number) => (
        <div data-th="S.No" className="mobile-cell">
          <span className="text-gray-500 font-medium">
            {(currentPage - 1) * rowsPerPage + index + 1}
          </span>
        </div>
      ),
    },
    {
      name: 'Role Name',
      selector: (row: Role) => row.name,
      sortable: true,
      minWidth: "120px",
      cell: (row: Role) => <div data-th="Role Name" className="mobile-cell"><span className="md:font-medium text-gray-600 md:text-gray-900 capitalize">{row.name}</span></div>
    },
    {
      name: 'Permissions Granted',
      minWidth: "140px",
      cell: (row: Role) => {
        const totalGranted = (row.permissions || []).reduce((acc, p) => {
          let count = 0;
          if (p.read) count++;
          if (p.create) count++;
          if (p.update) count++;
          if (p.delete) count++;
          return acc + count;
        }, 0);
        return <div data-th="Permissions Granted" className="mobile-cell"><span className="text-gray-600">{totalGranted} permissions</span></div>;
      }
    },
    {
      name: 'Action',
      center: true,
      minWidth: "160px",
      cell: (row: Role) => (
        <div data-th="Action" className="mobile-cell w-full sm:w-auto">
          <div className="flex justify-start sm:justify-center gap-2">
            {!isArchiveView ? (
              <>
                <button className="w-8 h-8 rounded-md bg-brand-950/10 flex items-center justify-center text-brand-950 hover:bg-brand-950/20 transition-colors"
                  onClick={() => handleViewRole(row)}
                >
                  <Eye size={18} />
                </button>

                <span
                  className="cursor-pointer w-8 h-8 rounded-md bg-yellow-500/30 flex items-center justify-center text-[#c17916]"
                  onClick={() => handleOpenModal(row)}
                >
                  <Pencil size={16} />
                </span>

                {/* <button
                  className="w-8 h-8 rounded-md bg-gray-500/10 flex items-center justify-center text-gray-600 hover:bg-gray-500/20 transition-colors"
                  onClick={() => handleArchiveRole(row)}
                  title="Archive Role"
                >
                  <Archive size={16} />
                </button> */}

                <button className="w-8 h-8 rounded-md bg-red-500/10 flex items-center justify-center text-red-500 hover:bg-red-500/20 transition-colors"
                  onClick={() => handleDeleteRole(row)}
                >
                  <Trash2 size={16} />
                </button>


              </>
            ) : (
              <button
                className="w-8 h-8 rounded-md bg-gray-500/10 flex items-center justify-center text-gray-600 hover:bg-gray-500/20 transition-colors"
                onClick={() => handleUndoArchiveRole(row)}
                title="Un-Archive Role"
              >
                <Undo2 size={16} />
              </button>
            )}
          </div>
        </div>
      )
    }
  ];

  const filteredRoles = roles;

  return (
    <div className="min-h-screen">
      <div className="mx-auto max-w-[1500px] space-y-6">
        <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
          <div className="flex flex-col gap-2">
            <h1 className="text-xl lg:text-2xl font-medium text-brand-950">Role Management</h1>
            {/* <div className="flex items-center gap-1 bg-gray-100 p-1 rounded-lg w-max">
              <button
                onClick={() => setIsArchiveView(false)}
                className={`px-4 py-2 text-sm font-medium rounded-md transition-all ${!isArchiveView ? 'bg-white text-brand-950 shadow-theme-xs' : 'text-gray-500 hover:text-gray-700'
                  }`}
              >
                Active
              </button>
              <button
                onClick={() => setIsArchiveView(true)}
                className={`px-4 py-2 text-sm font-medium rounded-md transition-all ${isArchiveView ? 'bg-white text-brand-950 shadow-theme-xs' : 'text-gray-500 hover:text-gray-700'
                  }`}
              >
                Archived
              </button>
            </div> */}
          </div>
          <button
            onClick={() => handleOpenModal()}
            className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-2.5 lg:px-4 py-2.5 lg:py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500"
          >
            <svg className="w-5 h-5 fill-current" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
              <path fillRule="evenodd" clipRule="evenodd" d="M9 17a1 1 0 102 0v-6h6a1 1 0 100-2h-6V3a1 1 0 10-2 0v6H3a1 1 0 000 2h6v6z" />
            </svg>
            <span className="hidden lg:inline-block">Create Role</span>
          </button>
        </div>

        {/* Roles Table */}
        <div className="rounded-xl bg-white p-6 shadow-theme-md">
          <div className="md:border border-gray-200 rounded-lg overflow-hidden">
            <div className="flex items-center justify-between md:border-b md:px-4 pb-4 md:py-4">
              <div className="hidden md:flex items-center gap-2">
                <span className="text-sm font-normal text-gray-500 block">Show</span>
                <div className="relative">
                  <select
                    value={rowsPerPage}
                    onChange={(e) => {
                      setRowsPerPage(Number(e.target.value));
                      setCurrentPage(1);
                      setResetPaginationToggle(!resetPaginationToggle);
                    }}
                    className="w-full rounded-lg border appearance-none px-3 py-2 pr-8 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 border-gray-300 outline-none"
                  >
                    <option value={10}>10</option>
                    <option value={20}>20</option>
                    <option value={30}>30</option>
                    <option value={50}>50</option>
                  </select>
                  <span className="absolute text-gray-500 -translate-y-1/2 pointer-events-none right-2 top-1/2">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none">
                      <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M4.792 7.396 10 12.604l5.208-5.208"></path>
                    </svg>
                  </span>
                </div>
                <span className="text-sm font-normal text-gray-500">entries</span>
              </div>
              <div className="flex items-center gap-4 w-full sm:w-auto">
                <div className="relative block w-full sm:w-auto">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
                  <input
                    type="text"
                    placeholder="Search roles..."
                    value={searchText}
                    onChange={(e) => {
                      setSearchText(e.target.value);
                      setCurrentPage(1);
                    }}
                    className="h-11 w-full rounded-lg border appearance-none py-2.5 pl-9 pr-4 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 border-gray-300 outline-none"
                  />
                </div>
              </div>
            </div>

            <div className="overflow-x-auto">
              <DataTable
                key={`table-${rowsPerPage}`}
                columns={columns}
                data={filteredRoles}
                progressPending={isLoading}
                pagination
                paginationResetDefaultPage={resetPaginationToggle}
                paginationServer
                paginationTotalRows={total}
                paginationPerPage={rowsPerPage}
                onChangeRowsPerPage={(currentRowsPerPage) => {
                  setRowsPerPage(currentRowsPerPage);
                  setCurrentPage(1);
                }}
                onChangePage={(page) => setCurrentPage(page)}
                paginationComponentOptions={{ noRowsPerPage: true }}
                highlightOnHover
                customStyles={{
                  headRow: {
                    style: {
                      backgroundColor: '#ffffff',
                      color: '#1E293B',
                      fontWeight: 600,
                      fontSize: '14px',
                      borderBottom: '1px solid #F1F5F9',
                    },
                  },
                  rows: {
                    style: {
                      fontSize: '14px',
                      color: '#475569',
                      minHeight: '60px',
                      borderBottom: '1px solid #F1F5F9',
                    },
                  },
                }}
              />
            </div>
          </div>
        </div>

        {/* Add/Edit Modal */}
        <Modal isOpen={isOpen} onClose={handleCloseModal} className="max-w-[700px] m-4">
          <div className="no-scrollbar relative w-full max-w-[700px] rounded-3xl bg-white p-4 lg:p-8">
            <div className="px-2 pr-14 mb-6 lg:mb-7">
              <h4 className="text-xl lg:text-2xl font-semibold text-brand-950">
                {formData.id ? "Edit Role" : "Create Role"}
              </h4>
            </div>

            <form onSubmit={handleSubmit(onSaveRole)} className="px-2 space-y-6 lg:space-y-5">
              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700">Role Name</label>
                <input
                  type="text"
                  {...register('name', { required: 'Role Name is required' })}
                  className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.name ? 'border-red-500' : 'border-gray-300'}`}
                  placeholder="e.g. admin"
                />
                {errors.name && <p className="mt-1.5 text-xs text-red-500">{errors.name.message}</p>}
              </div>

              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700">Permissions</label>
                <div className="space-y-3">
                  {(formData.permissions || AVAILABLE_MODULES.map(DEFAULT_PERMISSION)).map((perm, index) => {
                    const isExpanded = expandedModules.includes(perm.module);
                    const allSelected = perm.read && perm.create && perm.update && perm.delete;
                    const someSelected = perm.read || perm.create || perm.update || perm.delete;

                    return (
                      <div key={perm.module} className="border border-gray-200 rounded-xl overflow-hidden transition-all duration-200 bg-gray-50/50">
                        <div
                          className="px-4 py-3 flex md:items-center justify-between cursor-pointer hover:bg-gray-100 transition-colors flex-col md:flex-row gap-3 md:gap-0"
                          onClick={() => toggleModuleAccordion(perm.module)}
                        >
                          <div className="flex items-center gap-3">
                            <h5 className="font-medium text-gray-800 text-sm">{formatModuleName(perm.module)}</h5>
                          </div>
                          <div className="flex items-center gap-4 justify-between md:justify-end w-full md:w-auto">
                            <button
                              type="button"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleSelectAllModule(perm.module, !allSelected);
                              }}
                              className="text-gray-500 hover:text-brand-950 transition-colors focus:outline-none flex items-center gap-1.5"
                              title={allSelected ? "Deselect All" : "Select All"}
                            >
                              {allSelected ? <CheckSquare size={16} className="text-brand-950" /> : someSelected ? <MinusSquare size={16} className="text-brand-950 opacity-70" /> : <Square size={16} />}
                              <span className="text-sm">{allSelected ? "All" : "Select All"}</span>
                            </button>
                            <span className="text-gray-400">
                              {isExpanded ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
                            </span>
                          </div>
                        </div>

                        {isExpanded && (
                          <div className="px-5 py-4 bg-white border-t border-gray-100 grid grid-cols-2 gap-y-4 gap-x-6">
                            {allPermissions.some(ap => ap.module === perm.module && ap.action === 'view') && (
                              <label className="flex items-center gap-3 cursor-pointer group">
                                <div className="relative flex items-center">
                                  <input
                                    type="checkbox"
                                    checked={perm.read}
                                    onChange={() => handlePermissionChange(perm.module, 'read')}
                                    className="peer h-5 w-5 cursor-pointer appearance-none rounded border border-gray-300 checked:border-brand-950 checked:bg-brand-950 transition-all"
                                  />
                                  <span className="absolute text-white opacity-0 peer-checked:opacity-100 top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 pointer-events-none">
                                    <svg xmlns="http://www.w3.org/2000/svg" className="h-3.5 w-3.5" viewBox="0 0 20 20" fill="currentColor">
                                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                                    </svg>
                                  </span>
                                </div>
                                <span className="text-sm text-gray-700 group-hover:text-gray-900">view</span>
                              </label>
                            )}

                            {allPermissions.some(ap => ap.module === perm.module && ap.action === 'create') && (
                              <label className="flex items-center gap-3 cursor-pointer group">
                                <div className="relative flex items-center">
                                  <input
                                    type="checkbox"
                                    checked={perm.create}
                                    onChange={() => handlePermissionChange(perm.module, 'create')}
                                    className="peer h-5 w-5 cursor-pointer appearance-none rounded border border-gray-300 checked:border-brand-950 checked:bg-brand-950 transition-all"
                                  />
                                  <span className="absolute text-white opacity-0 peer-checked:opacity-100 top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 pointer-events-none">
                                    <svg xmlns="http://www.w3.org/2000/svg" className="h-3.5 w-3.5" viewBox="0 0 20 20" fill="currentColor">
                                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                                    </svg>
                                  </span>
                                </div>
                                <span className="text-sm text-gray-700 group-hover:text-gray-900">create</span>
                              </label>
                            )}

                            {allPermissions.some(ap => ap.module === perm.module && ap.action === 'update') && (
                              <label className="flex items-center gap-3 cursor-pointer group">
                                <div className="relative flex items-center">
                                  <input
                                    type="checkbox"
                                    checked={perm.update}
                                    onChange={() => handlePermissionChange(perm.module, 'update')}
                                    className="peer h-5 w-5 cursor-pointer appearance-none rounded border border-gray-300 checked:border-brand-950 checked:bg-brand-950 transition-all"
                                  />
                                  <span className="absolute text-white opacity-0 peer-checked:opacity-100 top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 pointer-events-none">
                                    <svg xmlns="http://www.w3.org/2000/svg" className="h-3.5 w-3.5" viewBox="0 0 20 20" fill="currentColor">
                                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                                    </svg>
                                  </span>
                                </div>
                                <span className="text-sm text-gray-700 group-hover:text-gray-900">update</span>
                              </label>
                            )}

                            {allPermissions.some(ap => ap.module === perm.module && ap.action === 'delete') && (
                              <label className="flex items-center gap-3 cursor-pointer group">
                                <div className="relative flex items-center">
                                  <input
                                    type="checkbox"
                                    checked={perm.delete}
                                    onChange={() => handlePermissionChange(perm.module, 'delete')}
                                    className="peer h-5 w-5 cursor-pointer appearance-none rounded border border-gray-300 checked:border-brand-950 checked:bg-brand-950 transition-all"
                                  />
                                  <span className="absolute text-white opacity-0 peer-checked:opacity-100 top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 pointer-events-none">
                                    <svg xmlns="http://www.w3.org/2000/svg" className="h-3.5 w-3.5" viewBox="0 0 20 20" fill="currentColor">
                                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                                    </svg>
                                  </span>
                                </div>
                                <span className="text-sm text-gray-700 group-hover:text-gray-900">delete</span>
                              </label>
                            )}

                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>

              <div className="flex items-center gap-3 mt-6 lg:justify-end">
                <button
                  type="button"
                  onClick={handleCloseModal}
                  className="flex items-center justify-center gap-2 rounded-lg border border-gray-300 bg-[#f7f8fa] px-4 py-3 text-sm font-medium text-gray-700 hover:bg-gray-100 transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-4 py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500 disabled:bg-yellow-500 disabled:opacity-50"
                >
                  {formData.id ? "Update" : "Create"}
                </button>
              </div>
            </form>
          </div>
        </Modal>

        {/* Delete Role Modal */}
        <Modal isOpen={isDeleteModalOpen} onClose={closeDeleteModal} showCloseButton={false} className="max-w-[450px] m-4">
          <div className="p-8">
            <div className="text-center">
              <h3 className="text-xl font-semibold text-brand-950 mb-4">Confirm Delete</h3>
              <p className="text-sm text-gray-500 mb-8 leading-relaxed">
                Are you sure you want to delete the role <span className="font-semibold text-gray-800">{roleToDelete?.name}</span>?
              </p>
            </div>
            <div className="flex justify-center gap-3">
              <button onClick={closeDeleteModal} className="px-5 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-xl hover:bg-gray-50 transition-colors">
                Cancel
              </button>
              <button onClick={confirmDelete} className="px-5 py-2.5 text-sm font-medium text-white bg-brand-950 rounded-xl hover:text-brand-950 hover:bg-yellow-500 transition-colors">
                Delete
              </button>
            </div>
          </div>
        </Modal>

        {/* Archive Role Modal */}
        {/* <Modal isOpen={isArchiveModalOpen} onClose={closeArchiveModal} showCloseButton={false} className="max-w-[450px] m-4">
          <div className="p-8">
            <div className="text-center">
              <h3 className="text-xl font-semibold text-brand-950 mb-4">Archive Role</h3>
              <p className="text-sm text-gray-500 mb-8 leading-relaxed">
                Are you sure you want to archive the role <span className="font-semibold text-gray-800">{roleToArchive?.name}</span>?
              </p>
            </div>
            <div className="flex justify-center gap-3">
              <button onClick={closeArchiveModal} className="px-5 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-xl hover:bg-gray-50 transition-colors">
                Cancel
              </button>
              <button onClick={confirmArchive} className="px-5 py-2.5 text-sm font-medium text-white bg-brand-950 rounded-xl hover:text-brand-950 hover:bg-yellow-500 transition-colors">
                Archive
              </button>
            </div>
          </div>
        </Modal> */}

        {/* Undo Archive Role Modal */}
        {/* <Modal isOpen={isUndoArchiveModalOpen} onClose={closeUndoArchiveModal} showCloseButton={false} className="max-w-[450px] m-4">
          <div className="p-8">
            <div className="text-center">
              <h3 className="text-xl font-semibold text-brand-950 mb-4">Un-Archive Role</h3>
              <p className="text-sm text-gray-500 mb-8 leading-relaxed">
                Are you sure you want to un-archive the role <span className="font-semibold text-gray-800">{roleToUndoArchive?.name}</span>?
              </p>
            </div>
            <div className="flex justify-center gap-3">
              <button onClick={closeUndoArchiveModal} className="px-5 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-xl hover:bg-gray-50 transition-colors">
                Cancel
              </button>
              <button onClick={confirmUndoArchive} className="px-5 py-2.5 text-sm font-medium text-white bg-brand-950 rounded-xl hover:text-brand-950 hover:bg-yellow-500 transition-colors">
                Un-Archive
              </button>
            </div>
          </div>
        </Modal> */}

        {/* View Role Modal */}
        {selectedRole && (
          <Modal isOpen={isViewModalOpen} onClose={closeViewModal} className="max-w-[700px] m-4">
            <div className="no-scrollbar relative w-full max-w-[700px] rounded-3xl bg-white p-4 lg:p-8">
              <div className="px-2 pr-14 mb-6">
                <h4 className="mb-2 text-xl lg:text-2xl font-semibold text-brand-950 capitalize">
                  {selectedRole.name} Role
                </h4>
                {/* <p className="text-sm text-gray-500">
                  ID: {selectedRole.id}
                </p> */}
              </div>

              <div className="px-2 space-y-6 lg:space-y-5">
                <div>
                  <h5 className="mb-4 text-lg font-medium text-gray-800">Granted Permissions</h5>
                  <div className="bg-white border border-gray-200 rounded-lg p-4">
                    {selectedRole.permissions.map(p => {
                      const perms = [];
                      if (p.read) perms.push("View");
                      if (p.create) perms.push("Create");
                      if (p.update) perms.push("Update");
                      if (p.delete) perms.push("Delete");
                      if (perms.length === 0) return null;
                      return (
                        <div key={p.module} className="flex flex-col sm:flex-row sm:items-center justify-between py-2.5 border-b border-gray-100 last:border-0">
                          <p className="text-sm font-medium text-gray-800">{p.module}</p>
                          <div className="flex gap-2 mt-1 sm:mt-0 flex-wrap">
                            {perms.map(perm => (
                              <span key={perm} className="px-2 py-1 text-xs font-normal bg-brand-950/10 text-brand-950 rounded-md">
                                {perm}
                              </span>
                            ))}
                          </div>
                        </div>
                      );
                    })}
                    {selectedRole.permissions.every(p => !p.read && !p.create && !p.update && !p.delete) && (
                      <p className="text-sm text-gray-500 py-2">No permissions granted.</p>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </Modal>
        )}
      </div>
    </div>
  );
}
