"use client" import { useEffect, useState } from "react" import { Plus, Pencil, Trash2, Loader2, AlertCircle } from "lucide-react" import { Button } from "@/components/ui/button" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert" interface FormaJuridica { id: number nombre: string codigo?: string descripcion?: string estado: boolean } export function FormasJuridicasConfig() { const [formas, setFormas] = useState([]) const [isLoading, setIsLoading] = useState(true) const [error, setError] = useState(null) // Modal state const [isModalOpen, setIsModalOpen] = useState(false) const [editingForma, setEditingForma] = useState(null) const [formData, setFormData] = useState({ nombre: "", codigo: "", descripcion: "", estado: true }) const [isSaving, setIsSaving] = useState(false) // Delete state const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false) const [deletingId, setDeletingId] = useState(null) const fetchFormas = async () => { setIsLoading(true) setError(null) try { const token = localStorage.getItem("token") if (!token) throw new Error("No autenticado") const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/formas-juridicas`, { headers: { Authorization: `Bearer ${token}`, Accept: "application/json", }, }) if (!response.ok) throw new Error("Error al cargar formas jurídicas") const { data } = await response.json() setFormas(data) } catch (err) { console.error(err) setError("No se pudieron cargar las formas jurídicas") } finally { setIsLoading(false) } } useEffect(() => { fetchFormas() }, []) const handleOpenModal = (forma?: FormaJuridica) => { if (forma) { setEditingForma(forma) setFormData({ nombre: forma.nombre, codigo: forma.codigo || "", descripcion: forma.descripcion || "", estado: forma.estado }) } else { setEditingForma(null) setFormData({ nombre: "", codigo: "", descripcion: "", estado: true }) } setIsModalOpen(true) } const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setIsSaving(true) try { const token = localStorage.getItem("token") if (!token) throw new Error("No autenticado") const url = editingForma ? `${process.env.NEXT_PUBLIC_API_URL}/api/formas-juridicas/${editingForma.id}` : `${process.env.NEXT_PUBLIC_API_URL}/api/formas-juridicas` const method = editingForma ? "PUT" : "POST" const response = await fetch(url, { method, headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, Accept: "application/json", }, body: JSON.stringify(formData), }) if (!response.ok) { const errorData = await response.json() throw new Error(errorData.message || "Error al guardar") } await fetchFormas() setIsModalOpen(false) } catch (err: any) { console.error(err) alert(err.message || "Error al guardar la forma jurídica") } finally { setIsSaving(false) } } const handleDelete = async () => { if (!deletingId) return setIsSaving(true) try { const token = localStorage.getItem("token") if (!token) throw new Error("No autenticado") const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/formas-juridicas/${deletingId}`, { method: "DELETE", headers: { Authorization: `Bearer ${token}`, Accept: "application/json", }, }) if (!response.ok) throw new Error("Error al eliminar") await fetchFormas() setIsDeleteModalOpen(false) } catch (err) { console.error(err) alert("Error al eliminar la forma jurídica. Puede que esté en uso.") } finally { setIsSaving(false) setDeletingId(null) } } return (
Formas Jurídicas Gestionar el catálogo de formas jurídicas disponibles
{error && ( Error {error} )} {isLoading ? (
) : (
Nombre Código Acciones {formas.length === 0 ? ( No hay formas jurídicas registradas ) : ( formas.map((forma) => ( {forma.nombre} {forma.codigo || "-"} {forma.descripcion || "-"} {forma.estado ? 'Activo' : 'Inactivo'}
)) )}
)} {/* Modal Agregar/Editar */} {editingForma ? "Editar Forma Jurídica" : "Nueva Forma Jurídica"} Complete los datos de la forma jurídica. El nombre debe ser único.
setFormData({ ...formData, nombre: e.target.value })} placeholder="Ej: Cooperativa de Trabajo" required />
setFormData({ ...formData, codigo: e.target.value })} placeholder="Ej: COOP-TRAB" />
setFormData({ ...formData, descripcion: e.target.value })} placeholder="Descripción breve..." />
setFormData({ ...formData, estado: e.target.checked })} className="h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary" />
{/* Modal Eliminar */} ¿Está seguro? Esta acción eliminará la forma jurídica permanentemente. Si está en uso por algún trámite, no se podrá eliminar.
) }