import { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { 
    Plus, Search, Edit2, Trash2, Image, Music,
    Home, ChevronRight, Calendar, AlertTriangle, X
} from 'lucide-react';
import Toast from '../../../components/Toast';
import Tooltip from '../../../components/Tooltip';
import AdminHeader from '../../../components/admin/AdminHeader';
import useToast from '../../../hooks/useToast';
import * as authApi from '../../../api/admin/auth';
import { getAlbums } from '../../../api/public/albums';
import * as albumsApi from '../../../api/admin/albums';

function AdminAlbums() {
    const navigate = useNavigate();
    const [albums, setAlbums] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState('');
    const [user, setUser] = useState(null);
    const { toast, setToast } = useToast();
    const [deleteDialog, setDeleteDialog] = useState({ show: false, album: null });
    const [deleting, setDeleting] = useState(false);

    useEffect(() => {
        // 로그인 확인
        if (!authApi.hasToken()) {
            navigate('/admin');
            return;
        }

        setUser(authApi.getCurrentUser());
        fetchAlbums();
    }, [navigate]);

    const fetchAlbums = async () => {
        try {
            const data = await getAlbums();
            setAlbums(data);
        } catch (error) {
            console.error('앨범 로드 오류:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleDelete = async () => {
        if (!deleteDialog.album) return;
        
        setDeleting(true);
        try {
            await albumsApi.deleteAlbum(deleteDialog.album.id);
            setToast({ message: `"${deleteDialog.album.title}" 앨범이 삭제되었습니다.`, type: 'success' });
            setDeleteDialog({ show: false, album: null });
            fetchAlbums();
        } catch (error) {
            console.error('삭제 오류:', error);
            setToast({ message: '앨범 삭제 중 오류가 발생했습니다.', type: 'error' });
        } finally {
            setDeleting(false);
        }
    };

    // 날짜 포맷팅
    const formatDate = (dateStr) => {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`;
    };

    // 검색 필터링
    const filteredAlbums = albums.filter(album => 
        album.title.toLowerCase().includes(searchQuery.toLowerCase())
    );

    return (
        <div className="min-h-screen bg-gray-50">
            {/* Toast */}
            <Toast toast={toast} onClose={() => setToast(null)} />

            {/* 삭제 확인 다이얼로그 */}
            <AnimatePresence>
                {deleteDialog.show && (
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
                        onClick={() => !deleting && setDeleteDialog({ show: false, album: null })}
                    >
                        <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-md w-full mx-4 shadow-xl"
                            onClick={(e) => e.stopPropagation()}
                        >
                            <div className="flex items-center gap-3 mb-4">
                                <div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
                                    <AlertTriangle className="text-red-500" size={20} />
                                </div>
                                <h3 className="text-lg font-bold text-gray-900">앨범 삭제</h3>
                            </div>
                            
                            <p className="text-gray-600 mb-6">
                                <span className="font-medium text-gray-900">"{deleteDialog.album?.title}"</span> 앨범을 삭제하시겠습니까?
                                <br />
                                <span className="text-sm text-red-500">이 작업은 되돌릴 수 없으며, 모든 트랙과 커버 이미지가 함께 삭제됩니다.</span>
                            </p>
                            
                            <div className="flex justify-end gap-3">
                                <button
                                    onClick={() => setDeleteDialog({ show: false, album: null })}
                                    disabled={deleting}
                                    className="px-4 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50"
                                >
                                    취소
                                </button>
                                <button
                                    onClick={handleDelete}
                                    disabled={deleting}
                                    className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors disabled:opacity-50 flex items-center gap-2"
                                >
                                    {deleting ? (
                                        <>
                                            <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                                            삭제 중...
                                        </>
                                    ) : (
                                        <>
                                            <Trash2 size={16} />
                                            삭제
                                        </>
                                    )}
                                </button>
                            </div>
                        </motion.div>
                    </motion.div>
                )}
            </AnimatePresence>

            {/* 헤더 */}
            <AdminHeader user={user} />

            {/* 메인 콘텐츠 */}
            <main className="max-w-7xl 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} />
                    <span className="text-gray-700">앨범 관리</span>
                </div>

                {/* 타이틀 & 액션 */}
                <div className="flex items-center justify-between mb-8">
                    <div>
                        <h1 className="text-3xl font-bold text-gray-900 mb-2">앨범 관리</h1>
                        <p className="text-gray-500">앨범, 트랙, 사진을 관리합니다</p>
                    </div>
                    <button
                        onClick={() => navigate('/admin/albums/new')}
                        className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors"
                    >
                        <Plus size={18} />
                        <span>새 앨범 추가</span>
                    </button>
                </div>

                {/* 검색 */}
                <div className="mb-6">
                    <div className="relative max-w-md">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
                        <input
                            type="text"
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            placeholder="앨범 검색..."
                            className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                        />
                    </div>
                </div>

                {/* 앨범 목록 */}
                {loading ? (
                    <div className="flex justify-center items-center py-20">
                        <div className="animate-spin rounded-full h-12 w-12 border-4 border-primary border-t-transparent"></div>
                    </div>
                ) : (
                    <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                        <table className="w-full">
                            <thead className="bg-gray-50 border-b border-gray-100">
                                <tr>
                                    <th className="text-left px-6 py-4 text-sm font-medium text-gray-500">앨범</th>
                                    <th className="text-left px-6 py-4 text-sm font-medium text-gray-500">타입</th>
                                    <th className="text-left px-6 py-4 text-sm font-medium text-gray-500">발매일</th>
                                    <th className="text-left px-6 py-4 text-sm font-medium text-gray-500">트랙</th>
                                    <th className="text-right px-6 py-4 text-sm font-medium text-gray-500">관리</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100">
                                {filteredAlbums.map((album, index) => (
                                    <motion.tr
                                        key={album.id}
                                        initial={{ opacity: 0, y: 10 }}
                                        animate={{ opacity: 1, y: 0 }}
                                        transition={{ delay: index * 0.05 }}
                                        className="hover:bg-gray-50 transition-colors"
                                    >
                                        <td className="px-6 py-4">
                                            <div className="flex items-center gap-4">
                                                <img
                                                    src={album.cover_thumb_url || album.cover_original_url}
                                                    alt={album.title}
                                                    className="w-12 h-12 rounded-lg object-cover"
                                                />
                                                <div>
                                                    <p className="font-medium text-gray-900">{album.title}</p>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-6 py-4">
                                            <span className="px-2 py-1 bg-gray-100 text-gray-600 text-xs font-medium rounded-full">
                                                {album.album_type}
                                            </span>
                                        </td>
                                        <td className="px-6 py-4 text-gray-500 text-sm">
                                            <div className="flex items-center gap-1">
                                                <Calendar size={14} />
                                                {formatDate(album.release_date)}
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 text-gray-500 text-sm">
                                            <div className="flex items-center gap-1">
                                                <Music size={14} />
                                                {album.tracks?.length || 0}곡
                                            </div>
                                        </td>
                                        <td className="px-6 py-4">
                                            <div className="flex items-center justify-end gap-2">
                                                <Tooltip text="사진 관리" position="top">
                                                    <button
                                                        onClick={() => navigate(`/admin/albums/${album.id}/photos`)}
                                                        className="p-2 text-gray-400 hover:text-purple-500 hover:bg-purple-50 rounded-lg transition-colors"
                                                    >
                                                        <Image size={18} />
                                                    </button>
                                                </Tooltip>
                                                <Tooltip text="수정" position="top">
                                                    <button
                                                        onClick={() => navigate(`/admin/albums/${album.id}/edit`)}
                                                        className="p-2 text-gray-400 hover:text-primary hover:bg-primary/10 rounded-lg transition-colors"
                                                    >
                                                        <Edit2 size={18} />
                                                    </button>
                                                </Tooltip>
                                                <Tooltip text="삭제" position="top">
                                                    <button
                                                        onClick={() => setDeleteDialog({ show: true, album })}
                                                        className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                                                    >
                                                        <Trash2 size={18} />
                                                    </button>
                                                </Tooltip>
                                            </div>
                                        </td>
                                    </motion.tr>
                                ))}
                            </tbody>
                        </table>

                        {filteredAlbums.length === 0 && (
                            <div className="text-center py-12 text-gray-500">
                                {searchQuery ? '검색 결과가 없습니다.' : '등록된 앨범이 없습니다.'}
                            </div>
                        )}
                    </div>
                )}
            </main>
        </div>
    );
}

export default AdminAlbums;
