File size: 17,154 Bytes
6aa6081
 
 
fc9e304
 
 
6aa6081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc9e304
6aa6081
 
 
 
fc9e304
6aa6081
fc9e304
6aa6081
fc9e304
6aa6081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc9e304
 
 
6aa6081
fc9e304
 
 
 
 
 
 
6aa6081
 
 
fc9e304
 
 
 
 
6aa6081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc9e304
6aa6081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc9e304
 
 
6aa6081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc9e304
6aa6081
 
 
 
 
fc9e304
 
 
 
 
6aa6081
 
 
 
 
 
 
 
 
fc9e304
6aa6081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
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<SectionSchedule[]>([]);
  const [loading, setLoading] = useState(true);
  const [form, setForm] = useState({ day_of_week: 0, slot_idx: 0, subject_id: '' });
  const [localSubjects, setLocalSubjects] = useState<DropdownSubject[]>([]);
  const [showNewSubject, setShowNewSubject] = useState(false);
  const [newSubjectName, setNewSubjectName] = useState('');
  const [newSubjectCode, setNewSubjectCode] = useState('');
  const [selectedBlockIdx, setSelectedBlockIdx] = useState<number | null>(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<HTMLDivElement>(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<string>();
  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 (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl max-w-5xl w-full max-h-[90vh] flex flex-col" onClick={(e) => e.stopPropagation()} ref={modalRef} tabIndex={-1} onKeyDown={handleKeyDown}>
        <div className="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between rounded-t-2xl shrink-0">
          <h2 className="text-xl font-bold">Horarios — {sectionName}</h2>
          <div className="flex items-center gap-3">
            {copiedSubject && <span className="text-sm text-blue-600 font-medium">Copiado: {copiedSubject.subject_name || 'Sin materia'} <button className="text-gray-400 hover:text-gray-600 ml-1" onClick={() => setCopiedSubject(null)}>&times;</button></span>}
            <label className="flex items-center gap-1.5 text-sm text-gray-500 cursor-pointer select-none">
              <input type="checkbox" checked={showWeekend} onChange={(e) => setShowWeekend(e.target.checked)} className="rounded" />
              Mostrar fin de semana
            </label>
            <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-2xl leading-none">&times;</button>
          </div>
        </div>
        <div className="p-4 overflow-auto flex-1">
          {loading ? (
            <div className="flex items-center justify-center py-24"><LoadingState /></div>
          ) : (
          <div className="grid gap-3" style={{ gridTemplateColumns: `120px repeat(${visibleDays.length}, 1fr)` }}>
            <div className="text-base text-gray-400 font-medium self-end pb-2 pl-1">Hora</div>
            {visibleDays.map((d, i) => (
              <div key={i} className="text-base font-semibold text-gray-600 text-center pb-2 border-b-2 border-gray-200">{d.slice(0, 3)}</div>
            ))}
            {allSlots.map((slot, rowIdx) => (
              <div key={rowIdx} className="contents">
                <div className={`text-base text-gray-500 font-mono pt-1.5 pr-1 text-right self-start ${rowIdx >= FIXED_SLOTS.length ? 'italic' : ''}`}>
                  {slot.entry}<br/><span className="text-gray-300">{slot.exit}</span>
                </div>
                {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 (
                    <div
                      key={vIdx}
                      className={`min-h-[90px] rounded-lg border-2 p-2 transition-colors cursor-pointer ${
                        targetCell?.day_of_week === dayIdx && targetCell?.entry_time === slot.entry && targetCell?.exit_time === slot.exit
                          ? 'border-green-400 bg-green-50'
                          : cellBlocks.length > 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 (
                          <div key={bIdx}
                            draggable
                            onClick={(e) => {
                              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}` : ''}`}
                          >
                            <div className="flex items-center justify-between gap-2">
                              <span>{block.entry_time}–{block.exit_time}</span>
                              <button className="text-sm opacity-60 hover:opacity-100 shrink-0" onClick={(e) => { e.stopPropagation(); removeRow(items.indexOf(block)); }}>&times;</button>
                            </div>
                            {block.subject_name && (
                              <div className="text-sm opacity-75 mt-0.5">
                                {block.subject_name}{block.teacher_name ? ` — ${block.teacher_name}` : ''}
                              </div>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  );
                })}
              </div>
            ))}
          </div>
          )}
        </div>
        <div className="sticky bottom-0 bg-white border-t border-gray-200 px-6 py-4 flex items-center gap-3 shrink-0 flex-wrap">
          <span className="text-base text-gray-500 font-medium">Agregar bloque</span>
          <select value={form.day_of_week} onChange={(e) => setForm({ ...form, day_of_week: Number(e.target.value) })} className="border border-gray-300 rounded-lg px-3 py-2 text-base">
            {visibleDays.map((d, i) => <option key={i} value={DAY_NAMES.indexOf(d)}>{d}</option>)}
          </select>
          <select value={form.slot_idx} onChange={(e) => setForm({ ...form, slot_idx: Number(e.target.value) })} className="border border-gray-300 rounded-lg px-3 py-2 text-base">
            {FIXED_SLOTS.map((s, i) => <option key={i} value={i}>{s.entry}–{s.exit}</option>)}
          </select>
          <select value={form.subject_id} onChange={(e) => setForm({ ...form, subject_id: e.target.value })} className="border border-gray-300 rounded-lg px-3 py-2 text-base">
            <option value="">Sin materia</option>
            {localSubjects.map((sub) => <option key={sub.id} value={sub.id}>{sub.name}</option>)}
          </select>
          {!showNewSubject ? (
            <button className="text-blue-600 hover:text-blue-800 text-sm font-medium px-2 py-1.5 rounded-lg hover:bg-blue-50 transition" onClick={() => setShowNewSubject(true)}>+ Crear materia</button>
          ) : (
            <div className="flex items-center gap-2">
              <input type="text" value={newSubjectName} onChange={(e) => setNewSubjectName(e.target.value)} placeholder="Nombre" className="border border-gray-300 rounded-lg px-3 py-2 text-base w-40" />
              <input type="text" value={newSubjectCode} onChange={(e) => 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(); }} />
              <button className="bg-green-600 text-white px-3 py-2 rounded-lg hover:bg-green-700 transition text-sm" onClick={handleCreateSubject}>Guardar</button>
              <button className="text-gray-500 hover:text-gray-700 text-sm px-2" onClick={() => { setShowNewSubject(false); setNewSubjectName(''); setNewSubjectCode(''); }}>Cancelar</button>
            </div>
          )}
          <button className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition text-base inline-flex items-center justify-center gap-1" onClick={addRow}>+ Agregar</button>
        </div>
        {!copiedSubject && targetCell && (
          <div className="px-6 py-2 text-xs text-gray-400 border-t border-gray-100 bg-gray-50/50">
            Haz clic en un bloque y presiona Ctrl+C para copiar, luego Ctrl+V para pegar en la celda seleccionada (verde)
          </div>
        )}
      </div>
    </div>
  );
}