import { useState, useEffect, useRef } from 'react'; import { listSectionSchedules, updateSectionSchedules, type SectionSchedule } from '../services/sectionScheduleService'; import { createSubject } from '../services/subjectService'; import LoadingState from './LoadingState'; type DropdownSubject = { id: number; name: string }; const DAY_NAMES = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo']; const COLORS = [ 'bg-blue-100 border-blue-300 text-blue-700', 'bg-emerald-100 border-emerald-300 text-emerald-700', 'bg-amber-100 border-amber-300 text-amber-700', 'bg-purple-100 border-purple-300 text-purple-700', 'bg-rose-100 border-rose-300 text-rose-700', 'bg-cyan-100 border-cyan-300 text-cyan-700', 'bg-orange-100 border-orange-300 text-orange-700', 'bg-teal-100 border-teal-300 text-teal-700', ]; const FIXED_SLOTS = Array.from({ length: 11 }, (_, i) => { const h = 7 + i; const entry = `${String(h).padStart(2, '0')}:00`; const exit = `${String(h + 1).padStart(2, '0')}:00`; return { entry, exit }; }); interface Props { sectionId: number; sectionName: string; sectionSubjects: { subject_id: number; subject_name?: string | null }[]; open: boolean; onClose: () => void; } export default function ScheduleModal({ sectionId, sectionName, sectionSubjects, open, onClose }: Props) { const [items, setItems] = useState([]); const [loading, setLoading] = useState(true); const [form, setForm] = useState({ day_of_week: 0, slot_idx: 0, subject_id: '' }); const [localSubjects, setLocalSubjects] = useState([]); const [showNewSubject, setShowNewSubject] = useState(false); const [newSubjectName, setNewSubjectName] = useState(''); const [newSubjectCode, setNewSubjectCode] = useState(''); const [selectedBlockIdx, setSelectedBlockIdx] = useState(null); const [copiedSubject, setCopiedSubject] = useState<{ subject_id: number | null; subject_name: string | null } | null>(null); const [targetCell, setTargetCell] = useState<{ day_of_week: number; entry_time: string; exit_time: string } | null>(null); const [showWeekend, setShowWeekend] = useState(false); const modalRef = useRef(null); const visibleDays = DAY_NAMES.filter((_, i) => showWeekend || i < 5); useEffect(() => { if (open && modalRef.current) modalRef.current.focus(); }, [open]); // Sync filtered subject list from the section's assigned subjects on open. // Subjects newly created via the inline "+ Crear materia" button accumulate // here so they remain available in the dropdown for this modal session. useEffect(() => { setLocalSubjects( sectionSubjects.map((ss) => ({ id: ss.subject_id, name: ss.subject_name || '', })) ); }, [sectionSubjects, open]); useEffect(() => { if (!open) return; setLoading(true); listSectionSchedules(sectionId) .then(setItems) .catch(() => setItems([])) .finally(() => setLoading(false)); setForm({ day_of_week: 0, slot_idx: 0, subject_id: '' }); }, [open, sectionId]); const addRow = async () => { const slot = FIXED_SLOTS[form.slot_idx]; if (!slot) return; const newItems = [...items, { id: 0, section_id: sectionId, account_id: 0, day_of_week: form.day_of_week, entry_time: slot.entry, exit_time: slot.exit, subject_id: form.subject_id ? Number(form.subject_id) : null, subject_name: localSubjects.find((s) => s.id === Number(form.subject_id))?.name || null, }]; setItems(newItems); try { const saved = await updateSectionSchedules(sectionId, newItems.map((i) => ({ day_of_week: i.day_of_week, entry_time: i.entry_time, exit_time: i.exit_time, subject_id: i.subject_id, }))); setItems(saved); } catch { /* ignore */ } setForm({ day_of_week: 0, slot_idx: 0, subject_id: '' }); }; const removeRow = async (index: number) => { const newItems = items.filter((_, i) => i !== index); setItems(newItems); try { const saved = await updateSectionSchedules(sectionId, newItems.map((i) => ({ day_of_week: i.day_of_week, entry_time: i.entry_time, exit_time: i.exit_time, subject_id: i.subject_id, }))); setItems(saved); } catch { /* ignore */ } }; const handleCreateSubject = async () => { const name = newSubjectName.trim(); const code = newSubjectCode.trim(); if (!name || !code) { alert('Nombre y código son requeridos'); return; } try { const created = await createSubject({ name, code }); setLocalSubjects((prev) => [...prev, { id: created.id, name: created.name }]); setForm((prev) => ({ ...prev, subject_id: String(created.id) })); setNewSubjectName(''); setNewSubjectCode(''); setShowNewSubject(false); } catch { /* ignore */ } }; const handlePaste = async () => { if (!copiedSubject || !targetCell) return; const newItems = [...items, { id: 0, section_id: sectionId, account_id: 0, day_of_week: targetCell.day_of_week, entry_time: targetCell.entry_time, exit_time: targetCell.exit_time, subject_id: copiedSubject.subject_id, subject_name: copiedSubject.subject_name, }]; setItems(newItems); try { const saved = await updateSectionSchedules(sectionId, newItems.map((i) => ({ day_of_week: i.day_of_week, entry_time: i.entry_time, exit_time: i.exit_time, subject_id: i.subject_id, }))); setItems(saved); } catch { /* ignore */ } }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.ctrlKey && e.key === 'c') { if (selectedBlockIdx !== null && items[selectedBlockIdx]) { e.preventDefault(); setCopiedSubject({ subject_id: items[selectedBlockIdx].subject_id, subject_name: items[selectedBlockIdx].subject_name }); } } if (e.ctrlKey && e.key === 'v') { e.preventDefault(); handlePaste(); } if (e.key === 'Escape') { setSelectedBlockIdx(null); setTargetCell(null); } }; if (!open) return null; const customSlots: { entry: string; exit: string }[] = []; const seenCustom = new Set(); for (const item of items) { const key = `${item.entry_time}-${item.exit_time}`; if (seenCustom.has(key)) continue; seenCustom.add(key); const isFixed = FIXED_SLOTS.some((s) => s.entry === item.entry_time && s.exit === item.exit_time); if (!isFixed) customSlots.push({ entry: item.entry_time, exit: item.exit_time }); } customSlots.sort((a, b) => a.entry.localeCompare(b.entry)); const allSlots = [...FIXED_SLOTS, ...customSlots]; return (
e.stopPropagation()} ref={modalRef} tabIndex={-1} onKeyDown={handleKeyDown}>

Horarios — {sectionName}

{copiedSubject && Copiado: {copiedSubject.subject_name || 'Sin materia'} }
{loading ? (
) : (
Hora
{visibleDays.map((d, i) => (
{d.slice(0, 3)}
))} {allSlots.map((slot, rowIdx) => (
= FIXED_SLOTS.length ? 'italic' : ''}`}> {slot.entry}
{slot.exit}
{visibleDays.map((dayName, vIdx) => { const dayIdx = DAY_NAMES.indexOf(dayName); const cellBlocks = items.filter((b) => b.day_of_week === dayIdx && b.entry_time === slot.entry && b.exit_time === slot.exit); return (
0 ? 'border-transparent' : 'border-dashed border-gray-200 hover:border-blue-300 hover:bg-blue-50/30' }`} onClick={() => { setTargetCell({ day_of_week: dayIdx, entry_time: slot.entry, exit_time: slot.exit }); const slotIdx = FIXED_SLOTS.findIndex((s) => s.entry === slot.entry && s.exit === slot.exit); setForm((prev) => ({ day_of_week: dayIdx, slot_idx: slotIdx >= 0 ? slotIdx : prev.slot_idx, subject_id: '', })); }} onDragOver={(e) => { e.preventDefault(); e.currentTarget.classList.add('border-blue-400', 'bg-blue-100'); }} onDragLeave={(e) => { e.currentTarget.classList.remove('border-blue-400', 'bg-blue-100'); }} onDrop={(e) => { e.preventDefault(); e.currentTarget.classList.remove('border-blue-400', 'bg-blue-100'); const draggedIdx = Number(e.dataTransfer.getData('text/plain')); if (!isNaN(draggedIdx)) { const newItems = items.map((item, i) => i === draggedIdx ? { ...item, day_of_week: dayIdx, entry_time: slot.entry, exit_time: slot.exit } : item ); setItems(newItems); updateSectionSchedules(sectionId, newItems.map((i) => ({ day_of_week: i.day_of_week, entry_time: i.entry_time, exit_time: i.exit_time, subject_id: i.subject_id, }))).then(setItems).catch(() => {}); } }} > {cellBlocks.map((block) => { const bIdx = items.indexOf(block); const colorClass = block?.subject_id ? COLORS[block.subject_id! % COLORS.length] : 'bg-gray-100 border-gray-200 text-gray-500'; const isSelected = selectedBlockIdx === bIdx; return (
{ e.stopPropagation(); const willSelect = !isSelected; setSelectedBlockIdx(willSelect ? bIdx : null); if (willSelect) { const slotIdx = FIXED_SLOTS.findIndex((s) => s.entry === block.entry_time && s.exit === block.exit_time); setForm((prev) => ({ day_of_week: block.day_of_week, slot_idx: slotIdx >= 0 ? slotIdx : prev.slot_idx, subject_id: block.subject_id != null ? String(block.subject_id) : '', })); } }} onDragStart={(e) => { e.dataTransfer.setData('text/plain', String(bIdx)); e.dataTransfer.effectAllowed = 'move'; }} className={`text-base leading-snug font-medium rounded-md px-4 py-3 border cursor-pointer mb-1.5 last:mb-0 ${colorClass} ${isSelected ? 'ring-2 ring-blue-500' : ''}`} title={`${block.entry_time}–${block.exit_time}${block.subject_name ? ` · ${block.subject_name}` : ''}${block.teacher_name ? ` · ${block.teacher_name}` : ''}`} >
{block.entry_time}–{block.exit_time}
{block.subject_name && (
{block.subject_name}{block.teacher_name ? ` — ${block.teacher_name}` : ''}
)}
); })}
); })}
))}
)}
Agregar bloque {!showNewSubject ? ( ) : (
setNewSubjectName(e.target.value)} placeholder="Nombre" className="border border-gray-300 rounded-lg px-3 py-2 text-base w-40" /> setNewSubjectCode(e.target.value)} placeholder="Código" className="border border-gray-300 rounded-lg px-3 py-2 text-base w-32" onKeyDown={(e) => { if (e.key === 'Enter') handleCreateSubject(); }} />
)}
{!copiedSubject && targetCell && (
Haz clic en un bloque y presiona Ctrl+C para copiar, luego Ctrl+V para pegar en la celda seleccionada (verde)
)}
); }