import React, { useEffect, useMemo, useRef, useState } from 'react'; import { ArrowDownIcon, ArrowUpIcon, PencilIcon, TrashIcon } from '@phosphor-icons/react'; import { adminApi, instructorApi, LearningPath, LearningPathInput, TrailCourseOption } from '../../services/api'; import { useToast } from '../../context/ToastContext'; import { CourseCoverImage } from '../CourseCoverImage'; import { Select } from '../ui/Select'; import { ConfirmDialog } from '../ui/ConfirmDialog'; import { PlusMockIcon } from '../ui/MockupIcons'; const emptyInput = (): LearningPathInput => ({ title: '', description: '', coverImageUrl: null, coverImageZoom: 1, coverImagePositionX: 50, coverImagePositionY: 50, status: 'draft', courseIds: [] }); const toInput = (path: LearningPath): LearningPathInput => ({ title: path.title, description: path.description, coverImageUrl: path.coverImageUrl, coverImageZoom: path.coverImageZoom, coverImagePositionX: path.coverImagePositionX, coverImagePositionY: path.coverImagePositionY, status: path.status === 'published' ? 'published' : 'draft', courseIds: path.courses.map((course) => course.id) }); export const TrailManager: React.FC<{ onChanged?: () => void }> = ({ onChanged }) => { const { showToast } = useToast(); const [paths, setPaths] = useState([]); const [courses, setCourses] = useState([]); const [loading, setLoading] = useState(true); const [editorOpen, setEditorOpen] = useState(false); const [editing, setEditing] = useState(null); const [input, setInput] = useState(emptyInput()); const [courseToAdd, setCourseToAdd] = useState(''); const [saving, setSaving] = useState(false); const [uploading, setUploading] = useState(false); const [coverConfigured, setCoverConfigured] = useState(false); const [deleteTarget, setDeleteTarget] = useState(null); const coverInput = useRef(null); const load = async () => { setLoading(true); try { const [pathsResponse, coursesResponse] = await Promise.all([adminApi.listPaths(), adminApi.listPathCourses()]); setPaths(pathsResponse.data); setCourses(coursesResponse.data); } catch { showToast('Não foi possível carregar as trilhas.', 'error'); } finally { setLoading(false); } }; useEffect(() => { void load(); instructorApi.coverConfiguration().then((response) => setCoverConfigured(response.data.configured)).catch(() => setCoverConfigured(false)); }, []); const selectedCourses = useMemo(() => input.courseIds.map((id) => courses.find((course) => course.id === id)).filter((course): course is TrailCourseOption => Boolean(course)), [courses, input.courseIds]); const availableCourses = courses.filter((course) => !input.courseIds.includes(course.id)); const openNew = () => { setEditing(null); setInput(emptyInput()); setCourseToAdd(''); setEditorOpen(true); }; const openEdit = (path: LearningPath) => { setEditing(path); setInput(toInput(path)); setCourseToAdd(''); setEditorOpen(true); }; const uploadCover = async (file?: File) => { if (!file) return; if (!coverConfigured) { showToast('O envio de imagens ainda não está configurado.', 'error'); return; } setUploading(true); try { const response = await instructorApi.uploadCover(file); setInput((current) => ({ ...current, coverImageUrl: response.data.coverImageUrl })); } catch { showToast('Não foi possível enviar a capa.', 'error'); } finally { setUploading(false); } }; const save = async (event: React.FormEvent) => { event.preventDefault(); if (!input.title.trim()) { showToast('Informe o nome da trilha.', 'error'); return; } if (!input.courseIds.length) { showToast('Adicione pelo menos um curso.', 'error'); return; } setSaving(true); try { if (editing) await adminApi.updatePath(editing.id, input); else await adminApi.createPath(input); showToast(editing ? 'Trilha atualizada.' : 'Trilha criada.', 'success'); setEditorOpen(false); await load(); onChanged?.(); } catch (error) { showToast(error instanceof Error ? error.message : 'Não foi possível salvar a trilha.', 'error'); } finally { setSaving(false); } }; const addCourse = () => { if (!courseToAdd) return; setInput((current) => ({ ...current, courseIds: [...current.courseIds, courseToAdd] })); setCourseToAdd(''); }; const moveCourse = (index: number, direction: -1 | 1) => { const target = index + direction; if (target < 0 || target >= input.courseIds.length) return; const next = [...input.courseIds]; [next[index], next[target]] = [next[target], next[index]]; setInput((current) => ({ ...current, courseIds: next })); }; const removeCourse = (courseId: string) => setInput((current) => ({ ...current, courseIds: current.courseIds.filter((id) => id !== courseId) })); const performDelete = async () => { if (!deleteTarget) return; try { await adminApi.deletePath(deleteTarget.id); setPaths((current) => current.filter((path) => path.id !== deleteTarget.id)); setDeleteTarget(null); showToast('Trilha excluída. Os cursos foram preservados.', 'success'); onChanged?.(); } catch { showToast('Não foi possível excluir a trilha.', 'error'); } }; if (loading) return
Carregando trilhas…
; return <>

Trilhas

{paths.length ?
{paths.map((path) =>
{path.coverImageUrl ? : null} {path.title}{path.status === 'published' ? 'Publicada' : 'Rascunho'} · {path.courses.length} {path.courses.length === 1 ? 'curso' : 'cursos'}
)}
:

Nenhuma trilha criada ainda.

} {editorOpen &&
{ if (event.target === event.currentTarget) setEditorOpen(false); }}>

{editing ? 'Editar trilha' : 'Nova trilha'}

Organize cursos existentes na ordem em que os alunos devem assisti-los.

setInput((current) => ({ ...current, title: event.target.value }))} maxLength={160} required />