// static/js/admin.Employees.jsx

function AdminEmployees({ token }) {
    const [users, setUsers] = useState([]);
    const [formData, setFormData] = useState({
        email: "",
        first_name: "",
        last_name: "",
        password: "",
        role: "specialist",
    });
    const [editingId, setEditingId] = useState(null);
    const [loading, setLoading] = useState(false);

    // Загрузка списка при старте
    const fetchUsers = async () => {
        try {
            setLoading(true);
            const data = await API.adminGetUsers(token);
            setUsers(data);
        } catch (e) {
            console.error(e);
            alert(e.message || "Ошибка загрузки списка сотрудников");
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchUsers();
    }, []);

    // Логика кнопки "Добавить" / "Сохранить"
    const handleSubmit = async () => {
        const payload = { ...formData };
        if (editingId && !payload.password) {
            delete payload.password;
        }

        try {
            setLoading(true);
            if (editingId) {
                await API.adminUpdateUser(token, editingId, payload);
            } else {
                await API.adminCreateUser(token, payload);
            }
            await fetchUsers();
            resetForm();
        } catch (e) {
            console.error(e);
            alert(e.message || "Ошибка сохранения сотрудника");
        } finally {
            setLoading(false);
        }
    };

    // Логика кнопки "Удалить"
    const handleDelete = async (id) => {
        if (!confirm("Вы уверены, что хотите удалить сотрудника?")) return;

        try {
            setLoading(true);
            await API.adminDeleteUser(token, id);
            await fetchUsers();
            if (editingId === id) {
                resetForm();
            }
        } catch (e) {
            console.error(e);
            alert(e.message || "Ошибка удаления (возможно, нельзя удалить себя)");
        } finally {
            setLoading(false);
        }
    };

    // Загрузка данных в форму для редактирования
    const startEdit = (user) => {
        setEditingId(user.id);
        setFormData({
            email: user.email,
            first_name: user.first_name,
            last_name: user.last_name,
            role: user.role,
            password: "",
        });
    };

    const resetForm = () => {
        setEditingId(null);
        setFormData({
            email: "",
            first_name: "",
            last_name: "",
            password: "",
            role: "specialist",
        });
    };

    const roleBadges = {
        admin: { text: "Администратор", color: "bg-purple-100 text-purple-800" },
        manager: { text: "Руководитель", color: "bg-orange-100 text-orange-800" },
        specialist: { text: "Специалист", color: "bg-gray-200 text-gray-800" },
    };

    return (
        <div>
            {/* ФОРМА СОЗДАНИЯ / РЕДАКТИРОВАНИЯ */}
            <div className="bg-white p-4 mb-6 rounded shadow border border-gray-200">
                <div className="flex justify-between items-center mb-3">
                    <h4 className="font-bold text-lg">
                        {editingId ? "✏️ Редактирование сотрудника" : "➕ Новый сотрудник"}
                    </h4>
                    {editingId && (
                        <button
                            onClick={resetForm}
                            className="text-sm text-gray-500 hover:text-gray-700"
                        >
                            ✕ Отмена
                        </button>
                    )}
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-2 mb-3">
                    <input
                        placeholder="Имя"
                        className="border p-2 rounded"
                        name="new-employee-first-name"
                        autoComplete="off"
                        value={formData.first_name}
                        onChange={(e) =>
                            setFormData({ ...formData, first_name: e.target.value })
                        }
                    />
                    <input
                        placeholder="Фамилия"
                        className="border p-2 rounded"
                        name="new-employee-last-name"
                        autoComplete="off"
                        value={formData.last_name}
                        onChange={(e) =>
                            setFormData({ ...formData, last_name: e.target.value })
                        }
                    />
                    <input
                        placeholder="Email"
                        className="border p-2 rounded"
                        type="email"
                        name="new-employee-email"
                        autoComplete="off"
                        value={formData.email}
                        onChange={(e) =>
                            setFormData({ ...formData, email: e.target.value })
                        }
                    />
                    <input
                        placeholder={
                            editingId ? "Новый пароль (необязательно)" : "Пароль"
                        }
                        className="border p-2 rounded"
                        type="password"
                        name="new-employee-password"
                        autoComplete="new-password"
                        value={formData.password}
                        onChange={(e) =>
                            setFormData({ ...formData, password: e.target.value })
                        }
                    />
                    <select
                        className="border p-2 rounded bg-white"
                        name="new-employee-role"
                        autoComplete="off"
                        value={formData.role}
                        onChange={(e) =>
                            setFormData({ ...formData, role: e.target.value })
                        }
                    >
                        <option value="specialist">Специалист</option>
                        <option value="manager">Руководитель</option>
                        <option value="admin">Администратор</option>
                    </select>
                </div>

                <button
                    onClick={handleSubmit}
                    disabled={loading}
                    className={`w-full py-2 rounded text-white font-bold transition ${
                        editingId
                            ? "bg-orange-500 hover:bg-orange-600"
                            : "bg-green-600 hover:bg-green-700"
                    } disabled:opacity-60`}
                >
                    {editingId ? "Сохранить изменения" : "Добавить сотрудника"}
                </button>
            </div>

            {/* ТАБЛИЦА СОТРУДНИКОВ */}
            <div className="relative">
                {loading && (
                    <div className="absolute inset-0 bg-white bg-opacity-50 flex items-center justify-center z-10">
                        <div className="spinner"></div>
                    </div>
                )}

                <table className="w-full bg-white shadow rounded overflow-hidden">
                    <thead className="bg-gray-100 border-b">
                        <tr>
                            <th className="p-3 text-left font-semibold text-gray-600">
                                ФИО
                            </th>
                            <th className="p-3 text-left font-semibold text-gray-600">
                                Email
                            </th>
                            <th className="p-3 text-left font-semibold text-gray-600">
                                Роль
                            </th>
                            <th className="p-3 text-right font-semibold text-gray-600">
                                Действия
                            </th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                        {users.map((u) => (
                            <tr key={u.id} className="hover:bg-blue-50 transition">
                                <td className="p-3">
                                    {u.first_name} {u.last_name}
                                </td>
                                <td className="p-3 text-gray-600">{u.email}</td>
                                <td className="p-3">
                                    <span
                                        className={`px-2 py-1 rounded-full text-xs font-semibold ${
                                            (roleBadges[u.role] || roleBadges.specialist).color
                                        }`}
                                    >
                                        {(roleBadges[u.role] || roleBadges.specialist).text}
                                    </span>
                                </td>
                                <td className="p-3 text-right">
                                    <div className="flex justify-end gap-2">
                                        <button
                                            onClick={() => startEdit(u)}
                                            className="px-3 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 text-sm font-medium"
                                        >
                                            Изм.
                                        </button>
                                        <button
                                            onClick={() => handleDelete(u.id)}
                                            className="px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200 text-sm font-medium"
                                        >
                                            Удалить
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>

                {users.length === 0 && !loading && (
                    <div className="text-center p-8 text-gray-500">
                        Нет сотрудников
                    </div>
                )}
            </div>
        </div>
    );
}
