// Exemplo de componente de criação de plano de treino em React
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const TrainingPlanForm = () => {
const [plan, setPlan] = useState({
name: '',
description: '',
trainings: [],
isPublic: false,
difficulty: '',
goal: '',
duration: 12
});
const [availableTrainings, setAvailableTrainings] = useState([]);
const [loading, setLoading] = useState(false);
const [loadingTrainings, setLoadingTrainings] = useState(true);
const [error, setError] = useState(null);
const [success, setSuccess] = useState(false);
useEffect(() => {
// Carregar treinos disponíveis
const fetchTrainings = async () => {
try {
setLoadingTrainings(true);
const response = await axios.get('/trainings/my-trainings?page=0&size=100');
setAvailableTrainings(response.data.content);
setLoadingTrainings(false);
} catch (err) {
console.error('Erro ao carregar treinos:', err);
setLoadingTrainings(false);
}
};
fetchTrainings();
}, []);
const handleChange = (e) => {
const { name, value, type, checked } = e.target;
setPlan(prev => ({
...prev,
[name]: type === 'checkbox' ? checked : value
}));
};
const handleAddTraining = () => {
if (availableTrainings.length === 0) return;
const newTraining = {
trainingId: availableTrainings[0].id,
dayOfWeek: 'MONDAY',
order: 1
};
setPlan(prev => ({
...prev,
trainings: [...prev.trainings, newTraining]
}));
};
const handleRemoveTraining = (index) => {
const newTrainings = [...plan.trainings];
newTrainings.splice(index, 1);
setPlan(prev => ({
...prev,
trainings: newTrainings
}));
};
const handleTrainingChange = (index, field, value) => {
const newTrainings = [...plan.trainings];
newTrainings[index] = {
...newTrainings[index],
[field]: value
};
setPlan(prev => ({
...prev,
trainings: newTrainings
}));
};
const handleSubmit = async (e) => {
e.preventDefault();
// Validação básica
if (!plan.name || !plan.description || plan.trainings.length === 0) {
setError('Preencha todos os campos obrigatórios e adicione pelo menos um treino.');
return;
}
setLoading(true);
setError(null);
setSuccess(false);
try {
const response = await axios.post('/training-plans', plan);
setLoading(false);
setSuccess(true);
// Resetar formulário
setPlan({
name: '',
description: '',
trainings: [],
isPublic: false,
difficulty: '',
goal: '',
duration: 12
});
} catch (err) {
setLoading(false);
setError(err.response?.data?.message || 'Erro ao criar plano de treino');
}
};
if (loadingTrainings) return <div>Carregando treinos...</div>;
if (availableTrainings.length === 0) return <div>Você não tem treinos cadastrados. Crie treinos primeiro.</div>;
return (
<div className="training-plan-form">
<h2>Criar Novo Plano de Treino</h2>
{error && <div className="error-message">{error}</div>}
{success && <div className="success-message">Plano de treino criado com sucesso!</div>}
<form onSubmit={handleSubmit}>
<div className="form-group">
<label>Nome *</label>
<input
type="text"
name="name"
value={plan.name}
onChange={handleChange}
required
/>
</div>
<div className="form-group">
<label>Descrição *</label>
<textarea
name="description"
value={plan.description}
onChange={handleChange}
required
/>
</div>
<div className="form-group">
<label>Objetivo</label>
<select
name="goal"
value={plan.goal}
onChange={handleChange}
>
<option value="">Selecione um objetivo</option>
<option value="HIPERTROFIA">Hipertrofia</option>
<option value="EMAGRECIMENTO">Emagrecimento</option>
<option value="RESISTENCIA">Resistência</option>
<option value="FORCA">Força</option>
<option value="OUTRO">Outro</option>
</select>
</div>
<div className="form-group">
<label>Dificuldade</label>
<select
name="difficulty"
value={plan.difficulty}
onChange={handleChange}
>
<option value="">Selecione a dificuldade</option>
<option value="INICIANTE">Iniciante</option>
<option value="INTERMEDIARIO">Intermediário</option>
<option value="AVANCADO">Avançado</option>
</select>
</div>
<div className="form-group">
<label>Duração (semanas)</label>
<input
type="number"
name="duration"
value={plan.duration}
onChange={handleChange}
min="1"
/>
</div>
<div className="form-group">
<label className="checkbox-label">
<input
type="checkbox"
name="isPublic"
checked={plan.isPublic}
onChange={handleChange}
/>
Tornar plano público
</label>
<small>Planos públicos podem ser vistos e utilizados por outros personal trainers.</small>
</div>
<div className="trainings-section">
<h3>Treinos</h3>
<button type="button" onClick={handleAddTraining}>
Adicionar Treino
</button>
{plan.trainings.length === 0 && (
<p className="no-trainings">Nenhum treino adicionado. Clique no botão acima para adicionar.</p>
)}
{plan.trainings.map((training, index) => (
<div key={index} className="training-item">
<div className="training-header">
<h4>Treino {index + 1}</h4>
<button
type="button"
onClick={() => handleRemoveTraining(index)}
>
Remover
</button>
</div>
<div className="training-form">
<div className="form-group">
<label>Treino *</label>
<select
value={training.trainingId}
onChange={(e) => handleTrainingChange(index, 'trainingId', Number(e.target.value))}
required
>
{availableTrainings.map(t => (
<option key={t.id} value={t.id}>
{t.name}
</option>
))}
</select>
</div>
<div className="form-group">
<label>Dia da Semana *</label>
<select
value={training.dayOfWeek}
onChange={(e) => handleTrainingChange(index, 'dayOfWeek', e.target.value)}
required
>
<option value="MONDAY">Segunda-feira</option>
<option value="TUESDAY">Terça-feira</option>
<option value="WEDNESDAY">Quarta-feira</option>
<option value="THURSDAY">Quinta-feira</option>
<option value="FRIDAY">Sexta-feira</option>
<option value="SATURDAY">Sábado</option>
<option value="SUNDAY">Domingo</option>
</select>
</div>
<div className="form-group">
<label>Ordem *</label>
<input
type="number"
value={training.order}
onChange={(e) => handleTrainingChange(index, 'order', Number(e.target.value))}
min="1"
required
/>
<small>Ordem do treino no dia (se houver mais de um treino no mesmo dia)</small>
</div>
</div>
</div>
))}
</div>
<button type="submit" disabled={loading}>
{loading ? 'Criando...' : 'Criar Plano de Treino'}
</button>
</form>
</div>
);
};
export default TrainingPlanForm;