/**
 * 관리자 앨범 목록 페이지
 */
import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { motion } from 'framer-motion';
import { Plus, Search, Edit2, Trash2, Image, Music, Home, ChevronRight, Calendar } from 'lucide-react';
import { Toast, Tooltip } from '@/components/common';
import { AdminLayout, ConfirmDialog } from '@/components/pc/admin';
import { useAdminAuth } from '@/hooks/pc/admin';
import { useToast } from '@/hooks/common';
import { adminAlbumApi } from '@/api/admin';

function AdminAlbums() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { user, isAuthenticated } = useAdminAuth();
  const { toast, setToast } = useToast();

  const [searchQuery, setSearchQuery] = useState('');
  const [deleteDialog, setDeleteDialog] = useState({ show: false, album: null });
  const [deleting, setDeleting] = useState(false);

  // 앨범 목록 조회
  const { data: albums = [], isLoading: loading } = useQuery({
    queryKey: ['admin', 'albums'],
    queryFn: adminAlbumApi.getAlbums,
    enabled: isAuthenticated,
    staleTime: 0,
  });

  const handleDelete = async () => {
    if (!deleteDialog.album) return;

    setDeleting(true);
    try {
      await adminAlbumApi.deleteAlbum(deleteDialog.album.id);
      setToast({ message: `"${deleteDialog.album.title}" 앨범이 삭제되었습니다.`, type: 'success' });
      setDeleteDialog({ show: false, album: null });
      queryClient.invalidateQueries({ queryKey: ['admin', 'albums'] });
    } 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 (
    <AdminLayout user={user}>
      <Toast toast={toast} onClose={() => setToast(null)} />

      {/* 삭제 확인 다이얼로그 */}
      <ConfirmDialog
        isOpen={deleteDialog.show}
        onClose={() => setDeleteDialog({ show: false, album: null })}
        onConfirm={handleDelete}
        title="앨범 삭제"
        message={
          <>
            <span className="font-medium text-gray-900">"{deleteDialog.album?.title}"</span> 앨범을
            삭제하시겠습니까?
            <br />
            <span className="text-sm text-red-500">
              이 작업은 되돌릴 수 없으며, 모든 트랙과 커버 이미지가 함께 삭제됩니다.
            </span>
          </>
        }
        loading={deleting}
      />

      <div 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="min-h-[400px]" />
        ) : (
          <motion.div
            initial={{ opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{
              duration: 0.4,
              ease: [0.25, 0.1, 0.25, 1],
              delay: 0.15,
            }}
            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>
            )}
          </motion.div>
        )}
      </div>
    </AdminLayout>
  );
}

export default AdminAlbums;
