fromis_9/frontend/src/pages/pc/admin/AdminScheduleForm.jsx

1192 lines
55 KiB
React
Raw Normal View History

import { useState, useEffect, useRef } from 'react';
import { useNavigate, Link, useParams } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
LogOut, Home, ChevronRight, Calendar, Save, X, Upload, Link as LinkIcon,
ChevronLeft, ChevronDown, Clock, Image, Users, Check, Plus
} from 'lucide-react';
import Toast from '../../../components/Toast';
import Lightbox from '../../../components/common/Lightbox';
// 커스텀 데이트픽커 컴포넌트 (AdminMemberEdit.jsx에서 가져옴)
function CustomDatePicker({ value, onChange, placeholder = '날짜 선택' }) {
const [isOpen, setIsOpen] = useState(false);
const [viewMode, setViewMode] = useState('days');
const [viewDate, setViewDate] = useState(() => {
if (value) return new Date(value);
return new Date();
});
const ref = useRef(null);
useEffect(() => {
const handleClickOutside = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
setIsOpen(false);
setViewMode('days');
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const year = viewDate.getFullYear();
const month = viewDate.getMonth();
const firstDay = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
const days = [];
for (let i = 0; i < firstDay; i++) {
days.push(null);
}
for (let i = 1; i <= daysInMonth; i++) {
days.push(i);
}
const startYear = Math.floor(year / 10) * 10 - 1;
const years = Array.from({ length: 12 }, (_, i) => startYear + i);
const prevMonth = () => setViewDate(new Date(year, month - 1, 1));
const nextMonth = () => setViewDate(new Date(year, month + 1, 1));
const prevYearRange = () => setViewDate(new Date(year - 10, month, 1));
const nextYearRange = () => setViewDate(new Date(year + 10, month, 1));
const selectDate = (day) => {
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
onChange(dateStr);
setIsOpen(false);
setViewMode('days');
};
const selectYear = (y) => {
setViewDate(new Date(y, month, 1));
setViewMode('months');
};
const selectMonth = (m) => {
setViewDate(new Date(year, m, 1));
setViewMode('days');
};
const formatDisplayDate = (dateStr) => {
if (!dateStr) return '';
const [y, m, d] = dateStr.split('-');
return `${y}${parseInt(m)}${parseInt(d)}`;
};
const isSelected = (day) => {
if (!value || !day) return false;
const [y, m, d] = value.split('-');
return parseInt(y) === year && parseInt(m) === month + 1 && parseInt(d) === day;
};
const isToday = (day) => {
if (!day) return false;
const today = new Date();
return today.getFullYear() === year && today.getMonth() === month && today.getDate() === day;
};
const isCurrentYear = (y) => new Date().getFullYear() === y;
const isCurrentMonth = (m) => {
const today = new Date();
return today.getFullYear() === year && today.getMonth() === m;
};
const months = ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'];
return (
<div ref={ref} className="relative">
<button
type="button"
onClick={() => setIsOpen(!isOpen)}
className="w-full px-4 py-3 border border-gray-200 rounded-xl bg-white flex items-center justify-between hover:border-gray-300 transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
>
<span className={value ? 'text-gray-900' : 'text-gray-400'}>
{value ? formatDisplayDate(value) : placeholder}
</span>
<Calendar size={18} className="text-gray-400" />
</button>
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
transition={{ duration: 0.15 }}
className="absolute z-50 mt-2 bg-white border border-gray-200 rounded-xl shadow-lg p-4 w-80"
>
<div className="flex items-center justify-between mb-4">
<button
type="button"
onClick={viewMode === 'years' ? prevYearRange : prevMonth}
className="p-1.5 hover:bg-gray-100 rounded-lg transition-colors"
>
<ChevronLeft size={20} className="text-gray-600" />
</button>
<button
type="button"
onClick={() => setViewMode(viewMode === 'days' ? 'years' : 'days')}
className="font-medium text-gray-900 hover:text-primary transition-colors flex items-center gap-1"
>
{viewMode === 'years' ? `${years[0]} - ${years[years.length - 1]}` : `${year}${month + 1}`}
<ChevronDown size={16} className={`transition-transform ${viewMode !== 'days' ? 'rotate-180' : ''}`} />
</button>
<button
type="button"
onClick={viewMode === 'years' ? nextYearRange : nextMonth}
className="p-1.5 hover:bg-gray-100 rounded-lg transition-colors"
>
<ChevronRight size={20} className="text-gray-600" />
</button>
</div>
<AnimatePresence mode="wait">
{viewMode === 'years' && (
<motion.div
key="years"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
<div className="text-center text-sm text-gray-500 mb-3">년도</div>
<div className="grid grid-cols-4 gap-2 mb-4">
{years.map((y) => (
<button
key={y}
type="button"
onClick={() => selectYear(y)}
className={`py-2 rounded-lg text-sm transition-colors ${year === y ? 'bg-primary text-white' : 'hover:bg-gray-100 text-gray-700'} ${isCurrentYear(y) && year !== y ? 'border border-primary text-primary' : ''}`}
>
{y}
</button>
))}
</div>
<div className="text-center text-sm text-gray-500 mb-3"></div>
<div className="grid grid-cols-4 gap-2">
{months.map((m, i) => (
<button
key={m}
type="button"
onClick={() => selectMonth(i)}
className={`py-2 rounded-lg text-sm transition-colors ${month === i ? 'bg-primary text-white' : 'hover:bg-gray-100 text-gray-700'} ${isCurrentMonth(i) && month !== i ? 'border border-primary text-primary' : ''}`}
>
{m}
</button>
))}
</div>
</motion.div>
)}
{viewMode === 'months' && (
<motion.div
key="months"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
<div className="text-center text-sm text-gray-500 mb-3"> 선택</div>
<div className="grid grid-cols-4 gap-2">
{months.map((m, i) => (
<button
key={m}
type="button"
onClick={() => selectMonth(i)}
className={`py-2.5 rounded-lg text-sm transition-colors ${month === i ? 'bg-primary text-white' : 'hover:bg-gray-100 text-gray-700'} ${isCurrentMonth(i) && month !== i ? 'border border-primary text-primary' : ''}`}
>
{m}
</button>
))}
</div>
</motion.div>
)}
{viewMode === 'days' && (
<motion.div
key="days"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
<div className="grid grid-cols-7 gap-1 mb-2">
{['일', '월', '화', '수', '목', '금', '토'].map((d, i) => (
<div
key={d}
className={`text-center text-xs font-medium py-1 ${i === 0 ? 'text-red-400' : i === 6 ? 'text-blue-400' : 'text-gray-400'}`}
>
{d}
</div>
))}
</div>
<div className="grid grid-cols-7 gap-1">
{days.map((day, i) => (
<button
key={i}
type="button"
disabled={!day}
onClick={() => day && selectDate(day)}
className={`aspect-square rounded-lg text-sm flex items-center justify-center transition-colors ${!day ? '' : 'hover:bg-gray-100'} ${isSelected(day) ? 'bg-primary text-white hover:bg-primary-dark' : ''} ${isToday(day) && !isSelected(day) ? 'border border-primary text-primary' : ''} ${day && !isSelected(day) && !isToday(day) ? 'text-gray-700' : ''}`}
>
{day}
</button>
))}
</div>
</motion.div>
)}
</AnimatePresence>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
// 숫자 피커 컬럼 컴포넌트 (Vue 컴포넌트를 React로 변환)
function NumberPicker({ items, value, onChange }) {
const ITEM_HEIGHT = 40;
const containerRef = useRef(null);
const [offset, setOffset] = useState(0);
const offsetRef = useRef(0); // 드래그용 ref
const touchStartY = useRef(0);
const startOffset = useRef(0);
const isScrolling = useRef(false);
// offset 변경시 ref도 업데이트
useEffect(() => {
offsetRef.current = offset;
}, [offset]);
// 초기 위치 설정
useEffect(() => {
if (value !== null && value !== undefined) {
const index = items.indexOf(value);
if (index !== -1) {
const newOffset = -index * ITEM_HEIGHT;
setOffset(newOffset);
offsetRef.current = newOffset;
}
}
}, []);
// 값 변경시 위치 업데이트
useEffect(() => {
const index = items.indexOf(value);
if (index !== -1) {
const targetOffset = -index * ITEM_HEIGHT;
if (Math.abs(offset - targetOffset) > 1) {
setOffset(targetOffset);
offsetRef.current = targetOffset;
}
}
}, [value, items]);
const centerOffset = ITEM_HEIGHT; // 중앙 위치 오프셋
// 아이템이 중앙에 있는지 확인
const isItemInCenter = (item) => {
const itemIndex = items.indexOf(item);
const itemPosition = -itemIndex * ITEM_HEIGHT;
const tolerance = ITEM_HEIGHT / 2;
return Math.abs(offset - itemPosition) < tolerance;
};
// 오프셋 업데이트 (경계 제한)
const updateOffset = (newOffset) => {
const maxOffset = 0;
const minOffset = -(items.length - 1) * ITEM_HEIGHT;
return Math.min(maxOffset, Math.max(minOffset, newOffset));
};
// 중앙 아이템 업데이트
const updateCenterItem = (currentOffset) => {
const centerIndex = Math.round(-currentOffset / ITEM_HEIGHT);
if (centerIndex >= 0 && centerIndex < items.length) {
const centerItem = items[centerIndex];
if (value !== centerItem) {
onChange(centerItem);
}
}
};
// 가장 가까운 아이템에 스냅
const snapToClosestItem = (currentOffset) => {
const targetOffset = Math.round(currentOffset / ITEM_HEIGHT) * ITEM_HEIGHT;
setOffset(targetOffset);
offsetRef.current = targetOffset;
updateCenterItem(targetOffset);
};
// 터치 시작
const handleTouchStart = (e) => {
e.stopPropagation();
touchStartY.current = e.touches[0].clientY;
startOffset.current = offsetRef.current;
};
// 터치 이동
const handleTouchMove = (e) => {
e.stopPropagation();
const touchY = e.touches[0].clientY;
const deltaY = touchY - touchStartY.current;
const newOffset = updateOffset(startOffset.current + deltaY);
setOffset(newOffset);
offsetRef.current = newOffset;
};
// 터치 종료
const handleTouchEnd = (e) => {
e.stopPropagation();
snapToClosestItem(offsetRef.current);
};
// 마우스 휠 - 바깥 스크롤 방지
const handleWheel = (e) => {
e.preventDefault();
e.stopPropagation();
if (isScrolling.current) return;
isScrolling.current = true;
const newOffset = updateOffset(offsetRef.current - Math.sign(e.deltaY) * ITEM_HEIGHT);
setOffset(newOffset);
offsetRef.current = newOffset;
snapToClosestItem(newOffset);
setTimeout(() => {
isScrolling.current = false;
}, 50);
};
// 마우스 드래그
const handleMouseDown = (e) => {
e.preventDefault();
e.stopPropagation();
touchStartY.current = e.clientY;
startOffset.current = offsetRef.current;
const handleMouseMove = (moveEvent) => {
moveEvent.preventDefault();
const deltaY = moveEvent.clientY - touchStartY.current;
const newOffset = updateOffset(startOffset.current + deltaY);
setOffset(newOffset);
offsetRef.current = newOffset;
};
const handleMouseUp = () => {
snapToClosestItem(offsetRef.current);
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
};
// wheel 이벤트 passive false로 등록
useEffect(() => {
const container = containerRef.current;
if (container) {
container.addEventListener('wheel', handleWheel, { passive: false });
return () => container.removeEventListener('wheel', handleWheel);
}
}, []);
return (
<div
ref={containerRef}
className="relative w-16 h-[120px] overflow-hidden touch-none select-none cursor-grab active:cursor-grabbing"
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
onMouseDown={handleMouseDown}
>
{/* 중앙 선택 영역 */}
<div className="absolute top-1/2 left-1 right-1 h-10 -translate-y-1/2 bg-primary/10 rounded-lg z-0" />
{/* 피커 내부 */}
<div
className="relative transition-transform duration-150 ease-out"
style={{ transform: `translateY(${offset + centerOffset}px)` }}
>
{items.map((item) => (
<div
key={item}
className={`h-10 leading-10 text-center select-none transition-all duration-150 ${
isItemInCenter(item)
? 'text-primary text-lg font-bold'
: 'text-gray-300 text-base'
}`}
>
{item}
</div>
))}
</div>
</div>
);
}
// 커스텀 시간 피커 (Vue 컴포넌트 기반)
function CustomTimePicker({ value, onChange, placeholder = '시간 선택' }) {
const [isOpen, setIsOpen] = useState(false);
const ref = useRef(null);
// 현재 값 파싱
const parseValue = () => {
if (!value) return { hour: '12', minute: '00', period: '오후' };
const [h, m] = value.split(':');
const hour = parseInt(h);
const isPM = hour >= 12;
const hour12 = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;
return {
hour: String(hour12).padStart(2, '0'),
minute: m,
period: isPM ? '오후' : '오전'
};
};
const parsed = parseValue();
const [selectedHour, setSelectedHour] = useState(parsed.hour);
const [selectedMinute, setSelectedMinute] = useState(parsed.minute);
const [selectedPeriod, setSelectedPeriod] = useState(parsed.period);
// 외부 클릭 시 닫기
useEffect(() => {
const handleClickOutside = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
setIsOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
// 피커 열릴 때 현재 값으로 초기화
useEffect(() => {
if (isOpen) {
const parsed = parseValue();
setSelectedHour(parsed.hour);
setSelectedMinute(parsed.minute);
setSelectedPeriod(parsed.period);
}
}, [isOpen, value]);
// 시간 확정
const handleSave = () => {
let hour = parseInt(selectedHour);
if (selectedPeriod === '오후' && hour !== 12) hour += 12;
if (selectedPeriod === '오전' && hour === 12) hour = 0;
const timeStr = `${String(hour).padStart(2, '0')}:${selectedMinute}`;
onChange(timeStr);
setIsOpen(false);
};
// 취소
const handleCancel = () => {
setIsOpen(false);
};
// 초기화
const handleClear = () => {
onChange('');
setIsOpen(false);
};
// 표시용 포맷
const displayValue = () => {
if (!value) return placeholder;
const [h, m] = value.split(':');
const hour = parseInt(h);
const isPM = hour >= 12;
const hour12 = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;
return `${isPM ? '오후' : '오전'} ${hour12}:${m}`;
};
// 피커 아이템 데이터
const periods = ['오전', '오후'];
const hours = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
const minutes = Array.from({ length: 60 }, (_, i) => String(i).padStart(2, '0'));
return (
<div ref={ref} className="relative">
<button
type="button"
onClick={() => setIsOpen(!isOpen)}
className="w-full px-4 py-3 border border-gray-200 rounded-xl bg-white flex items-center justify-between hover:border-gray-300 transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
>
<span className={value ? 'text-gray-900' : 'text-gray-400'}>
{displayValue()}
</span>
<Clock size={18} className="text-gray-400" />
</button>
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
className="absolute top-full left-0 mt-2 bg-white rounded-2xl shadow-xl border border-gray-200 z-50 overflow-hidden"
>
{/* 피커 영역 */}
<div className="flex items-center justify-center px-4 py-4">
{/* 오전/오후 (맨 앞) */}
<NumberPicker
items={periods}
value={selectedPeriod}
onChange={setSelectedPeriod}
/>
{/* 시간 */}
<NumberPicker
items={hours}
value={selectedHour}
onChange={setSelectedHour}
/>
<span className="text-xl text-gray-300 font-medium mx-0.5">:</span>
{/* 분 */}
<NumberPicker
items={minutes}
value={selectedMinute}
onChange={setSelectedMinute}
/>
</div>
{/* 푸터 버튼 */}
<div className="flex items-center justify-between px-4 py-3 bg-gray-50">
<button
type="button"
onClick={handleClear}
className="px-3 py-1.5 text-sm text-gray-400 hover:text-gray-600 transition-colors"
>
초기화
</button>
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleCancel}
className="px-4 py-1.5 text-sm text-gray-600 hover:bg-gray-200 rounded-lg transition-colors"
>
취소
</button>
<button
type="button"
onClick={handleSave}
className="px-4 py-1.5 text-sm bg-primary text-white font-medium rounded-lg hover:bg-primary-dark transition-colors"
>
저장
</button>
</div>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
function AdminScheduleForm() {
const navigate = useNavigate();
const { id } = useParams();
const isEditMode = !!id;
const [user, setUser] = useState(null);
const [toast, setToast] = useState(null);
const [loading, setLoading] = useState(false);
const [members, setMembers] = useState([]);
// 폼 데이터 (날짜/시간 범위 지원)
const [formData, setFormData] = useState({
title: '',
startDate: '',
endDate: '',
startTime: '',
endTime: '',
isRange: false, // 범위 설정 여부
category: 'broadcast',
description: '',
url: '',
members: [],
images: []
});
// 이미지 미리보기
const [imagePreviews, setImagePreviews] = useState([]);
// 라이트박스 상태
const [lightboxOpen, setLightboxOpen] = useState(false);
const [lightboxIndex, setLightboxIndex] = useState(0);
// 삭제 다이얼로그 상태
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [deleteTargetIndex, setDeleteTargetIndex] = useState(null);
// 카테고리 목록
const categories = [
{ id: 'broadcast', name: '방송', color: 'blue' },
{ id: 'event', name: '이벤트', color: 'green' },
{ id: 'release', name: '발매', color: 'purple' },
{ id: 'concert', name: '콘서트', color: 'red' },
{ id: 'fansign', name: '팬사인회', color: 'pink' },
];
// 카테고리 색상
const getCategoryColor = (categoryId) => {
const colors = {
broadcast: 'bg-blue-500',
event: 'bg-green-500',
release: 'bg-purple-500',
concert: 'bg-red-500',
fansign: 'bg-pink-500',
};
return colors[categoryId] || 'bg-gray-500';
};
// Toast 자동 숨김
useEffect(() => {
if (toast) {
const timer = setTimeout(() => setToast(null), 3000);
return () => clearTimeout(timer);
}
}, [toast]);
useEffect(() => {
const token = localStorage.getItem('adminToken');
const userData = localStorage.getItem('adminUser');
if (!token || !userData) {
navigate('/admin');
return;
}
setUser(JSON.parse(userData));
fetchMembers();
}, [navigate]);
const fetchMembers = async () => {
try {
const res = await fetch('/api/members');
const data = await res.json();
setMembers(data.filter(m => !m.is_former));
} catch (error) {
console.error('멤버 로드 오류:', error);
}
};
const handleLogout = () => {
localStorage.removeItem('adminToken');
localStorage.removeItem('adminUser');
navigate('/admin');
};
// 멤버 토글
const toggleMember = (memberId) => {
const newMembers = formData.members.includes(memberId)
? formData.members.filter(id => id !== memberId)
: [...formData.members, memberId];
setFormData({ ...formData, members: newMembers });
};
// 전체 선택/해제
const toggleAllMembers = () => {
if (formData.members.length === members.length) {
setFormData({ ...formData, members: [] });
} else {
setFormData({ ...formData, members: members.map(m => m.id) });
}
};
// 다중 이미지 업로드
const handleImagesUpload = (e) => {
const files = Array.from(e.target.files);
const newImages = [...formData.images, ...files];
setFormData({ ...formData, images: newImages });
files.forEach(file => {
const reader = new FileReader();
reader.onloadend = () => {
setImagePreviews(prev => [...prev, reader.result]);
};
reader.readAsDataURL(file);
});
};
// 이미지 삭제 다이얼로그 열기
const openDeleteDialog = (index) => {
setDeleteTargetIndex(index);
setDeleteDialogOpen(true);
};
// 이미지 삭제 확인
const confirmDeleteImage = () => {
if (deleteTargetIndex !== null) {
const newImages = formData.images.filter((_, i) => i !== deleteTargetIndex);
const newPreviews = imagePreviews.filter((_, i) => i !== deleteTargetIndex);
setFormData({ ...formData, images: newImages });
setImagePreviews(newPreviews);
}
setDeleteDialogOpen(false);
setDeleteTargetIndex(null);
};
// 라이트박스 열기
const openLightbox = (index) => {
setLightboxIndex(index);
setLightboxOpen(true);
};
// 드래그 앤 드롭 상태
const [draggedIndex, setDraggedIndex] = useState(null);
const [dragOverIndex, setDragOverIndex] = useState(null);
// 드래그 시작
const handleDragStart = (e, index) => {
setDraggedIndex(index);
e.dataTransfer.effectAllowed = 'move';
// 드래그 이미지 설정
e.dataTransfer.setData('text/plain', index);
};
// 드래그 오버
const handleDragOver = (e, index) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
if (dragOverIndex !== index) {
setDragOverIndex(index);
}
};
// 드래그 종료
const handleDragEnd = () => {
setDraggedIndex(null);
setDragOverIndex(null);
};
// 드롭 - 이미지 순서 변경
const handleDrop = (e, dropIndex) => {
e.preventDefault();
if (draggedIndex === null || draggedIndex === dropIndex) {
handleDragEnd();
return;
}
// 새 배열 생성
const newPreviews = [...imagePreviews];
const newImages = [...formData.images];
// 드래그된 아이템 제거 후 새 위치에 삽입
const [movedPreview] = newPreviews.splice(draggedIndex, 1);
const [movedImage] = newImages.splice(draggedIndex, 1);
newPreviews.splice(dropIndex, 0, movedPreview);
newImages.splice(dropIndex, 0, movedImage);
setImagePreviews(newPreviews);
setFormData({ ...formData, images: newImages });
handleDragEnd();
};
// 폼 제출 (UI만)
const handleSubmit = (e) => {
e.preventDefault();
setToast({ type: 'success', message: isEditMode ? '일정이 수정되었습니다.' : '일정이 추가되었습니다.' });
setTimeout(() => navigate('/admin/schedule'), 1000);
};
return (
<div className="min-h-screen bg-gray-50">
<Toast toast={toast} onClose={() => setToast(null)} />
{/* 삭제 확인 다이얼로그 */}
<AnimatePresence>
{deleteDialogOpen && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
onClick={() => setDeleteDialogOpen(false)}
>
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.9, opacity: 0 }}
className="bg-white rounded-2xl p-6 max-w-sm w-full mx-4 shadow-xl"
onClick={(e) => e.stopPropagation()}
>
<h3 className="text-lg font-bold text-gray-900 mb-2">이미지 삭제</h3>
<p className="text-gray-500 mb-6"> 이미지를 삭제하시겠습니까?</p>
<div className="flex justify-end gap-3">
<button
type="button"
onClick={() => setDeleteDialogOpen(false)}
className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
>
취소
</button>
<button
type="button"
onClick={confirmDeleteImage}
className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
>
삭제
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
{/* 이미지 라이트박스 - 공통 컴포넌트 사용 */}
<Lightbox
images={imagePreviews}
currentIndex={lightboxIndex}
isOpen={lightboxOpen}
onClose={() => setLightboxOpen(false)}
onIndexChange={setLightboxIndex}
/>
{/* 헤더 */}
<header className="bg-white shadow-sm border-b border-gray-100">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<Link to="/admin/dashboard" className="text-2xl font-bold text-primary hover:opacity-80 transition-opacity">
fromis_9
</Link>
<span className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
Admin
</span>
</div>
<div className="flex items-center gap-4">
<span className="text-gray-500 text-sm">
안녕하세요, <span className="text-gray-900 font-medium">{user?.username}</span>
</span>
<button
onClick={handleLogout}
className="flex items-center gap-2 px-4 py-2 text-gray-500 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
>
<LogOut size={18} />
<span>로그아웃</span>
</button>
</div>
</div>
</header>
{/* 메인 콘텐츠 */}
<main className="max-w-4xl mx-auto px-6 py-8">
{/* 브레드크럼 */}
<div className="flex items-center gap-2 text-sm text-gray-400 mb-8">
<Link to="/admin/dashboard" className="hover:text-primary transition-colors">
<Home size={16} />
</Link>
<ChevronRight size={14} />
<Link to="/admin/schedule" className="hover:text-primary transition-colors">일정 관리</Link>
<ChevronRight size={14} />
<span className="text-gray-700">{isEditMode ? '일정 수정' : '일정 추가'}</span>
</div>
{/* 타이틀 */}
<div className="mb-8">
<h1 className="text-3xl font-bold text-gray-900 mb-2">{isEditMode ? '일정 수정' : '일정 추가'}</h1>
<p className="text-gray-500">새로운 일정을 등록합니다</p>
</div>
{/* 폼 */}
<form onSubmit={handleSubmit} className="space-y-8">
{/* 기본 정보 카드 */}
<div className="bg-white rounded-2xl shadow-sm p-8">
<h2 className="text-lg font-bold text-gray-900 mb-6">기본 정보</h2>
<div className="space-y-6">
{/* 제목 */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">제목 *</label>
<input
type="text"
value={formData.title}
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
placeholder="일정 제목을 입력하세요"
className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
required
/>
</div>
{/* 범위 설정 토글 */}
<div className="flex items-center gap-3">
<button
type="button"
onClick={() => setFormData({ ...formData, isRange: !formData.isRange })}
className={`relative w-12 h-6 rounded-full transition-colors ${formData.isRange ? 'bg-primary' : 'bg-gray-300'}`}
>
<span className={`absolute top-0.5 w-5 h-5 bg-white rounded-full shadow transition-all ${formData.isRange ? 'left-6' : 'left-0.5'}`} />
</button>
<span className="text-sm text-gray-700">기간 설정 (시작~종료)</span>
</div>
{/* 날짜 + 시간 */}
{formData.isRange ? (
// 범위 설정 모드
<div className="space-y-4">
{/* 시작 */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">시작 날짜 *</label>
<CustomDatePicker
value={formData.startDate}
onChange={(date) => setFormData({ ...formData, startDate: date })}
placeholder="시작 날짜 선택"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">시작 시간</label>
<CustomTimePicker
value={formData.startTime}
onChange={(time) => setFormData({ ...formData, startTime: time })}
placeholder="시작 시간 선택"
/>
</div>
</div>
{/* 종료 */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">종료 날짜 *</label>
<CustomDatePicker
value={formData.endDate}
onChange={(date) => setFormData({ ...formData, endDate: date })}
placeholder="종료 날짜 선택"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">종료 시간</label>
<CustomTimePicker
value={formData.endTime}
onChange={(time) => setFormData({ ...formData, endTime: time })}
placeholder="종료 시간 선택"
/>
</div>
</div>
</div>
) : (
// 단일 날짜 모드
<div className="grid grid-cols-2 gap-6">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">날짜 *</label>
<CustomDatePicker
value={formData.startDate}
onChange={(date) => setFormData({ ...formData, startDate: date })}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">시간</label>
<CustomTimePicker
value={formData.startTime}
onChange={(time) => setFormData({ ...formData, startTime: time })}
/>
</div>
</div>
)}
{/* 카테고리 */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">카테고리 *</label>
<div className="grid grid-cols-5 gap-3">
{categories.map(category => (
<button
key={category.id}
type="button"
onClick={() => setFormData({ ...formData, category: category.id })}
className={`flex items-center justify-center gap-2 px-4 py-3 rounded-xl border-2 transition-all ${
formData.category === category.id
? 'border-primary bg-primary/5'
: 'border-gray-200 hover:border-gray-300'
}`}
>
<span className={`w-2.5 h-2.5 rounded-full ${getCategoryColor(category.id)}`} />
<span className="text-sm font-medium">{category.name}</span>
</button>
))}
</div>
</div>
{/* 설명 */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">설명</label>
<textarea
rows={3}
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="일정에 대한 설명을 입력하세요"
className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent resize-none"
/>
</div>
{/* URL */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">관련 URL</label>
<div className="relative">
<LinkIcon size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400" />
<input
type="url"
value={formData.url}
onChange={(e) => setFormData({ ...formData, url: e.target.value })}
placeholder="https://..."
className="w-full pl-12 pr-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
/>
</div>
</div>
</div>
</div>
{/* 멤버 선택 카드 */}
<div className="bg-white rounded-2xl shadow-sm p-8">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center gap-2">
<Users size={20} className="text-primary" />
<h2 className="text-lg font-bold text-gray-900">참여 멤버</h2>
</div>
<button
type="button"
onClick={toggleAllMembers}
className="text-sm text-primary hover:underline"
>
{formData.members.length === members.length ? '전체 해제' : '전체 선택'}
</button>
</div>
<div className="grid grid-cols-5 gap-4">
{members.map(member => (
<button
key={member.id}
type="button"
onClick={() => toggleMember(member.id)}
className={`relative rounded-xl overflow-hidden transition-all ${
formData.members.includes(member.id)
? 'ring-2 ring-primary ring-offset-2'
: 'hover:opacity-80'
}`}
>
<div className="aspect-[3/4] bg-gray-100">
{member.image_url ? (
<img
src={member.image_url}
alt={member.name}
className="w-full h-full object-cover"
/>
) : (
<div className="w-full h-full flex items-center justify-center bg-gray-200">
<Users size={24} className="text-gray-400" />
</div>
)}
</div>
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/70 to-transparent p-3">
<p className="text-white text-sm font-medium">{member.name}</p>
</div>
{formData.members.includes(member.id) && (
<div className="absolute top-2 right-2 w-6 h-6 bg-primary rounded-full flex items-center justify-center">
<Check size={14} className="text-white" />
</div>
)}
</button>
))}
</div>
</div>
{/* 다중 이미지 업로드 카드 */}
<div className="bg-white rounded-2xl shadow-sm p-8">
<div className="flex items-center gap-2 mb-6">
<Image size={20} className="text-primary" />
<h2 className="text-lg font-bold text-gray-900">일정 이미지</h2>
<span className="text-sm text-gray-400 ml-2">여러 업로드 가능</span>
</div>
{/* 이미지 그리드 */}
<div className="grid grid-cols-4 gap-4">
{/* 이미지 추가 버튼 - 항상 첫번째 */}
<label className="aspect-square border-2 border-dashed border-gray-200 rounded-xl cursor-pointer hover:border-primary/50 hover:bg-primary/5 transition-colors flex flex-col items-center justify-center">
<input
type="file"
accept="image/*"
multiple
onChange={handleImagesUpload}
className="hidden"
/>
<Plus size={24} className="text-gray-400 mb-2" />
<p className="text-sm text-gray-500">이미지 추가</p>
</label>
{/* 이미지 목록 - 드래그 앤 드롭 가능 */}
{imagePreviews.map((preview, index) => (
<div
key={index}
className={`relative aspect-square rounded-xl overflow-hidden group cursor-grab active:cursor-grabbing transition-all duration-200 ${
draggedIndex === index ? 'opacity-50 scale-95' : ''
} ${
dragOverIndex === index && draggedIndex !== index ? 'ring-2 ring-primary ring-offset-2' : ''
}`}
draggable
onDragStart={(e) => handleDragStart(e, index)}
onDragOver={(e) => handleDragOver(e, index)}
onDragEnd={handleDragEnd}
onDrop={(e) => handleDrop(e, index)}
>
{/* 이미지 클릭시 라이트박스 열기 */}
<img
src={preview}
alt={`업로드 ${index + 1}`}
className="w-full h-full object-cover"
onClick={() => openLightbox(index)}
draggable={false}
/>
{/* 호버시 어두운 오버레이 */}
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors pointer-events-none" />
{/* 순서 표시 */}
<div className="absolute bottom-2 left-2 px-2 py-0.5 bg-black/50 rounded-full text-white text-xs font-medium">
{index + 1}
</div>
{/* 삭제 버튼 */}
<button
type="button"
onClick={(e) => {
e.stopPropagation();
openDeleteDialog(index);
}}
className="absolute top-2 right-2 w-7 h-7 bg-black/50 hover:bg-red-500 rounded-full flex items-center justify-center transition-all shadow-lg"
>
<X size={14} className="text-white" />
</button>
</div>
))}
</div>
</div>
{/* 버튼 */}
<div className="flex items-center justify-end gap-4">
<button
type="button"
onClick={() => navigate('/admin/schedule')}
className="px-6 py-3 text-gray-700 hover:bg-gray-100 rounded-xl transition-colors font-medium"
>
취소
</button>
<button
type="submit"
disabled={loading}
className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl hover:bg-primary-dark transition-colors font-medium disabled:opacity-50"
>
<Save size={18} />
{isEditMode ? '수정하기' : '추가하기'}
</button>
</div>
</form>
</main>
</div>
);
}
export default AdminScheduleForm;