import{c as B,r as g,j as e,t as b,L as q}from"./index-DiwDH9aE.js";import{A as H,D as ce}from"./Alert-Cq7mXBD-.js";import{S as W,P as ie,M as de}from"./Modal-tocKJOcW.js";import{C as G,T as ue}from"./ConfirmModal-mJDwNEXB.js";import{F as me}from"./FullScreenModal-DHvf5XmH.js";import{u as ge,a as pe,h as he}from"./handleFormErrors-CaWHVJ6Q.js";import{o as A,b as xe,s as C,c as fe,e as be,I as R,E as S}from"./schemas-BwNPnT22.js";import{R as V}from"./RadioGroup-qqSrRVM3.js";import{B as $}from"./Button-Cu8l7rID.js";import{B as ye,S as we}from"./BaseService-B6zq4ARl.js";import{E as k,b as I}from"./endpoints-BUXROgJ9.js";import{a as M}from"./multiUserApiClient-CKPzIhIr.js";import{X as je}from"./x-D4vgwdOf.js";import{u as Ee}from"./useRoles-B8PPbxwm.js";import{C as P}from"./Can-w-eLoK-Q.js";import{S as ve}from"./shield-Beyfz6Tk.js";import"./search-h1vL1q1e.js";import"./triangle-alert-BxjRBxgM.js";import"./circle-check-big-CvbUXdGb.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 Se=[["path",{d:"M2.586 17.414A2 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-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]],Ne=B("key-round",Se);/**
 * @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 Ce=[["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m14.305 16.53.923-.382",key:"1itpsq"}],["path",{d:"m15.228 13.852-.923-.383",key:"eplpkm"}],["path",{d:"m16.852 12.228-.383-.923",key:"13v3q0"}],["path",{d:"m16.852 17.772-.383.924",key:"1i8mnm"}],["path",{d:"m19.148 12.228.383-.923",key:"1q8j1v"}],["path",{d:"m19.53 18.696-.382-.924",key:"vk1qj3"}],["path",{d:"m20.772 13.852.924-.383",key:"n880s0"}],["path",{d:"m20.772 16.148.924.383",key:"1g6xey"}],["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],Ue=B("user-cog",Ce),J={document_number:C().min(8,"El documento debe tener al menos 8 caracteres").max(20,"El documento no puede exceder 20 caracteres"),names:C().min(3,"Los nombres deben tener al menos 3 caracteres").max(50,"Los nombres no pueden exceder 50 caracteres"),paternal_surname:C().min(3,"El apellido paterno debe tener al menos 3 caracteres").max(50,"El apellido paterno no puede exceder 50 caracteres"),maternal_surname:C().min(3,"El apellido materno debe tener al menos 3 caracteres").max(50,"El apellido materno no puede exceder 50 caracteres"),gender:fe(["male","female"],{required_error:"El género es obligatorio",invalid_type_error:"Selecciona un género válido"}),birth_date:C().min(1,"La fecha de nacimiento es obligatoria").refine(i=>new Date(i)<new Date,{message:"La fecha de nacimiento debe ser anterior a hoy"}),email:C().email("Correo electrónico inválido").max(255,"El correo no puede exceder 255 caracteres"),phone_number:C().min(1,"El teléfono es obligatorio").max(20,"El teléfono no puede exceder 20 caracteres"),active:xe({required_error:"El estado es obligatorio",invalid_type_error:"El estado debe ser verdadero o falso"})},_e=A(J),Re=A(J);A({password:C().min(8,"La contraseña debe tener al menos 8 caracteres").max(50,"La contraseña no puede exceder 50 caracteres")});A({roles:be(C()).min(1,"Debe seleccionar al menos un rol")});class ke extends ye{constructor(){super(k.ADMIN.USERS.BASE)}async toggleStatus(d){try{if(!d)throw new Error("ID es requerido para toggleStatus()");const u=I(k.ADMIN.USERS.TOGGLE_STATUS,{id:d});return await M.patch(u)}catch(u){throw console.error("[UsersService] Error en toggleStatus:",u),u}}async resetPassword(d){try{if(!d)throw new Error("ID es requerido para resetPassword()");const u=I(k.ADMIN.USERS.RESET_PASSWORD,{id:d});return await M.patch(u)}catch(u){throw console.error("[UsersService] Error en resetPassword:",u),u}}async changePassword(d,u){try{if(!d)throw new Error("ID es requerido para changePassword()");const a=I(k.ADMIN.USERS.CHANGE_PASSWORD,{id:d});return await M.patch(a,u)}catch(a){throw console.error("[UsersService] Error en changePassword:",a),a}}async syncRoles(d,u){try{if(!d)throw new Error("ID es requerido para syncRoles()");const a=I(k.ADMIN.USERS.SYNC_ROLES,{id:d});return await M.post(a,u)}catch(a){throw console.error("[UsersService] Error en syncRoles:",a),a}}}const N=new ke,T=()=>{const[i,d]=g.useState(null),[u,a]=g.useState(!1),[v,t]=g.useState(null),x="el Usuario",y="los Usuarios";return{data:i,loading:u,error:v,fetchUsers:async(o={})=>{a(!0),t(null);try{const s=await N.getAll(o);return s.success?(d(s),s):(t(s.message),s)}catch(s){throw t(s.message||`Error al cargar ${y}`),console.error("Error en fetchUsers:",s),s}finally{a(!1)}},getUser:async(o,s={})=>{a(!0),t(null);try{const r=await N.getById(o,s);return r.success?r.data:(t(r.message),null)}catch(r){throw t(r.message||`Error al cargar ${x}`),console.error("Error en getUser:",r),r}finally{a(!1)}},createUser:async o=>{a(!0),t(null);try{const s=await N.create(o);return s.success||t(s.message),s}catch(s){throw t(s.message||`Error al crear ${x}`),console.error("Error en createUser:",s),s}finally{a(!1)}},updateUser:async(o,s)=>{a(!0),t(null);try{const r=await N.update(o,s);return r.success||t(r.message),r}catch(r){throw t(r.message||`Error al actualizar ${x}`),console.error("Error en updateUser:",r),r}finally{a(!1)}},deleteUser:async o=>{a(!0),t(null);try{const s=await N.delete(o);return s.success||t(s.message),s}catch(s){throw t(s.message||`Error al eliminar ${x}`),console.error("Error en deleteUser:",s),s}finally{a(!1)}},toggleStatus:async o=>{a(!0),t(null);try{const s=await N.toggleStatus(o);return s.success||t(s.message||"Error al cambiar estado"),s}catch(s){throw t(s.message||"Error al cambiar estado"),console.error("Error en toggleStatus:",s),s}finally{a(!1)}},resetPassword:async o=>{a(!0),t(null);try{const s=await N.resetPassword(o);return s.success||t(s.message||"Error al restablecer contraseña"),s}catch(s){throw t(s.message||"Error al restablecer contraseña"),console.error("Error en resetPassword:",s),s}finally{a(!1)}},changePassword:async(o,s)=>{a(!0),t(null);try{const r=await N.changePassword(o,s);return r.success||t(r.message||"Error al cambiar contraseña"),r}catch(r){throw t(r.message||"Error al cambiar contraseña"),console.error("Error en changePassword:",r),r}finally{a(!1)}},syncRoles:async(o,s)=>{a(!0),t(null);try{const r=await N.syncRoles(o,s);return r.success||t(r.message||"Error al sincronizar roles"),r}catch(r){throw t(r.message||"Error al sincronizar roles"),console.error("Error en syncRoles:",r),r}finally{a(!1)}},clearError:()=>{t(null)},reset:()=>{d(null),a(!1),t(null)}}},Pe=({initialData:i=null,onSuccess:d,onCancel:u})=>{const a=!!i,{createUser:v,updateUser:t,loading:x}=T(),y=a?Re:_e,{register:m,handleSubmit:p,formState:{errors:c},setError:U,reset:j,watch:w,setValue:E}=ge({resolver:pe(y),mode:"onChange",defaultValues:i||{document_number:"",names:"",paternal_surname:"",maternal_surname:"",gender:"male",birth_date:"",email:"",phone_number:"",photo_user:"",active:!0}}),_=w("active"),f=w("gender"),n=[{value:!0,label:"Activo"},{value:!1,label:"Inactivo"}],h=[{value:"male",label:"Masculino"},{value:"female",label:"Femenino"}],o=async s=>{try{let r;a?r=await t(i.id,s):r=await v(s),r?.success?(b.success(r.message||"Operación exitosa"),j(),d?.()):he(r,U)}catch(r){console.error("Error en onSubmit:",r),b.error("Error inesperado en la operación")}};return e.jsxs("form",{onSubmit:p(o),className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(R,{label:"Número de Documento",placeholder:"Ej: 12345678",error:c.document_number?.message,...m("document_number")}),e.jsx(S,{message:c.document_number?.message})]}),e.jsxs("div",{children:[e.jsx(R,{label:"Nombres",placeholder:"Ej: Juan Carlos",error:c.names?.message,...m("names")}),e.jsx(S,{message:c.names?.message})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(R,{label:"Apellido Paterno",placeholder:"Ej: Pérez",error:c.paternal_surname?.message,...m("paternal_surname")}),e.jsx(S,{message:c.paternal_surname?.message})]}),e.jsxs("div",{children:[e.jsx(R,{label:"Apellido Materno",placeholder:"Ej: García",error:c.maternal_surname?.message,...m("maternal_surname")}),e.jsx(S,{message:c.maternal_surname?.message})]})]}),e.jsxs("div",{children:[e.jsx(V,{label:"Género",name:"gender",required:!0,options:h,value:f,onValueChange:s=>E("gender",s,{shouldValidate:!0}),error:c.gender?.message,direction:"row"}),e.jsx(S,{message:c.gender?.message})]}),e.jsxs("div",{children:[e.jsx(R,{type:"date",label:"Fecha de Nacimiento",error:c.birth_date?.message,...m("birth_date")}),e.jsx(S,{message:c.birth_date?.message})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(R,{type:"email",label:"Correo Electrónico",placeholder:"usuario@example.com",error:c.email?.message,...m("email")}),e.jsx(S,{message:c.email?.message})]}),e.jsxs("div",{children:[e.jsx(R,{label:"Teléfono",placeholder:"999999999",error:c.phone_number?.message,...m("phone_number")}),e.jsx(S,{message:c.phone_number?.message})]})]}),e.jsxs("div",{children:[e.jsx(V,{label:"Estado",name:"active",helperText:"Usuario activo puede iniciar sesión",options:n,value:_,onValueChange:s=>E("active",s,{shouldValidate:!0}),error:c.active?.message,direction:"row"}),e.jsx(S,{message:c.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(je,{className:"w-4 h-4"}),onClick:u,disabled:x}),e.jsx($,{type:"submit",variant:"primary",text:x?"Guardando...":a?"Actualizar":"Crear",leftIcon:!x&&e.jsx(W,{className:"w-4 h-4"}),loading:x,disabled:x})]})]})},Ie=({initialData:i})=>{const{getUser:d,syncRoles:u,loading:a}=T(),{data:v,loading:t,fetchRoles:x}=Ee(),[y,m]=g.useState(new Set),[p,c]=g.useState(!1),[U,j]=g.useState(null),w=v?.data||[];g.useEffect(()=>{let n=!0;const h=async()=>{try{const o=await d(i.id,{include:"roles"});if(await x(),n&&o?.roles){const s=o.roles.map(r=>r.slug);m(new Set(s))}}catch(o){if(n){console.error("Error al cargar datos:",o);const s="Error al cargar los datos iniciales";j(s),b.error(s)}}};return i?.id&&h(),()=>{n=!1}},[i?.id]);const E=n=>{m(h=>{const o=new Set(h);return o.has(n)?o.delete(n):o.add(n),o})},_=async()=>{if(!i?.id){b.error("ID del usuario no disponible");return}c(!0),j(null);try{const n=Array.from(y),h=await u(i.id,{roles:n});if(h?.success)b.success(h.message||"Roles actualizados correctamente");else{const o=h?.message||"Error al actualizar roles";b.error(o),j(o)}}catch(n){console.error("Error al guardar:",n);const h="Error inesperado al guardar los roles";b.error(h),j(h)}finally{c(!1)}},f=a||t;return f?e.jsx(q,{message:"Cargando roles del usuario...",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(Ue,{className:"w-8 h-8","aria-hidden":"true"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("h2",{className:"text-2xl font-bold mb-2",children:[i?.names," ",i?.paternal_surname]}),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",children:i?.document_number}),e.jsx("span",{className:"bg-white/20 px-3 py-1 rounded-full",children:i?.email}),e.jsx("span",{className:`px-3 py-1 rounded-full ${i?.active?"bg-green-500/20 text-green-100":"bg-red-500/20 text-red-100"}`,children:i?.active?"Activo":"Inactivo"})]})]})]})}),U&&e.jsx(H,{variant:"warning",message:`⚠️ ${U}`,autoClose:5e3,onClose:()=>j(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:y.size})," de"," ",e.jsx("span",{className:"font-semibold",children:w.length})," roles seleccionados"]})}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:w.map(n=>e.jsx("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:e.jsxs("label",{htmlFor:`role-${n.id}`,className:"flex items-start gap-3 p-4 hover:bg-gray-50 transition-colors cursor-pointer group",children:[e.jsx("input",{type:"checkbox",id:`role-${n.id}`,checked:y.has(n.slug),onChange:()=>E(n.slug),className:"mt-0.5 w-5 h-5 text-[#00306e] border-gray-300 rounded focus:ring-[#00306e] cursor-pointer flex-shrink-0","aria-label":n.name}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-800 group-hover:text-[#00306e] transition-colors",children:n.name}),n.description&&e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:n.description}),e.jsx("span",{className:"text-xs text-gray-400 font-mono mt-1 block",children:n.slug})]})]})},n.id))}),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:p?"Guardando...":"Guardar Cambios",leftIcon:!p&&e.jsx(W,{className:"w-4 h-4"}),onClick:_,loading:p,disabled:p||f})}),p&&e.jsx(q,{message:"Guardando roles...",variant:"glass",overlay:!0,portal:!0,size:"md"})]})},Qe=()=>{const{data:i,loading:d,error:u,fetchUsers:a,deleteUser:v,resetPassword:t}=T(),[x,y]=g.useState(!1),[m,p]=g.useState(null),[c,U]=g.useState(!1),[j,w]=g.useState(!1),[E,_]=g.useState(null),[f,n]=g.useState(!1),[h,o]=g.useState(!1),[s,r]=g.useState(null),[L,F]=g.useState(!1),D={sort_by:"id",order:"desc",per_page:10},K=[{key:"id",label:"ID",sortable:!0,wrap:!1,width:"w-16"},{key:"document_number",label:"Documento",sortable:!0,wrap:!1},{key:"names",label:"Nombres Completos",sortable:!0,wrap:!1,render:(l,O)=>`${O.names} ${O.paternal_surname} ${O.maternal_surname}`},{key:"email",label:"Correo",sortable:!0,wrap:!1},{key:"active",label:"Estado",sortable:!0,wrap:!1,render:l=>e.jsx("span",{className:`px-2 py-1 text-xs font-medium rounded-full ${l?"bg-green-100 text-green-800":"bg-red-100 text-red-800"}`,children:l?"Activo":"Inactivo"})}],X=()=>{p(null),y(!0)},Y=l=>{p(l),y(!0)},Q=l=>{p(l),U(!0)},z=()=>{y(!1),p(null)},Z=()=>{U(!1),p(null)},ee=()=>{y(!1),p(null),a(D)},se=l=>{_(l),w(!0)},re=()=>{f||(w(!1),_(null))},ae=async()=>{if(E){n(!0);try{const l=await v(E.id);l?.success?(b.success(l.message||"Usuario eliminado correctamente"),w(!1),_(null),a(D)):(b.error(l?.message||"Error al eliminar usuario"),w(!1))}catch(l){console.error("Error al eliminar:",l),b.error("Error inesperado al eliminar usuario"),w(!1)}finally{n(!1)}}},oe=l=>{r(l),o(!0)},te=()=>{L||(o(!1),r(null))},ne=async()=>{if(s){F(!0);try{const l=await t(s.id);l?.success?(b.success(l.message||"Contraseña restablecida correctamente"),o(!1),r(null)):(b.error(l?.message||"Error al restablecer contraseña"),o(!1))}catch(l){console.error("Error al restablecer contraseña:",l),b.error("Error inesperado al restablecer contraseña"),o(!1)}finally{F(!1)}}},le=l=>e.jsxs(e.Fragment,{children:[e.jsx(P,{permission:"users.roles.assign",children:e.jsx("button",{onClick:()=>Q(l),className:"p-2 text-purple-600 hover:bg-purple-50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer",title:"Asignar Roles",disabled:f||d,children:e.jsx(ve,{className:"w-4 h-4"})})}),e.jsx(P,{permission:"users.update",children:e.jsx("button",{onClick:()=>oe(l),className:"p-2 text-orange-600 hover:bg-orange-50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer",title:"Restablecer Contraseña",disabled:f||d,children:e.jsx(Ne,{className:"w-4 h-4"})})}),e.jsx(P,{permission:"users.update",children:e.jsx("button",{onClick:()=>Y(l),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:f,children:e.jsx(we,{className:"w-4 h-4"})})}),e.jsx(P,{permission:"users.destroy",children:e.jsx("button",{onClick:()=>se(l),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:f,children:e.jsx(ue,{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 Usuarios"}),e.jsx("p",{className:"text-gray-600 mt-1",children:"Administra los usuarios del sistema"})]}),e.jsx(P,{permission:"users.store",children:e.jsxs("button",{onClick:X,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",disabled:f,children:[e.jsx(ie,{className:"w-5 h-5"}),"Nuevo Usuario"]})})]}),u&&e.jsx(H,{variant:"warning",message:"⚠️ Hubo un problema al realizar la operación.",autoClose:3e3}),e.jsx(ce,{columns:K,data:i,onFetchData:a,initialParams:D,renderActions:le,loading:d,loadingMessage:f?"Eliminando...":"Cargando...",searchable:!0,autoSearch:!1,sortable:!0,searchPlaceholder:"Buscar usuarios...",emptyMessage:"No hay usuarios registrados",perPageOptions:[10,25,50,100]}),e.jsx(de,{isOpen:x,onClose:z,title:m?"Editar Usuario":"Crear Usuario",size:"lg",closeOnClickOutside:!1,children:e.jsx(Pe,{initialData:m,onSuccess:ee,onCancel:z})}),e.jsx(me,{isOpen:c,onClose:Z,title:`Asignar Roles a ${m?.names||""}`,subtitle:"Gestión de roles del usuario",children:e.jsx(Ie,{initialData:m})}),e.jsx(G,{isOpen:j,onClose:re,onConfirm:ae,title:"Eliminar Usuario",message:`¿Estás seguro de eliminar al usuario "${E?.names||""}" ${E?.paternal_surname||""}? Esta acción no se puede deshacer.`,variant:"danger",confirmText:"Eliminar",cancelText:"Cancelar",loading:f}),e.jsx(G,{isOpen:h,onClose:te,onConfirm:ne,title:"Restablecer Contraseña",message:`¿Estás seguro de restablecer la contraseña del usuario "${s?.names||""}" ${s?.paternal_surname||""}? La nueva contraseña será su número de documento.`,variant:"warning",confirmText:"Restablecer",cancelText:"Cancelar",loading:L})]})};export{Qe as default};
