1import React, { useState, useEffect } from 'react';
2import { apiFetch } from '../lib/api';
3import MainLayout from '../components/Layout/MainLayout';
4import { useParams, useNavigate } from 'react-router-dom';
7 const { agentId } = useParams();
8 const navigate = useNavigate();
9 const [agent, setAgent] = useState(null);
10 const [loading, setLoading] = useState(true);
11 const [error, setError] = useState(null);
12 const [form, setForm] = useState({ name: '', customer: '' });
15 const token = localStorage.getItem('token');
19 const payload = token.split('.')[1];
20 const decoded = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
21 tenantId = decoded.tenant_id || decoded.tenantId || '';
24 apiFetch(`/agent/${agentId}`, {
26 'X-Tenant-Id': tenantId
29 .then(res => res.json())
32 setForm({ name: data.name || '', customer: data.customer || '' });
36 setError('Failed to load agent');
41 const handleChange = e => {
42 setForm({ ...form, [e.target.name]: e.target.value });
45 const handleSubmit = async e => {
50 const token = localStorage.getItem('token');
54 const payload = token.split('.')[1];
55 const decoded = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
56 tenantId = decoded.tenant_id || decoded.tenantId || '';
59 const res = await apiFetch(`/agent/${agentId}`, {
62 'Content-Type': 'application/json',
63 'X-Tenant-Id': tenantId
65 body: JSON.stringify(form),
67 if (!res.ok) throw new Error('Failed to update agent');
68 navigate(`/agents/${agentId}`);
70 setError(err.message);
75 const handleDelete = async () => {
76 if (!window.confirm('Are you sure you want to delete and unenroll this agent? This action cannot be undone.')) return;
80 const token = localStorage.getItem('token');
84 const payload = token.split('.')[1];
85 const decoded = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
86 tenantId = decoded.tenant_id || decoded.tenantId || '';
89 const res = await apiFetch(`/agent/${agentId}`, {
92 'Content-Type': 'application/json',
93 'X-Tenant-Id': tenantId
96 if (!res.ok) throw new Error('Failed to delete agent');
99 setError(err.message);
104 if (loading) return <MainLayout><div>Loading...</div></MainLayout>;
105 if (error) return <MainLayout><div className="error">{error}</div></MainLayout>;
110 <form onSubmit={handleSubmit} style={{ maxWidth: 400 }}>
111 <div style={{ marginBottom: 16 }}>
117 onChange={handleChange}
118 style={{ width: '100%', padding: 8 }}
121 <div style={{ marginBottom: 16 }}>
122 <label>Customer:</label>
126 value={form.customer}
127 onChange={handleChange}
128 style={{ width: '100%', padding: 8 }}
131 <button type="submit" style={{ padding: '8px 20px', fontSize: '1rem' }}>Save</button>
134 onClick={handleDelete}
135 style={{ marginLeft: 16, padding: '8px 20px', fontSize: '1rem', background: '#d9534f', color: 'white', border: 'none', borderRadius: 4 }}
144export default EditAgent;