import { e as createComponent, k as renderComponent, r as renderTemplate, m as maybeRenderHead } from '../../chunks/astro/server_CNSJbOTP.mjs';
import 'piccolore';
import { a as api, $ as $$AppLayout } from '../../chunks/AppLayout_DAKNch61.mjs';
import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useCallback, useEffect } from 'react';
export { renderers } from '../../renderers.mjs';

function ModalEmpresa({ empresa, onCerrar, onGuardado }) {
  const esEdicion = !!empresa;
  const [form, setForm] = useState({
    nombre: empresa?.nombre || "",
    rut: empresa?.rut || "",
    direccion: empresa?.direccion || "",
    correo: empresa?.correo || ""
  });
  const [guardando, setGuardando] = useState(false);
  const [error, setError] = useState("");
  async function guardar(e) {
    e.preventDefault();
    if (!form.nombre.trim()) {
      setError("El nombre es requerido");
      return;
    }
    setGuardando(true);
    setError("");
    try {
      const cuerpo = {
        nombre: form.nombre,
        rut: form.rut || null,
        direccion: form.direccion || null,
        correo: form.correo || null
      };
      if (esEdicion) {
        await api.put(`/empresas/${empresa.id}`, cuerpo);
      } else {
        await api.post("/empresas", cuerpo);
      }
      onGuardado();
    } catch (e2) {
      setError(e2 instanceof Error ? e2.message : "Error al guardar");
    } finally {
      setGuardando(false);
    }
  }
  return /* @__PURE__ */ jsx("div", { className: "fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4", children: /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl shadow-xl w-full max-w-md", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between p-6 border-b border-gray-100", children: [
      /* @__PURE__ */ jsx("h3", { className: "text-lg font-semibold text-gray-900", children: esEdicion ? "Editar Empresa" : "Nueva Empresa" }),
      /* @__PURE__ */ jsx("button", { onClick: onCerrar, className: "p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg", children: /* @__PURE__ */ jsx("svg", { className: "w-5 h-5", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M6 18L18 6M6 6l12 12" }) }) })
    ] }),
    /* @__PURE__ */ jsxs("form", { onSubmit: guardar, className: "p-6 space-y-4", children: [
      error && /* @__PURE__ */ jsx("div", { className: "p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700", children: error }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("label", { className: "block text-sm font-medium text-gray-700 mb-1.5", children: "Nombre *" }),
        /* @__PURE__ */ jsx("input", { type: "text", value: form.nombre, onChange: (e) => {
          const v = e.target.value;
          setForm((f) => ({ ...f, nombre: v }));
        }, className: "input", placeholder: "Nombre de la empresa" })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("label", { className: "block text-sm font-medium text-gray-700 mb-1.5", children: "RUT" }),
        /* @__PURE__ */ jsx("input", { type: "text", value: form.rut, onChange: (e) => {
          const v = e.target.value;
          setForm((f) => ({ ...f, rut: v }));
        }, className: "input", placeholder: "76.000.000-0" })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("label", { className: "block text-sm font-medium text-gray-700 mb-1.5", children: "Correo electrónico" }),
        /* @__PURE__ */ jsx("input", { type: "email", value: form.correo, onChange: (e) => {
          const v = e.target.value;
          setForm((f) => ({ ...f, correo: v }));
        }, className: "input", placeholder: "contacto@empresa.cl" })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("label", { className: "block text-sm font-medium text-gray-700 mb-1.5", children: "Dirección" }),
        /* @__PURE__ */ jsx("input", { type: "text", value: form.direccion, onChange: (e) => {
          const v = e.target.value;
          setForm((f) => ({ ...f, direccion: v }));
        }, className: "input", placeholder: "Ciudad, País" })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-3 justify-end pt-2", children: [
        /* @__PURE__ */ jsx("button", { type: "button", onClick: onCerrar, className: "btn-secondary text-sm", disabled: guardando, children: "Cancelar" }),
        /* @__PURE__ */ jsx("button", { type: "submit", className: "btn-primary text-sm", disabled: guardando, children: guardando ? "Guardando..." : esEdicion ? "Guardar cambios" : "Crear empresa" })
      ] })
    ] })
  ] }) });
}
function TablaEmpresas() {
  const [empresas, setEmpresas] = useState([]);
  const [total, setTotal] = useState(0);
  const [pagina, setPagina] = useState(1);
  const [cargando, setCargando] = useState(true);
  const [error, setError] = useState("");
  const [filtroActivo, setFiltroActivo] = useState(true);
  const [modalAbierto, setModalAbierto] = useState(false);
  const [empresaEditar, setEmpresaEditar] = useState(null);
  const [confirmDesactivar, setConfirmDesactivar] = useState(null);
  const [confirmEliminar, setConfirmEliminar] = useState(null);
  const [eliminando, setEliminando] = useState(false);
  const [errorEliminar, setErrorEliminar] = useState("");
  const porPagina = 20;
  const cargar = useCallback(async () => {
    setCargando(true);
    setError("");
    try {
      const params = new URLSearchParams({
        pagina: String(pagina),
        por_pagina: String(porPagina),
        activo: String(filtroActivo)
      });
      const data = await api.get(`/empresas?${params}`);
      setEmpresas(data.datos);
      setTotal(data.total);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Error al cargar empresas");
    } finally {
      setCargando(false);
    }
  }, [pagina, filtroActivo]);
  useEffect(() => {
    cargar();
  }, [cargar]);
  async function desactivar(empresa) {
    try {
      await api.delete(`/empresas/${empresa.id}`);
      setConfirmDesactivar(null);
      cargar();
    } catch (e) {
      alert(e instanceof Error ? e.message : "Error al desactivar");
    }
  }
  async function activar(empresa) {
    try {
      await api.put(`/empresas/${empresa.id}`, { activo: true });
      cargar();
    } catch (e) {
      alert(e instanceof Error ? e.message : "Error al activar");
    }
  }
  async function eliminar(empresa) {
    setEliminando(true);
    setErrorEliminar("");
    try {
      await api.delete(`/empresas/${empresa.id}/eliminar`);
      setConfirmEliminar(null);
      cargar();
    } catch (e) {
      setErrorEliminar(e instanceof Error ? e.message : "Error al eliminar");
    } finally {
      setEliminando(false);
    }
  }
  const totalPaginas = Math.ceil(total / porPagina);
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4", children: [
      /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm text-gray-600 cursor-pointer", children: [
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "checkbox",
            checked: filtroActivo,
            onChange: (e) => {
              setFiltroActivo(e.currentTarget.checked);
              setPagina(1);
            },
            className: "rounded border-gray-300"
          }
        ),
        "Solo activas"
      ] }),
      /* @__PURE__ */ jsxs("button", { onClick: () => {
        setEmpresaEditar(null);
        setModalAbierto(true);
      }, className: "btn-primary text-sm flex items-center gap-2", children: [
        /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M12 4v16m8-8H4" }) }),
        "Nueva Empresa"
      ] })
    ] }),
    error && /* @__PURE__ */ jsx("div", { className: "mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700", children: error }),
    /* @__PURE__ */ jsx("div", { className: "table-container", children: /* @__PURE__ */ jsxs("table", { className: "table", children: [
      /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
        /* @__PURE__ */ jsx("th", { children: "Empresa" }),
        /* @__PURE__ */ jsx("th", { className: "hidden sm:table-cell", children: "RUT" }),
        /* @__PURE__ */ jsx("th", { className: "hidden lg:table-cell", children: "Correo" }),
        /* @__PURE__ */ jsx("th", { className: "hidden lg:table-cell", children: "Dirección" }),
        /* @__PURE__ */ jsx("th", { children: "Estado" }),
        /* @__PURE__ */ jsx("th", { children: "Acciones" })
      ] }) }),
      /* @__PURE__ */ jsx("tbody", { children: cargando ? /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: 6, className: "text-center py-10 text-gray-400", children: "Cargando..." }) }) : empresas.length === 0 ? /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: 6, className: "text-center py-10 text-gray-400", children: "No hay empresas" }) }) : empresas.map((emp) => /* @__PURE__ */ jsxs("tr", { children: [
        /* @__PURE__ */ jsx("td", { className: "font-medium text-gray-900", children: emp.nombre }),
        /* @__PURE__ */ jsx("td", { className: "hidden sm:table-cell text-gray-600", children: emp.rut || "—" }),
        /* @__PURE__ */ jsx("td", { className: "hidden lg:table-cell text-gray-600", children: emp.correo || "—" }),
        /* @__PURE__ */ jsx("td", { className: "hidden lg:table-cell text-gray-600", children: emp.direccion || "—" }),
        /* @__PURE__ */ jsx("td", { children: /* @__PURE__ */ jsx("span", { className: emp.activo ? "badge badge-success" : "badge badge-gray", children: emp.activo ? "Activa" : "Inactiva" }) }),
        /* @__PURE__ */ jsx("td", { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
          /* @__PURE__ */ jsx("button", { onClick: () => {
            setEmpresaEditar(emp);
            setModalAbierto(true);
          }, title: "Editar", className: "p-1.5 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors", children: /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" }) }) }),
          emp.activo ? /* @__PURE__ */ jsx("button", { onClick: () => setConfirmDesactivar(emp), title: "Desactivar", className: "p-1.5 text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors", children: /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" }) }) }) : /* @__PURE__ */ jsx("button", { onClick: () => activar(emp), title: "Activar", className: "p-1.5 text-gray-500 hover:text-green-600 hover:bg-green-50 rounded-lg transition-colors", children: /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" }) }) }),
          /* @__PURE__ */ jsx(
            "button",
            {
              onClick: () => {
                setErrorEliminar("");
                setConfirmEliminar(emp);
              },
              title: "Eliminar definitivamente",
              className: "p-1.5 text-gray-500 hover:text-red-700 hover:bg-red-50 rounded-lg transition-colors",
              children: /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" }) })
            }
          )
        ] }) })
      ] }, emp.id)) })
    ] }) }),
    totalPaginas > 1 && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mt-4 text-sm text-gray-600", children: [
      /* @__PURE__ */ jsxs("span", { children: [
        total,
        " empresa",
        total !== 1 ? "s" : "",
        " en total"
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsx("button", { disabled: pagina === 1, onClick: () => setPagina((p) => p - 1), className: "btn-secondary py-1 px-3 text-xs disabled:opacity-50", children: "← Anterior" }),
        /* @__PURE__ */ jsx("button", { disabled: pagina === totalPaginas, onClick: () => setPagina((p) => p + 1), className: "btn-secondary py-1 px-3 text-xs disabled:opacity-50", children: "Siguiente →" })
      ] })
    ] }),
    modalAbierto && /* @__PURE__ */ jsx(
      ModalEmpresa,
      {
        empresa: empresaEditar,
        onCerrar: () => setModalAbierto(false),
        onGuardado: () => {
          setModalAbierto(false);
          cargar();
        }
      }
    ),
    confirmDesactivar && /* @__PURE__ */ jsx("div", { className: "fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4", children: /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl shadow-xl max-w-sm w-full p-6", children: [
      /* @__PURE__ */ jsx("h3", { className: "text-lg font-semibold text-gray-900 mb-2", children: "¿Desactivar empresa?" }),
      /* @__PURE__ */ jsxs("p", { className: "text-gray-600 text-sm mb-5", children: [
        "Se desactivará ",
        /* @__PURE__ */ jsx("strong", { children: confirmDesactivar.nombre }),
        ". El registro seguirá visible filtrando por inactivas."
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-3 justify-end", children: [
        /* @__PURE__ */ jsx("button", { onClick: () => setConfirmDesactivar(null), className: "btn-secondary text-sm", children: "Cancelar" }),
        /* @__PURE__ */ jsx("button", { onClick: () => desactivar(confirmDesactivar), className: "btn-danger text-sm", children: "Desactivar" })
      ] })
    ] }) }),
    confirmEliminar && /* @__PURE__ */ jsx("div", { className: "fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4", children: /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl shadow-xl max-w-sm w-full p-6", children: [
      /* @__PURE__ */ jsx("h3", { className: "text-lg font-semibold text-gray-900 mb-2", children: "¿Eliminar empresa definitivamente?" }),
      /* @__PURE__ */ jsxs("p", { className: "text-gray-600 text-sm mb-4", children: [
        "Se eliminará de forma permanente ",
        /* @__PURE__ */ jsx("strong", { children: confirmEliminar.nombre }),
        ". Esta acción no se puede deshacer. Solo es posible si la empresa no tiene actividades asociadas."
      ] }),
      errorEliminar && /* @__PURE__ */ jsx("div", { className: "mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700", children: errorEliminar }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-3 justify-end", children: [
        /* @__PURE__ */ jsx("button", { onClick: () => {
          setConfirmEliminar(null);
          setErrorEliminar("");
        }, className: "btn-secondary text-sm", disabled: eliminando, children: "Cancelar" }),
        /* @__PURE__ */ jsx("button", { onClick: () => eliminar(confirmEliminar), className: "btn-danger text-sm", disabled: eliminando, children: eliminando ? "Eliminando..." : "Eliminar definitivamente" })
      ] })
    ] }) })
  ] });
}

const $$Empresas = createComponent(($$result, $$props, $$slots) => {
  return renderTemplate`${renderComponent($$result, "AppLayout", $$AppLayout, { "titulo": "Gesti\xF3n de Empresas", "seccionActiva": "empresas" }, { "default": ($$result2) => renderTemplate` ${maybeRenderHead()}<div class="mb-4"> <a href="/dashboard" class="inline-flex items-center gap-2 text-sm text-gray-500 hover:text-[#1B2B4B] transition-colors"> <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path> </svg>
Volver al Dashboard
</a> </div> ${renderComponent($$result2, "TablaEmpresas", TablaEmpresas, { "client:load": true, "client:component-hydration": "load", "client:component-path": "C:/Proyectos IA/Sistema de Control y Gesti\xF3n Crew Consultores/frontend/src/components/admin/TablaEmpresas", "client:component-export": "default" })} ` })}`;
}, "C:/Proyectos IA/Sistema de Control y Gesti\xF3n Crew Consultores/frontend/src/pages/admin/empresas.astro", void 0);

const $$file = "C:/Proyectos IA/Sistema de Control y Gestión Crew Consultores/frontend/src/pages/admin/empresas.astro";
const $$url = "/admin/empresas";

const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  default: $$Empresas,
  file: $$file,
  url: $$url
}, Symbol.toStringTag, { value: 'Module' }));

const page = () => _page;

export { page };
