import React, { useState, useEffect } from "react"; import { Course, Institution } from "../types"; import { Input, Select } from "./Input"; import { Button } from "./Button"; import { GraduationCap, X, Check, AlertCircle, AlertTriangle } from "lucide-react"; import { getInstitutions, getGraduationYears } from "../services/apiService"; interface CourseFormProps { onCancel: () => void; onSubmit: (data: Partial) => void; initialData?: Course; userId: string; institutions: Institution[]; } const GRADUATION_TYPES = [ "Bacharelado", "Licenciatura", "Tecnológico", "Especialização", "Mestrado", "Doutorado", ]; export const CourseForm: React.FC = ({ onCancel, onSubmit, initialData, userId, institutions, }) => { const currentYear = new Date().getFullYear(); const [formData, setFormData] = useState>( initialData || { name: "", institutionId: "", year: currentYear, semester: 1, graduationType: "", createdAt: new Date().toISOString(), createdBy: userId, isActive: true, } ); const [showToast, setShowToast] = useState(false); const [error, setError] = useState(""); const [backendInstitutions, setBackendInstitutions] = useState>([]); const [graduationYears, setGraduationYears] = useState([]); const [isBackendDown, setIsBackendDown] = useState(false); const [isLoadingData, setIsLoadingData] = useState(true); // Buscar dados do backend useEffect(() => { const fetchBackendData = async () => { setIsLoadingData(true); const [institutionsResponse, yearsResponse] = await Promise.all([ getInstitutions(), getGraduationYears() ]); if (institutionsResponse.isBackendDown || yearsResponse.isBackendDown) { setIsBackendDown(true); } else { setIsBackendDown(false); if (institutionsResponse.data) { setBackendInstitutions(institutionsResponse.data); } if (yearsResponse.data) { setGraduationYears(yearsResponse.data); } } setIsLoadingData(false); }; fetchBackendData(); }, []); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); // Validações if (!formData.name || formData.name.trim().length < 3) { setError("Nome do curso deve ter pelo menos 3 caracteres"); return; } if (!formData.institutionId) { setError("Selecione uma universidade"); return; } if (!formData.graduationType) { setError("Selecione o tipo de graduação"); return; } setShowToast(true); setTimeout(() => { onSubmit(formData); }, 1000); }; const handleChange = (field: keyof Course, value: any) => { setFormData((prev) => ({ ...prev, [field]: value })); setError(""); // Limpa erro ao editar }; return (
{/* Success Toast */} {showToast && (

Sucesso!

Curso cadastrado com sucesso.

)} {/* Form Header */}

{initialData ? "Editar Curso/Turma" : "Cadastrar Curso/Turma"}

Registre as turmas disponíveis para eventos fotográficos

{/* Erro global */} {error && (

{error}

)} {/* Informações do Curso */}

Informações do Curso

handleChange("name", e.target.value)} disabled={isLoadingData || isBackendDown} className="w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-brand-gold disabled:bg-gray-100 disabled:cursor-not-allowed" > {backendInstitutions.map((inst) => ( ))} {isBackendDown && (
Backend não está rodando. Não é possível carregar os cursos.
)} {isLoadingData && !isBackendDown && (
Carregando cursos...
)}
{isBackendDown && (
Backend offline
)}
({ value: t, label: t }))} value={formData.graduationType || ""} onChange={(e) => handleChange("graduationType", e.target.value)} required />
{/* Status Ativo/Inativo */}
handleChange("isActive", e.target.checked)} className="w-4 h-4 text-brand-gold border-gray-300 rounded focus:ring-brand-gold" />
{/* Actions */}
); };