import { useState, useEffect, useCallback } from 'react';
import {
  fetchBoardPosts,
  adminDeleteBoardPost,
  type BoardPostItem,
  type BoardListResponse,
} from '@tabs/board/services/boardApi';

// ─── 상수 ──────────────────────────────────────────────────
const PAGE_SIZE = 20;

const CATEGORY_TABS = [
  { code: '', label: '전체' },
  { code: 'NOTICE', label: '공지사항' },
  { code: 'DATA', label: '게시판' },
  { code: 'QNA', label: 'Q&A' },
] as const;

const CATEGORY_LABELS: Record<string, string> = {
  NOTICE: '공지사항',
  DATA: '게시판',
  QNA: 'Q&A',
};

function formatDate(dateStr: string | null) {
  if (!dateStr) return '-';
  return new Date(dateStr).toLocaleString('ko-KR', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
}

// ─── 메인 패널 ─────────────────────────────────────────────
interface BoardMgmtPanelProps {
  initialCategory?: string;
}

export default function BoardMgmtPanel({ initialCategory = '' }: BoardMgmtPanelProps) {
  const [activeCategory, setActiveCategory] = useState(initialCategory);
  const [search, setSearch] = useState('');
  const [searchInput, setSearchInput] = useState('');
  const [page, setPage] = useState(1);
  const [data, setData] = useState<BoardListResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [deleting, setDeleting] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const result = await fetchBoardPosts({
        categoryCd: activeCategory || undefined,
        search: search || undefined,
        page,
        size: PAGE_SIZE,
      });
      setData(result);
      setSelected(new Set());
    } catch {
      console.error('게시글 목록 로드 실패');
    } finally {
      setLoading(false);
    }
  }, [activeCategory, search, page]);

  useEffect(() => {
    load();
  }, [load]);

  const totalPages = data ? Math.ceil(data.totalCount / PAGE_SIZE) : 0;
  const items = data?.items ?? [];

  const toggleSelect = (sn: number) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(sn)) next.delete(sn);
      else next.add(sn);
      return next;
    });
  };

  const toggleAll = () => {
    if (selected.size === items.length) {
      setSelected(new Set());
    } else {
      setSelected(new Set(items.map((i) => i.sn)));
    }
  };

  const handleDelete = async () => {
    if (selected.size === 0) return;
    if (!confirm(`선택한 ${selected.size}건의 게시글을 삭제하시겠습니까?`)) return;
    setDeleting(true);
    try {
      await Promise.all([...selected].map((sn) => adminDeleteBoardPost(sn)));
      await load();
    } catch {
      alert('삭제 중 오류가 발생했습니다.');
    } finally {
      setDeleting(false);
    }
  };

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setSearch(searchInput);
    setPage(1);
  };

  const handleCategoryChange = (code: string) => {
    setActiveCategory(code);
    setPage(1);
  };

  return (
    <div className="flex flex-col h-full overflow-hidden">
      {/* 헤더 */}
      <div className="flex items-center justify-between px-5 py-3 border-b border-stroke-1">
        <h2 className="text-body-2 font-semibold text-fg">게시판 관리</h2>
        <span className="text-caption text-fg-disabled">총 {data?.totalCount ?? 0}건</span>
      </div>

      {/* 카테고리 탭 + 검색 */}
      <div className="flex items-center gap-3 px-5 py-2 border-b border-stroke-1">
        <div className="flex gap-1">
          {CATEGORY_TABS.map((tab) => (
            <button
              key={tab.code}
              onClick={() => handleCategoryChange(tab.code)}
              className={`px-3 py-1 text-caption rounded-full transition-colors ${
                activeCategory === tab.code
                  ? 'bg-blue-500/20 text-blue-400 font-medium'
                  : 'text-fg-disabled hover:text-fg-sub hover:bg-bg-elevated'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>
        <form onSubmit={handleSearch} className="flex gap-1 ml-auto">
          <input
            type="text"
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            placeholder="제목/작성자 검색"
            className="px-2 py-1 text-caption rounded bg-bg-elevated border border-stroke-1 text-fg placeholder:text-text-4 w-48"
          />
          <button
            type="submit"
            className="px-2 py-1 text-caption rounded bg-bg-elevated border border-stroke-1 text-fg-sub hover:bg-bg-card"
          >
            검색
          </button>
        </form>
      </div>

      {/* 액션 바 */}
      <div className="flex items-center gap-2 px-5 py-2 border-b border-stroke-1">
        <button
          onClick={handleDelete}
          disabled={selected.size === 0 || deleting}
          className="px-3 py-1 text-caption rounded bg-red-500/20 text-red-400 hover:bg-red-500/30 disabled:opacity-40 disabled:cursor-not-allowed"
        >
          {deleting ? '삭제 중...' : `선택 삭제 (${selected.size})`}
        </button>
      </div>

      {/* 테이블 */}
      <div className="flex-1 overflow-auto">
        <table className="w-full text-caption">
          <thead className="sticky top-0 bg-bg-surface z-10">
            <tr className="border-b border-stroke-1 text-fg-disabled">
              <th className="w-8 py-2 text-center">
                <input
                  type="checkbox"
                  checked={items.length > 0 && selected.size === items.length}
                  onChange={toggleAll}
                  className="accent-blue-500"
                />
              </th>
              <th className="w-12 py-2 text-center">번호</th>
              <th className="w-20 py-2 text-center">분류</th>
              <th className="py-2 text-left pl-3">제목</th>
              <th className="w-24 py-2 text-center">작성자</th>
              <th className="w-16 py-2 text-center">조회</th>
              <th className="w-36 py-2 text-center">등록일</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={7} className="py-8 text-center text-fg-disabled">
                  로딩 중...
                </td>
              </tr>
            ) : items.length === 0 ? (
              <tr>
                <td colSpan={7} className="py-8 text-center text-fg-disabled">
                  게시글이 없습니다.
                </td>
              </tr>
            ) : (
              items.map((post) => (
                <PostRow
                  key={post.sn}
                  post={post}
                  checked={selected.has(post.sn)}
                  onToggle={() => toggleSelect(post.sn)}
                />
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* 페이지네이션 */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-1 py-2 border-t border-stroke-1">
          <button
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page <= 1}
            className="px-2 py-1 text-caption rounded text-fg-disabled hover:bg-bg-elevated disabled:opacity-30"
          >
            &lt;
          </button>
          {Array.from({ length: Math.min(totalPages, 10) }, (_, i) => {
            const startPage = Math.max(1, Math.min(page - 4, totalPages - 9));
            const p = startPage + i;
            if (p > totalPages) return null;
            return (
              <button
                key={p}
                onClick={() => setPage(p)}
                className={`w-7 h-7 text-caption rounded ${
                  p === page
                    ? 'bg-blue-500/20 text-blue-400 font-medium'
                    : 'text-fg-disabled hover:bg-bg-elevated'
                }`}
              >
                {p}
              </button>
            );
          })}
          <button
            onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
            disabled={page >= totalPages}
            className="px-2 py-1 text-caption rounded text-fg-disabled hover:bg-bg-elevated disabled:opacity-30"
          >
            &gt;
          </button>
        </div>
      )}
    </div>
  );
}

// ─── 행 컴포넌트 ───────────────────────────────────────────
interface PostRowProps {
  post: BoardPostItem;
  checked: boolean;
  onToggle: () => void;
}

function PostRow({ post, checked, onToggle }: PostRowProps) {
  return (
    <tr className="border-b border-stroke-1 hover:bg-bg-surface/50 transition-colors">
      <td className="py-2 text-center">
        <input type="checkbox" checked={checked} onChange={onToggle} className="accent-blue-500" />
      </td>
      <td className="py-2 text-center text-fg-disabled">{post.sn}</td>
      <td className="py-2 text-center">
        <span
          className={`inline-block px-2 py-0.5 rounded-full text-caption font-medium ${
            post.categoryCd === 'NOTICE'
              ? 'bg-red-500/15 text-red-400'
              : post.categoryCd === 'QNA'
                ? 'bg-purple-500/15 text-purple-400'
                : 'bg-blue-500/15 text-blue-400'
          }`}
        >
          {CATEGORY_LABELS[post.categoryCd] ?? post.categoryCd}
        </span>
      </td>
      <td className="py-2 pl-3 text-fg truncate max-w-[300px]">
        {post.pinnedYn === 'Y' && <span className="text-caption text-orange-400 mr-1">[고정]</span>}
        {post.title}
      </td>
      <td className="py-2 text-center text-fg-sub">{post.authorName}</td>
      <td className="py-2 text-center text-fg-disabled">{post.viewCnt}</td>
      <td className="py-2 text-center text-fg-disabled">{formatDate(post.regDtm)}</td>
    </tr>
  );
}
