import { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { 
    Plus, Search, Edit2, Trash2, Image, Music,
    Home, ChevronRight, LogOut, Calendar
} from 'lucide-react';

function AdminAlbums() {
    const navigate = useNavigate();
    const [albums, setAlbums] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState('');
    const [user, setUser] = useState(null);

    useEffect(() => {
        // 로그인 확인
        const token = localStorage.getItem('adminToken');
        const userData = localStorage.getItem('adminUser');

        if (!token || !userData) {
            navigate('/admin');
            return;
        }

        setUser(JSON.parse(userData));

        // 앨범 목록 로드
        fetch('/api/albums')
            .then(res => res.json())
            .then(data => {
                setAlbums(data);
                setLoading(false);
            })
            .catch(error => {
                console.error('앨범 로드 오류:', error);
                setLoading(false);
            });
    }, [navigate]);

    const handleLogout = () => {
        localStorage.removeItem('adminToken');
        localStorage.removeItem('adminUser');
        navigate('/admin');
    };

    // 날짜 포맷팅
    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">
            {/* 헤더 */}
            <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="/" 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-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_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">
                                                <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"
                                                    title="사진 관리"
                                                >
                                                    <Image size={18} />
                                                </button>
                                                <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"
                                                    title="수정"
                                                >
                                                    <Edit2 size={18} />
                                                </button>
                                                <button
                                                    className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                                                    title="삭제"
                                                >
                                                    <Trash2 size={18} />
                                                </button>
                                            </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;
