/**
 * 관리자 활동 로그 페이지
 */
import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { useQuery, keepPreviousData } from '@tanstack/react-query';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Home, ChevronRight, Search, ChevronLeft, ChevronDown,
  User, Bot, ScrollText, X, Loader2,
} from 'lucide-react';
import { AdminLayout, DatePicker } from '@/components/pc/admin';
import { useAdminAuth } from '@/hooks/pc/admin';
import { adminLogApi } from '@/api/admin';

// 카테고리 목록
const CATEGORIES = [
  { value: 'album', label: '앨범' },
  { value: 'schedule', label: '일정' },
  { value: 'member', label: '멤버' },
  { value: 'bot', label: '봇' },
  { value: 'category', label: '카테고리' },
  { value: 'dict', label: '사전' },
  { value: 'concert', label: '콘서트' },
  { value: 'sync', label: '동기화' },
];

// 액션 뱃지 색상
const ACTION_STYLES = {
  create: 'bg-emerald-100 text-emerald-700',
  upload: 'bg-emerald-100 text-emerald-700',
  update: 'bg-blue-100 text-blue-700',
  delete: 'bg-red-100 text-red-700',
  sync_complete: 'bg-purple-100 text-purple-700',
  error: 'bg-red-100 text-red-700',
  start: 'bg-amber-100 text-amber-700',
  stop: 'bg-amber-100 text-amber-700',
};

// 액션 한글 라벨
const ACTION_LABELS = {
  create: '생성',
  upload: '업로드',
  update: '수정',
  delete: '삭제',
  sync_complete: '동기화',
  error: '에러',
  start: '시작',
  stop: '정지',
};

const ITEMS_PER_PAGE = 15;

function Logs() {
  const { user } = useAdminAuth();

  // 필터 상태
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategories, setSelectedCategories] = useState([]);
  const [actorFilter, setActorFilter] = useState('all'); // all, admin, bot
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [actorDropdownOpen, setActorDropdownOpen] = useState(false);

  // 검색어 디바운스
  const [debouncedSearch, setDebouncedSearch] = useState('');
  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearch(searchQuery), 300);
    return () => clearTimeout(timer);
  }, [searchQuery]);

  // API 호출
  const { data, isLoading } = useQuery({
    queryKey: ['admin', 'logs', { page: currentPage, category: selectedCategories.join(','), actor: actorFilter === 'all' ? '' : actorFilter, search: debouncedSearch, from: dateFrom, to: dateTo }],
    queryFn: () => adminLogApi.getLogs({
      page: currentPage,
      limit: ITEMS_PER_PAGE,
      category: selectedCategories.join(',') || undefined,
      actor: actorFilter === 'all' ? undefined : actorFilter,
      search: debouncedSearch || undefined,
      from: dateFrom || undefined,
      to: dateTo || undefined,
    }),
    placeholderData: keepPreviousData,
  });

  const logs = data?.logs || [];
  const total = data?.total || 0;
  const totalPages = data?.totalPages || 0;

  // 카테고리 토글
  const toggleCategory = (cat) => {
    setSelectedCategories((prev) =>
      prev.includes(cat) ? prev.filter((c) => c !== cat) : [...prev, cat]
    );
    setCurrentPage(1);
  };

  // 날짜/시간 포맷
  const formatDateTime = (dateStr) => {
    const date = new Date(dateStr);
    const y = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${y}.${month}.${day} ${hours}:${minutes}`;
  };

  // 행위자 아이콘
  const renderActorBadge = (actor) => {
    if (actor === 'admin') {
      return (
        <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-gray-100 text-gray-700 text-xs font-medium rounded-full">
          <User size={12} />
          관리자
        </span>
      );
    }
    return (
      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-indigo-50 text-indigo-700 text-xs font-medium rounded-full">
        <Bot size={12} />
        {actor}
      </span>
    );
  };

  // 필터 초기화
  const clearFilters = () => {
    setSearchQuery('');
    setSelectedCategories([]);
    setActorFilter('all');
    setDateFrom('');
    setDateTo('');
    setCurrentPage(1);
  };

  const hasActiveFilters = searchQuery || selectedCategories.length > 0 || actorFilter !== 'all' || dateFrom || dateTo;

  return (
    <AdminLayout user={user}>
      <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="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">활동 로그</h1>
          <p className="text-gray-500">모든 관리자 및 봇 활동 기록을 확인합니다</p>
        </div>

        {/* 필터 영역 */}
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 mb-6">
          {/* 상단: 검색 + 행위자 + 날짜 */}
          <div className="flex items-center gap-4 mb-4">
            {/* 검색 */}
            <div className="relative flex-1 max-w-sm">
              <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); setCurrentPage(1); }}
                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 text-sm"
              />
            </div>

            {/* 행위자 드롭다운 */}
            <div className="relative">
              <button
                onClick={() => setActorDropdownOpen(!actorDropdownOpen)}
                className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg text-sm hover:bg-gray-50 transition-colors"
              >
                <span className="text-gray-600">
                  {actorFilter === 'all' ? '전체 행위자' : actorFilter === 'admin' ? '관리자' : '봇'}
                </span>
                <ChevronDown size={16} className="text-gray-400" />
              </button>
              <AnimatePresence>
                {actorDropdownOpen && (
                  <>
                    <div className="fixed inset-0 z-10" onClick={() => setActorDropdownOpen(false)} />
                    <motion.div
                      initial={{ opacity: 0, y: -8 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -8 }}
                      transition={{ duration: 0.15 }}
                      className="absolute top-full left-0 mt-1 w-36 bg-white border border-gray-200 rounded-lg shadow-lg z-20 py-1"
                    >
                      {[
                        { value: 'all', label: '전체 행위자' },
                        { value: 'admin', label: '관리자' },
                        { value: 'bot', label: '봇' },
                      ].map((opt) => (
                        <button
                          key={opt.value}
                          onClick={() => { setActorFilter(opt.value); setActorDropdownOpen(false); setCurrentPage(1); }}
                          className={`w-full text-left px-4 py-2 text-sm hover:bg-gray-50 transition-colors ${
                            actorFilter === opt.value ? 'text-primary font-medium' : 'text-gray-700'
                          }`}
                        >
                          {opt.label}
                        </button>
                      ))}
                    </motion.div>
                  </>
                )}
              </AnimatePresence>
            </div>

            {/* 날짜 필터 */}
            <div className="flex items-center gap-2">
              <div className="w-44">
                <DatePicker
                  value={dateFrom}
                  onChange={(v) => { setDateFrom(v); setCurrentPage(1); }}
                  placeholder="시작일"
                />
              </div>
              <span className="text-gray-400 text-sm">~</span>
              <div className="w-44">
                <DatePicker
                  value={dateTo}
                  onChange={(v) => { setDateTo(v); setCurrentPage(1); }}
                  placeholder="종료일"
                />
              </div>
            </div>

            {/* 필터 초기화 */}
            {hasActiveFilters && (
              <button
                onClick={clearFilters}
                className="flex items-center gap-1.5 px-3 py-2 text-sm text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <X size={14} />
                초기화
              </button>
            )}
          </div>

          {/* 하단: 카테고리 칩 */}
          <div className="flex items-center gap-2">
            <span className="text-xs text-gray-400 mr-1">카테고리</span>
            {CATEGORIES.map((cat) => (
              <button
                key={cat.value}
                onClick={() => toggleCategory(cat.value)}
                className={`px-3 py-1.5 text-xs font-medium rounded-full transition-colors ${
                  selectedCategories.includes(cat.value)
                    ? 'bg-primary text-white'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                {cat.label}
              </button>
            ))}
          </div>
        </div>

        {/* 결과 개수 */}
        <div className="flex items-center justify-between mb-4">
          <p className="text-sm text-gray-500">
            총 <span className="font-medium text-gray-900">{total}</span>개의 로그
          </p>
        </div>

        {/* 로그 테이블 */}
        <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 table-fixed">
            <thead className="bg-gray-50 border-b border-gray-100">
              <tr>
                <th className="text-left pl-4 pr-2 py-4 text-sm font-medium text-gray-500 whitespace-nowrap w-[15%]">시간</th>
                <th className="text-left px-3 py-4 text-sm font-medium text-gray-500 whitespace-nowrap w-[10%]">행위자</th>
                <th className="text-left px-3 py-4 text-sm font-medium text-gray-500 whitespace-nowrap w-[8%]">액션</th>
                <th className="text-left px-3 py-4 text-sm font-medium text-gray-500 whitespace-nowrap w-[8%]">카테고리</th>
                <th className="text-left pl-3 pr-6 py-4 text-sm font-medium text-gray-500">내용</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {logs.map((log, index) => (
                <motion.tr
                  key={log.id}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.03 }}
                  className="hover:bg-gray-50 transition-colors"
                >
                  <td className="pl-4 pr-2 py-3.5 text-sm text-gray-500 tabular-nums whitespace-nowrap">
                    {formatDateTime(log.created_at)}
                  </td>
                  <td className="px-3 py-3.5 whitespace-nowrap">
                    {renderActorBadge(log.actor)}
                  </td>
                  <td className="px-3 py-3.5 whitespace-nowrap">
                    <span className={`inline-block px-2.5 py-1 text-xs font-medium rounded-full ${ACTION_STYLES[log.action] || 'bg-gray-100 text-gray-600'}`}>
                      {ACTION_LABELS[log.action] || log.action}
                    </span>
                  </td>
                  <td className="px-3 py-3.5 whitespace-nowrap">
                    <span className="text-xs text-gray-500">
                      {CATEGORIES.find((c) => c.value === log.category)?.label || log.category}
                    </span>
                  </td>
                  <td className="pl-3 pr-6 py-3.5 text-sm text-gray-700">
                    {log.summary}
                  </td>
                </motion.tr>
              ))}
            </tbody>
          </table>

          {isLoading && logs.length === 0 && (
            <div className="flex flex-col items-center justify-center py-16 text-gray-400">
              <Loader2 size={32} className="animate-spin mb-4" />
              <p className="text-sm">로그를 불러오는 중...</p>
            </div>
          )}

          {!isLoading && logs.length === 0 && (
            <div className="flex flex-col items-center justify-center py-16 text-gray-400">
              <ScrollText size={48} strokeWidth={1} className="mb-4" />
              <p className="text-sm">
                {hasActiveFilters ? '검색 결과가 없습니다.' : '활동 로그가 없습니다.'}
              </p>
            </div>
          )}
        </motion.div>

        {/* 페이지네이션 */}
        {totalPages > 1 && (
          <div className="flex items-center justify-center gap-2 mt-6">
            <button
              onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
              disabled={currentPage === 1}
              className="p-2 rounded-lg hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
            >
              <ChevronLeft size={18} />
            </button>
            {Array.from({ length: totalPages }, (_, i) => i + 1)
              .filter((page) => {
                // 페이지가 많을 때 현재 페이지 주변만 표시
                if (totalPages <= 7) return true;
                if (page === 1 || page === totalPages) return true;
                if (Math.abs(page - currentPage) <= 2) return true;
                return false;
              })
              .reduce((acc, page, i, arr) => {
                // 생략 부호(...) 추가
                if (i > 0 && page - arr[i - 1] > 1) {
                  acc.push({ type: 'ellipsis', key: `e-${page}` });
                }
                acc.push({ type: 'page', value: page, key: page });
                return acc;
              }, [])
              .map((item) =>
                item.type === 'ellipsis' ? (
                  <span key={item.key} className="w-9 h-9 flex items-center justify-center text-sm text-gray-400">...</span>
                ) : (
                  <button
                    key={item.key}
                    onClick={() => setCurrentPage(item.value)}
                    className={`w-9 h-9 rounded-lg text-sm font-medium transition-colors ${
                      currentPage === item.value
                        ? 'bg-primary text-white'
                        : 'text-gray-600 hover:bg-gray-100'
                    }`}
                  >
                    {item.value}
                  </button>
                )
              )}
            <button
              onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
              disabled={currentPage === totalPages}
              className="p-2 rounded-lg hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
            >
              <ChevronRight size={18} />
            </button>
          </div>
        )}
      </div>
    </AdminLayout>
  );
}

export default Logs;
