import{c as L,j as e,t as f,r as g,L as D}from"./index-DiwDH9aE.js";import{A as G,D as V}from"./Alert-Cq7mXBD-.js";import{S as T,P as q,M as B}from"./Modal-tocKJOcW.js";import{C as H,T as K}from"./ConfirmModal-mJDwNEXB.js";import{F as W}from"./FullScreenModal-DHvf5XmH.js";import{u as X,a as J,h as Q}from"./handleFormErrors-CaWHVJ6Q.js";import{o as U,b as Y,s as F,I as z,E as O}from"./schemas-BwNPnT22.js";import{R as Z}from"./RadioGroup-qqSrRVM3.js";import{B as $}from"./Button-Cu8l7rID.js";import{u as A}from"./useRoles-B8PPbxwm.js";import{X as ee}from"./x-D4vgwdOf.js";import{C as R}from"./Can-w-eLoK-Q.js";import{u as se}from"./usePermissions-Bd6Y6GNw.js";import{S as re}from"./shield-Beyfz6Tk.js";import{S as ae}from"./BaseService-B6zq4ARl.js";import"./search-h1vL1q1e.js";import"./triangle-alert-BxjRBxgM.js";import"./circle-check-big-CvbUXdGb.js";import"./endpoints-BUXROgJ9.js";import"./multiUserApiClient-CKPzIhIr.js";/**
 * @license lucide-react v0.544.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const te=[["path",{d:"M12.4 2.7a2.5 2.5 0 0 1 3.4 0l5.5 5.5a2.5 2.5 0 0 1 0 3.4l-3.7 3.7a2.5 2.5 0 0 1-3.4 0L8.7 9.8a2.5 2.5 0 0 1 0-3.4z",key:"165ttr"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"m9.4 10.6-6.814 6.814A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814",key:"1ubxi2"}]],oe=L("key-square",te);/**
 * @license lucide-react v0.544.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const le=[["path",{d:"M5 12h14",key:"1ays0h"}]],ne=L("minus",le),ie=U({name:F().min(1,"El nombre es obligatorio").min(3,"El nombre debe tener al menos 3 caracteres"),slug:F().min(1,"El slug es obligatorio").min(3,"El slug debe tener al menos 3 caracteres").regex(/^[a-z._]+$/,"El slug solo puede contener letras minúsculas, puntos y guiones bajos"),description:F().optional().nullable(),active:Y().default(!0)}),ce=({initialData:l=null,onSuccess:w,onCancel:C})=>{const v=!!l,{createRole:k,updateRole:I,loading:d}=A(),{register:i,handleSubmit:x,formState:{errors:n},setError:N,reset:S,watch:c,setValue:j}=X({resolver:J(ie),mode:"onChange",defaultValues:l||{name:"",slug:"",description:"",active:!0}}),m=c("active"),h=[{value:!0,label:"Activo"},{value:!1,label:"Inactivo"}],E=async b=>{try{let u;v?u=await I(l.id,b):u=await k(b),u?.success?(f.success(u.message||"Operación exitosa"),S(),w?.()):(console.log(u),Q(u,N))}catch(u){console.error("Error en OnSubmit:",u),f.error("Error inesperado en la Operación")}};return e.jsxs("form",{onSubmit:x(E),className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(z,{label:"Nombre",placeholder:"Ej: Docente",error:n.name?.message,...i("name")}),e.jsx(O,{message:n.name?.message})]}),e.jsxs("div",{children:[e.jsx(z,{label:"Slug",placeholder:"Ej: teacher",error:n.slug?.message,...i("slug")}),e.jsx(O,{message:n.slug?.message})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2 text-gray-700",children:"Descripción (Opcional)"}),e.jsx("textarea",{placeholder:"Descripción del permiso",rows:3,className:`
                        w-full px-3 py-3 rounded-lg border bg-white text-gray-900 
                        placeholder:text-gray-500 transition-colors duration-200
                        focus:outline-none focus:border-[#00306e] focus:ring-2 focus:ring-[#00306e]/10
                        hover:border-gray-400
                        ${n.description?.message?"border-red-500 focus:border-red-500 focus:ring-red-500/10":"border-gray-300"}
                    `,...i("description")}),e.jsx(O,{message:n.description?.message})]}),e.jsxs("div",{children:[e.jsx(Z,{label:"Estado",options:h,value:m,onValueChange:b=>j("active",b),error:n.active?.message,direction:"row"}),e.jsx(O,{message:n.active?.message})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4 border-t border-gray-200",children:[e.jsx($,{type:"button",variant:"ghost",text:"Cancelar",leftIcon:e.jsx(ee,{className:"w-4 h-4"}),onClick:C,disabled:d}),e.jsx($,{type:"submit",variant:"primary",text:d?"Guardando...":v?"Actualizar":"Crear",leftIcon:!d&&e.jsx(T,{className:"w-4 h-4"}),loading:d,disabled:d})]})]})},de=({initialData:l})=>{const{getRole:w,syncPermissions:C,loading:v}=A(),{data:k,loading:I,fetchPermissions:d}=se(),[i,x]=g.useState(new Set),[n,N]=g.useState(!1),[S,c]=g.useState(null),j=k?.data||[],m=g.useMemo(()=>{const s={};return j.forEach(r=>{s[r.group]||(s[r.group]=[]),s[r.group].push(r)}),s},[j]),h=g.useMemo(()=>{const s={};return Object.keys(m).forEach(r=>{const a=m[r].map(y=>y.slug),p=a.filter(y=>i.has(y)).length;p===0?s[r]="none":p===a.length?s[r]="all":s[r]="partial"}),s},[m,i]);g.useEffect(()=>{let s=!0;const r=async()=>{try{const t=await w(l.id,{include:"permissions"});if(await d(),s&&t?.permissions){const a=t.permissions.map(p=>p.slug);x(new Set(a))}}catch(t){if(s){console.error("Error al cargar datos:",t);const a="Error al cargar los datos iniciales";c(a),f.error(a)}}};return l?.id&&r(),()=>{s=!1}},[l?.id]);const E=s=>{x(r=>{const t=new Set(r);return t.has(s)?t.delete(s):t.add(s),t})},b=s=>{const t=m[s].map(p=>p.slug),a=t.every(p=>i.has(p));x(p=>{const y=new Set(p);return a?t.forEach(P=>y.delete(P)):t.forEach(P=>y.add(P)),y})},u=async()=>{if(!l?.id){f.error("ID del rol no disponible");return}N(!0),c(null);try{const s=Array.from(i),r=await C(l.id,{permissions:s});if(r?.success)f.success(r.message||"Permisos actualizados correctamente");else{const t=r?.message||"Error al actualizar permisos";f.error(t),c(t)}}catch(s){console.error("Error al guardar:",s);const r="Error inesperado al guardar los permisos";f.error(r),c(r)}finally{N(!1)}},M=v||I;return M?e.jsx(D,{message:"Cargando permisos del rol...",variant:"light",overlay:!1,portal:!1,size:"md"}):e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"bg-gradient-to-r from-[#00306e] to-[#004b9c] rounded-lg p-6 text-white shadow-lg",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"bg-white/10 p-3 rounded-lg",children:e.jsx(re,{className:"w-8 h-8","aria-hidden":"true"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-2xl font-bold mb-2",children:l?.name}),l?.description&&e.jsx("p",{className:"text-blue-100 mb-3",children:l?.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsx("span",{className:"bg-white/20 px-3 py-1 rounded-full font-mono",children:l?.slug}),e.jsx("span",{className:`px-3 py-1 rounded-full ${l?.active?"bg-green-500/20 text-green-100":"bg-red-500/20 text-red-100"}`,children:l?.active?"Activo":"Inactivo"})]})]})]})}),S&&e.jsx(G,{variant:"warning",message:`⚠️ ${S}`,autoClose:5e3,onClose:()=>c(null)}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",children:e.jsxs("p",{className:"text-sm text-blue-800",children:[e.jsx("span",{className:"font-semibold",children:i.size})," de"," ",e.jsx("span",{className:"font-semibold",children:j.length})," permisos seleccionados"]})}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Object.keys(m).map(s=>{const r=h[s],t=m[s];return e.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden flex flex-col h-full",children:[e.jsx("div",{className:"bg-gray-50 px-4 py-3 border-b border-gray-200",children:e.jsxs("label",{htmlFor:`group-${s}`,className:"flex items-center gap-3 cursor-pointer",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",id:`group-${s}`,checked:r==="all",ref:a=>{a&&(a.indeterminate=r==="partial")},onChange:()=>b(s),className:"w-5 h-5 text-[#00306e] border-gray-300 rounded focus:ring-[#00306e] cursor-pointer","aria-label":`Seleccionar todos los permisos de ${s}`}),r==="partial"&&e.jsx(ne,{className:"w-3 h-3 text-white absolute top-1 left-1 pointer-events-none","aria-hidden":"true"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-semibold text-gray-800 capitalize truncate",children:s}),e.jsxs("div",{className:"text-xs text-gray-500",children:[t.length," permisos"]})]})]})}),e.jsx("div",{className:"p-3 space-y-1 flex-1 bg-white",children:t.map(a=>e.jsxs("label",{htmlFor:`permission-${a.id}`,className:"flex items-start gap-2 p-2 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer group",children:[e.jsx("input",{type:"checkbox",id:`permission-${a.id}`,checked:i.has(a.slug),onChange:()=>E(a.slug),className:"mt-0.5 w-4 h-4 text-[#00306e] border-gray-300 rounded focus:ring-[#00306e] cursor-pointer flex-shrink-0","aria-label":a.name}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-800 group-hover:text-[#00306e] transition-colors",children:a.name}),a.description&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5 line-clamp-2",children:a.description}),e.jsx("span",{className:"text-xs text-gray-400 font-mono",children:a.slug})]})]},a.id))})]},s)})}),e.jsx("div",{className:"flex items-center justify-end gap-3 pt-4 border-t border-gray-200 sticky bottom-0 bg-white pb-4",children:e.jsx($,{type:"button",variant:"primary",text:n?"Guardando...":"Guardar Cambios",leftIcon:!n&&e.jsx(T,{className:"w-4 h-4"}),onClick:u,loading:n,disabled:n||M})}),n&&e.jsx(D,{message:"Guardando permisos...",variant:"glass",overlay:!0,portal:!0,size:"md"})]})},Oe=()=>{const{data:l,loading:w,error:C,fetchRoles:v,deleteRole:k}=A(),[I,d]=g.useState(!1),[i,x]=g.useState(null),[n,N]=g.useState(!1),[S,c]=g.useState(!1),[j,m]=g.useState(null),[h,E]=g.useState(!1),b={sort_by:"id",order:"desc",per_page:10},u=[{key:"id",label:"ID",sortable:!0,wrap:!1,width:"w-20"},{key:"name",label:"Nombre",sortable:!0,wrap:!1},{key:"slug",label:"Slug",sortable:!0,wrap:!1},{key:"description",label:"Descripción",sortable:!1,wrap:!0,maxWidth:"max-w-xs"},{key:"active",label:"Estado",sortable:!0,wrap:!1,render:o=>e.jsx("span",{className:`px-2 py-1 text-xs font-medium rounded-full ${o?"bg-green-100 text-green-800":"bg-red-100 text-red-800"}`,children:o?"Activo":"Inactivo"})}],M=()=>{x(null),d(!0)},s=o=>{x(o),d(!0)},r=o=>{x(o),N(!0)},t=()=>{d(!1),x(null),N(!1)},a=()=>{d(!1),x(null),v(b)},p=o=>{m(o),c(!0)},y=()=>{h||(c(!1),m(null))},P=async()=>{if(j){E(!0);try{const o=await k(j.id);o?.success?(f.success(o.message||"Item eliminado correctamente"),c(!1),m(null),v(b)):(f.error(o?.message||"Error al eliminar el Item"),c(!1))}catch(o){console.error("Error al eliminar:",o),f.error("Error inesperado al eliminar el Item"),c(!1)}finally{E(!1)}}},_=o=>e.jsxs(e.Fragment,{children:[e.jsx(R,{permission:"roles.update",children:e.jsx("button",{onClick:()=>r(o),className:"p-2 text-[#ef7d00] hover:bg-blue-50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer",title:"Editar",disabled:h||w,children:e.jsx(oe,{className:"w-4 h-4"})})}),e.jsx(R,{permission:"roles.update",children:e.jsx("button",{onClick:()=>s(o),className:"p-2 text-[#00306e] hover:bg-blue-50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer",title:"Editar",disabled:h,children:e.jsx(ae,{className:"w-4 h-4"})})}),e.jsx(R,{permission:"roles.destroy",children:e.jsx("button",{onClick:()=>p(o),className:"p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer",title:"Eliminar",disabled:h,children:e.jsx(K,{className:"w-4 h-4"})})})]});return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-800",children:"Gestión de Roles"}),e.jsx("p",{className:"text-gray-600 mt-1",children:"Administra los Roles del Sistema"})]}),e.jsx(R,{permission:"roles.store",children:e.jsxs("button",{onClick:M,className:"flex items-center gap-2 px-4 py-2 text-white bg-[#00306e] rounded-lg hover:bg-[#002555] transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer",disabled:h,children:[e.jsx(q,{className:"w-5 h-5"}),"Nuevo Rol"]})})]}),C&&e.jsx(G,{variant:"warning",message:"⚠️ Hubo un problema al realizar la operación.",autoClose:3e3}),e.jsx(V,{columns:u,data:l,onFetchData:v,initialParams:b,renderActions:_,loading:w,loadingMessage:h?"Eliminando...":"Cargando...",searchable:!0,autoSearch:!1,sortable:!0,searchPlaceholder:"Buscar ...",emptyMessage:"No hay Información Registrada",perPageOptions:[10,25,50,100]}),e.jsx(B,{isOpen:I,onClose:t,title:i?"Editar Rol":"Crear Rol",size:"md",closeOnClickOutside:!1,children:e.jsx(ce,{initialData:i,onSuccess:a,onCancel:t})}),e.jsx(W,{isOpen:n,onClose:t,title:`Administrar Permisos de ${i?.name}`,subtitle:"Asignar Permisos a este Rol",children:e.jsx(de,{initialData:i})}),e.jsx(H,{isOpen:S,onClose:y,onConfirm:P,title:"Eliminar Rol",message:`¿Estás seguro de eliminar el rol "${j?.name||"seleccionado"}"? Esta acción no se puede deshacer.`,variant:"danger",confirmText:"Eliminar",cancelText:"Cancelar",loading:h})]})};export{Oe as default};
