import { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { motion, AnimatePresence, Reorder } from 'framer-motion';
import { Home, ChevronRight, Plus, Edit3, Trash2, GripVertical, X } from 'lucide-react';
import { HexColorPicker } from 'react-colorful';
import Toast from '../../../components/Toast';
import AdminLayout from '../../../components/admin/AdminLayout';
import ConfirmDialog from '../../../components/admin/ConfirmDialog';
import useAdminAuth from '../../../hooks/useAdminAuth';
import useToast from '../../../hooks/useToast';
import * as categoriesApi from '../../../api/admin/categories';

// 기본 색상 (8개)
const colorOptions = [
    { id: 'blue', name: '파란색', bg: 'bg-blue-500', hex: '#3b82f6' },
    { id: 'green', name: '초록색', bg: 'bg-green-500', hex: '#22c55e' },
    { id: 'purple', name: '보라색', bg: 'bg-purple-500', hex: '#a855f7' },
    { id: 'red', name: '빨간색', bg: 'bg-red-500', hex: '#ef4444' },
    { id: 'pink', name: '분홍색', bg: 'bg-pink-500', hex: '#ec4899' },
    { id: 'yellow', name: '노란색', bg: 'bg-yellow-500', hex: '#eab308' },
    { id: 'orange', name: '주황색', bg: 'bg-orange-500', hex: '#f97316' },
    { id: 'gray', name: '회색', bg: 'bg-gray-500', hex: '#6b7280' },
];

// 색상 헬퍼 (커스텀 HEX 지원)
const getColorStyle = (colorValue) => {
    // 기본 색상인지 확인
    const preset = colorOptions.find(c => c.id === colorValue);
    if (preset) {
        return { className: preset.bg };
    }
    // HEX 색상인 경우
    if (colorValue?.startsWith('#')) {
        return { style: { backgroundColor: colorValue } };
    }
    return { className: 'bg-gray-500' };
};

function AdminScheduleCategory() {
    const navigate = useNavigate();
    const { user, isAuthenticated } = useAdminAuth();
    const [categories, setCategories] = useState([]);
    const [loading, setLoading] = useState(true);
    const { toast, setToast, showSuccess, showError } = useToast();

    // 모달 상태
    const [modalOpen, setModalOpen] = useState(false);
    const [editingCategory, setEditingCategory] = useState(null);
    const [formData, setFormData] = useState({ name: '', color: 'blue' });

    // 삭제 다이얼로그
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [deleteTarget, setDeleteTarget] = useState(null);

    // 카스텀 컴러 피커 팝업
    const [colorPickerOpen, setColorPickerOpen] = useState(false);

    // 카테고리 로드
    useEffect(() => {
        if (isAuthenticated) {
            fetchCategories();
        }
    }, [isAuthenticated]);

    // 카테고리 목록 조회
    const fetchCategories = async () => {
        try {
            const data = await categoriesApi.getCategories();
            setCategories(data);
        } catch (error) {
            console.error('카테고리 조회 오류:', error);
            showError('카테고리를 불러오는데 실패했습니다.');
        } finally {
            setLoading(false);
        }
    };

    // 모달 열기 (추가/수정)
    const openModal = (category = null) => {
        if (category) {
            setEditingCategory(category);
            setFormData({ name: category.name, color: category.color });
        } else {
            setEditingCategory(null);
            setFormData({ name: '', color: 'blue' });
        }
        setColorPickerOpen(false); // 컬러 피커는 닫힌 상태로
        setModalOpen(true);
    };

    // 카테고리 저장
    const handleSave = async () => {
        if (!formData.name.trim()) {
            showError('카테고리 이름을 입력해주세요.');
            return;
        }

        // 중복 체크 (수정시 자기 자신 제외)
        const isDuplicate = categories.some(
            cat => cat.name.toLowerCase() === formData.name.trim().toLowerCase() 
                && cat.id !== editingCategory?.id
        );
        if (isDuplicate) {
            showError('이미 존재하는 카테고리입니다.');
            return;
        }
        
        try {
            if (editingCategory) {
                await categoriesApi.updateCategory(editingCategory.id, formData);
            } else {
                await categoriesApi.createCategory(formData);
            }
            showSuccess(editingCategory ? '카테고리가 수정되었습니다.' : '카테고리가 추가되었습니다.');
            setModalOpen(false);
            fetchCategories();
        } catch (error) {
            console.error('저장 오류:', error);
            showError(error.message || '저장에 실패했습니다.');
        }
    };

    // 삭제 다이얼로그 열기
    const openDeleteDialog = (category) => {
        setDeleteTarget(category);
        setDeleteDialogOpen(true);
    };

    // 카테고리 삭제
    const handleDelete = async () => {
        if (!deleteTarget) return;
        
        try {
            await categoriesApi.deleteCategory(deleteTarget.id);
            showSuccess('카테고리가 삭제되었습니다.');
            setDeleteDialogOpen(false);
            setDeleteTarget(null);
            fetchCategories();
        } catch (error) {
            console.error('삭제 오류:', error);
            showError(error.message || '삭제에 실패했습니다.');
        }
    };

    // Reorder 핸들러 (부드러운 애니메이션)
    const handleReorder = async (newOrder) => {
        setCategories(newOrder);
        
        // 순서 업데이트 API 호출
        const orders = newOrder.map((cat, idx) => ({
            id: cat.id,
            sort_order: idx + 1
        }));

        try {
            await categoriesApi.reorderCategories(orders);
        } catch (error) {
            console.error('순서 업데이트 오류:', error);
            fetchCategories(); // 실패시 원래 데이터 다시 불러오기
        }
    };

    if (loading) {
        return (
            <AdminLayout user={user}>
                <div className="flex items-center justify-center" style={{ minHeight: 'calc(100vh - 80px)' }}>
                    <div className="animate-spin rounded-full h-12 w-12 border-4 border-primary border-t-transparent"></div>
                </div>
            </AdminLayout>
        );
    }

    return (
        <AdminLayout user={user}>
            <Toast toast={toast} onClose={() => setToast(null)} />

            {/* 메인 콘텐츠 */}
            <div className="max-w-4xl mx-auto px-6 py-8">
                {/* 브레드크럼 */}
                <div className="flex items-center gap-2 text-sm text-gray-500 mb-6">
                    <Link to="/admin/dashboard" className="hover:text-primary flex items-center gap-1">
                        <Home size={14} />
                        대시보드
                    </Link>
                    <ChevronRight size={14} />
                    <Link to="/admin/schedule" className="hover:text-primary">일정 관리</Link>
                    <ChevronRight size={14} />
                    <span className="text-gray-900">카테고리 관리</span>
                </div>

                {/* 타이틀 */}
                <div className="flex items-center justify-between mb-8">
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900">카테고리 관리</h1>
                        <p className="text-gray-500 mt-1">일정 카테고리를 추가, 수정, 삭제할 수 있습니다.</p>
                    </div>
                    <button
                        onClick={() => openModal()}
                        className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-xl hover:bg-primary-dark transition-colors"
                    >
                        <Plus size={18} />
                        카테고리 추가
                    </button>
                </div>

                {/* 카테고리 목록 */}
                <div className="bg-white rounded-2xl shadow-sm overflow-hidden">
                    {categories.length === 0 ? (
                        <div className="p-12 text-center text-gray-500">
                            등록된 카테고리가 없습니다.
                        </div>
                    ) : (
                        <Reorder.Group 
                            axis="y" 
                            values={categories} 
                            onReorder={handleReorder}
                            className="divide-y divide-gray-100"
                        >
                            {categories.map((category) => (
                                <Reorder.Item
                                    key={category.id}
                                    value={category}
                                    className="flex items-center gap-4 p-4 bg-white cursor-grab active:cursor-grabbing"
                                    whileDrag={{ 
                                        scale: 1.02, 
                                        boxShadow: "0 10px 30px rgba(0,0,0,0.15)",
                                        zIndex: 50
                                    }}
                                >
                                    {/* 드래그 핸들 */}
                                    <div className="text-gray-400 hover:text-gray-600">
                                        <GripVertical size={20} />
                                    </div>
                                    
                                    {/* 색상 표시 */}
                                    {(() => {
                                        const colorStyle = getColorStyle(category.color);
                                        return (
                                            <div 
                                                className={`w-4 h-4 rounded-full ${colorStyle.className || ''}`}
                                                style={colorStyle.style}
                                            />
                                        );
                                    })()}
                                    
                                    {/* 이름 */}
                                    <span className="flex-1 font-medium text-gray-900">{category.name}</span>
                                    
                                    {/* 액션 버튼 */}
                                    <div className="flex items-center gap-2">
                                        <button
                                            onClick={(e) => { e.stopPropagation(); openModal(category); }}
                                            className="p-2 text-gray-400 hover:text-primary hover:bg-primary/10 rounded-lg transition-colors"
                                        >
                                            <Edit3 size={18} />
                                        </button>
                                        {category.is_default ? (
                                            <span 
                                                className="p-2 text-gray-300 cursor-not-allowed" 
                                                title="기본 카테고리는 삭제할 수 없습니다"
                                            >
                                                <Trash2 size={18} />
                                            </span>
                                        ) : (
                                            <button
                                                onClick={(e) => { e.stopPropagation(); openDeleteDialog(category); }}
                                                className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                                            >
                                                <Trash2 size={18} />
                                            </button>
                                        )}
                                    </div>
                                </Reorder.Item>
                            ))}
                        </Reorder.Group>
                    )}
                </div>
            </div>

            {/* 추가/수정 모달 */}
            <AnimatePresence>
                {modalOpen && (
                    <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={() => setModalOpen(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 w-full mx-4 shadow-xl"
                            style={{ maxWidth: '452px', minWidth: '452px' }}
                            onClick={(e) => e.stopPropagation()}
                        >
                            <h3 className="text-xl font-bold text-gray-900 mb-6">
                                {editingCategory ? '카테고리 수정' : '카테고리 추가'}
                            </h3>
                            
                            {/* 카테고리 이름 */}
                            <div className="mb-6">
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    카테고리 이름 *
                                </label>
                                <input
                                    type="text"
                                    value={formData.name}
                                    onChange={(e) => setFormData({ ...formData, name: 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"
                                />
                            </div>
                            
                            {/* 색상 선택 */}
                            <div className="mb-8">
                                <label className="block text-sm font-medium text-gray-700 mb-3">
                                    색상 선택 *
                                </label>
                                <div className="flex flex-wrap gap-3">
                                    {colorOptions.map((color) => (
                                        <button
                                            key={color.id}
                                            type="button"
                                            onClick={() => setFormData({ ...formData, color: color.id })}
                                            className={`w-10 h-10 rounded-full ${color.bg} transition-all ${
                                                formData.color === color.id
                                                    ? 'ring-2 ring-offset-2 ring-gray-400 scale-110'
                                                    : 'hover:scale-105'
                                            }`}
                                            title={color.name}
                                        />
                                    ))}
                                    {/* 커스텀 색상 - 무지개 그라디언트 버튼 */}
                                    <div className="relative">
                                        <button
                                            type="button"
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                setColorPickerOpen(!colorPickerOpen);
                                            }}
                                            className={`w-10 h-10 rounded-full transition-all ${
                                                formData.color?.startsWith('#')
                                                    ? 'ring-2 ring-offset-2 ring-gray-400 scale-110'
                                                    : 'hover:scale-105'
                                            }`}
                                            style={{
                                                background: formData.color?.startsWith('#') 
                                                    ? formData.color 
                                                    : 'conic-gradient(from 0deg, #ff0000, #ff8000, #ffff00, #00ff00, #00ffff, #0000ff, #8000ff, #ff0080, #ff0000)'
                                            }}
                                            title="커스텀 색상"
                                        />
                                        {/* 색상 선택 팝업 */}
                                        <AnimatePresence>
                                            {colorPickerOpen && (
                                                <>
                                                    {/* 바깥 영역 클릭시 컬러피커만 닫기 */}
                                                    <div 
                                                        className="fixed inset-0 z-40" 
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            setColorPickerOpen(false);
                                                        }}
                                                    />
                                                    <motion.div
                                                        initial={{ opacity: 0, scale: 0.9, y: -10 }}
                                                        animate={{ opacity: 1, scale: 1, y: 0 }}
                                                        exit={{ opacity: 0, scale: 0.9, y: -10 }}
                                                        className="absolute top-12 left-0 z-50 p-4 bg-white rounded-2xl shadow-xl border border-gray-100"
                                                        style={{ width: '240px' }}
                                                        onClick={(e) => e.stopPropagation()}
                                                    >
                                                        <HexColorPicker 
                                                            color={formData.color?.startsWith('#') ? formData.color : '#6b7280'}
                                                            onChange={(color) => setFormData({ ...formData, color })}
                                                            style={{ width: '100%', height: '180px' }}
                                                        />
                                                        <div className="mt-4 flex items-center">
                                                            <span className="px-3 py-2 text-sm bg-gray-100 border border-r-0 border-gray-200 rounded-l-lg text-gray-500">#</span>
                                                            <input
                                                                type="text"
                                                                value={formData.color?.startsWith('#') ? formData.color.slice(1) : ''}
                                                                onChange={(e) => {
                                                                    const val = e.target.value.replace(/[^0-9A-Fa-f]/g, '').slice(0, 6);
                                                                    if (val) {
                                                                        setFormData({ ...formData, color: '#' + val });
                                                                    }
                                                                }}
                                                                placeholder="FFFFFF"
                                                                className="w-full px-3 py-2 text-sm border border-gray-200 rounded-r-lg focus:outline-none focus:ring-2 focus:ring-primary"
                                                                style={{ minWidth: 0 }}
                                                            />
                                                        </div>
                                                        <div className="mt-3 flex justify-end gap-2">
                                                            <button
                                                                type="button"
                                                                onClick={() => {
                                                                    setFormData({ ...formData, color: 'blue' });
                                                                    setColorPickerOpen(false);
                                                                }}
                                                                className="px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
                                                            >
                                                                취소
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => setColorPickerOpen(false)}
                                                                className="px-3 py-1.5 text-sm bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors"
                                                            >
                                                                확인
                                                            </button>
                                                        </div>
                                                    </motion.div>
                                                </>
                                            )}
                                        </AnimatePresence>
                                    </div>
                                </div>
                            </div>
                            
                            {/* 버튼 */}
                            <div className="flex justify-end gap-3">
                                <button
                                    type="button"
                                    onClick={() => setModalOpen(false)}
                                    className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
                                >
                                    취소
                                </button>
                                <button
                                    type="button"
                                    onClick={handleSave}
                                    className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors"
                                >
                                    {editingCategory ? '수정' : '추가'}
                                </button>
                            </div>
                        </motion.div>
                    </motion.div>
                )}
            </AnimatePresence>

            {/* 삭제 확인 다이얼로그 */}
            <ConfirmDialog
                isOpen={deleteDialogOpen}
                onClose={() => setDeleteDialogOpen(false)}
                onConfirm={handleDelete}
                title="카테고리 삭제"
                message={
                    <>
                        <span className="font-medium text-gray-900">"{deleteTarget?.name}"</span> 카테고리를 삭제하시겠습니까?
                        <br />
                        <span className="text-sm text-red-500">이 작업은 되돌릴 수 없습니다.</span>
                    </>
                }
            />
        </AdminLayout>
    );
}

export default AdminScheduleCategory;
