import { useState, useEffect, useCallback } from 'react';
import { useAuthStore } from '@common/store/authStore';
import { fetchBoardPosts, type BoardPostItem } from '../services/boardApi';

// 카테고리 코드 ↔ 표시명 매핑
const CATEGORY_MAP: Record<string, string> = {
  NOTICE: '공지사항',
  DATA: '자료실',
  QNA: 'Q&A',
  MANUAL: '해경매뉴얼',
};

const CATEGORY_FILTER: { label: string; code: string | null }[] = [
  { label: '전체', code: null },
  { label: '공지사항', code: 'NOTICE' },
  { label: '자료실', code: 'DATA' },
  { label: 'Q&A', code: 'QNA' },
];

const CATEGORY_STYLE: Record<string, string> = {
  NOTICE: 'bg-[color-mix(in_srgb,var(--color-accent)_15%,transparent)] text-color-accent',
  DATA: 'bg-bg-elevated text-fg-sub',
  QNA: 'bg-bg-elevated text-fg-sub',
  MANUAL: 'bg-bg-elevated text-fg-sub',
};

const PAGE_SIZE = 20;

interface BoardListTableProps {
  onPostClick: (id: number) => void;
  onWriteClick: () => void;
}

export function BoardListTable({ onPostClick, onWriteClick }: BoardListTableProps) {
  const hasPermission = useAuthStore((s) => s.hasPermission);

  const [posts, setPosts] = useState<BoardPostItem[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [page, setPage] = useState(1);
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [searchInput, setSearchInput] = useState('');
  const [loading, setLoading] = useState(false);

  const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE));

  // 카테고리별 서브리소스 권한 확인 (전체 선택 시 board CREATE)
  const canWrite = selectedCategory
    ? hasPermission(`board:${selectedCategory.toLowerCase()}`, 'CREATE')
    : hasPermission('board', 'CREATE');

  const loadPosts = useCallback(async () => {
    setLoading(true);
    try {
      const result = await fetchBoardPosts({
        categoryCd: selectedCategory || undefined,
        search: searchTerm || undefined,
        page,
        size: PAGE_SIZE,
      });
      setPosts(result.items);
      setTotalCount(result.totalCount);
    } catch {
      setPosts([]);
      setTotalCount(0);
    } finally {
      setLoading(false);
    }
  }, [selectedCategory, searchTerm, page]);

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

  const handleCategoryChange = (code: string | null) => {
    setSelectedCategory(code);
    setPage(1);
  };

  const handleSearch = () => {
    setSearchTerm(searchInput);
    setPage(1);
  };

  const handleSearchKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') handleSearch();
  };

  const formatDate = (dtm: string) => {
    return new Date(dtm).toLocaleDateString('ko-KR', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    });
  };

  return (
    <div className="flex flex-col h-full bg-bg-base">
      {/* Header with Search and Write Button */}
      <div className="flex items-center justify-between px-8 py-4 border-b border-stroke bg-bg-surface">
        <div className="flex items-center gap-4">
          <div className="flex gap-2">
            {CATEGORY_FILTER.map((cat) => (
              <button
                key={cat.label}
                onClick={() => handleCategoryChange(cat.code)}
                className={`px-4 py-2 text-label-1 font-semibold rounded transition-all ${
                  selectedCategory === cat.code
                    ? 'bg-color-accent text-white'
                    : 'bg-bg-elevated text-fg-disabled hover:bg-bg-card hover:text-fg'
                }`}
              >
                {cat.label}
              </button>
            ))}
          </div>
        </div>

        <div className="flex items-center gap-3">
          <input
            type="text"
            placeholder="제목, 작성자 검색..."
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            onKeyDown={handleSearchKeyDown}
            className="px-4 py-2 text-label-1 bg-bg-elevated border border-stroke rounded text-fg placeholder-fg-disabled focus:border-color-accent focus:outline-none w-64"
          />

          {canWrite && (
            <button
              onClick={onWriteClick}
              className="rounded-sm text-label-1 font-semibold cursor-pointer text-color-accent px-3.5 py-1.5 bg-[color-mix(in_srgb,var(--color-accent)_8%,transparent)] border border-[color-mix(in_srgb,var(--color-accent)_30%,transparent)] flex items-center gap-2"
            >
              <span>+</span>
              <span>글쓰기</span>
            </button>
          )}
        </div>
      </div>

      {/* Board List Table */}
      <div className="flex-1 overflow-auto px-8 py-6">
        {loading ? (
          <div className="text-center py-20">
            <p className="text-fg-disabled text-label-1">불러오는 중...</p>
          </div>
        ) : (
          <>
            <table className="w-full border-collapse">
              <thead>
                <tr className="border-b-2 border-stroke">
                  <th className="px-4 py-3 text-left text-label-1 font-semibold text-fg-sub w-20">
                    번호
                  </th>
                  <th className="px-4 py-3 text-left text-label-1 font-semibold text-fg-sub w-32">
                    분류
                  </th>
                  <th className="px-4 py-3 text-left text-label-1 font-semibold text-fg-sub">
                    제목
                  </th>
                  <th className="px-4 py-3 text-left text-label-1 font-semibold text-fg-sub w-32">
                    작성자
                  </th>
                  <th className="px-4 py-3 text-left text-label-1 font-semibold text-fg-sub w-32">
                    작성일
                  </th>
                  <th className="px-4 py-3 text-left text-label-1 font-semibold text-fg-sub w-24">
                    조회수
                  </th>
                </tr>
              </thead>
              <tbody>
                {posts.map((post) => (
                  <tr
                    key={post.sn}
                    onClick={() => onPostClick(post.sn)}
                    className="border-b border-stroke hover:bg-bg-elevated cursor-pointer transition-colors"
                  >
                    <td className="px-4 py-4 text-label-1 text-fg">
                      {post.pinnedYn === 'Y' ? (
                        <span className="inline-flex items-center px-2 py-0.5 rounded text-caption font-semibold bg-[color-mix(in_srgb,var(--color-accent)_15%,transparent)] text-color-accent">
                          공지
                        </span>
                      ) : (
                        post.sn
                      )}
                    </td>
                    <td className="px-4 py-4">
                      <span
                        className={`inline-flex items-center px-2.5 py-0.5 rounded text-caption font-semibold ${
                          CATEGORY_STYLE[post.categoryCd] || 'bg-bg-elevated text-fg-sub'
                        }`}
                      >
                        {CATEGORY_MAP[post.categoryCd] || post.categoryCd}
                      </span>
                    </td>
                    <td className="px-4 py-4">
                      <span className="text-label-1 text-fg hover:text-color-accent transition-colors">
                        {post.title}
                      </span>
                    </td>
                    <td className="px-4 py-4 text-label-1 text-fg-sub">{post.authorName}</td>
                    <td className="px-4 py-4 text-label-1 text-fg-disabled">
                      {formatDate(post.regDtm)}
                    </td>
                    <td className="px-4 py-4 text-label-1 text-fg-disabled">{post.viewCnt}</td>
                  </tr>
                ))}
              </tbody>
            </table>

            {posts.length === 0 && (
              <div className="text-center py-20">
                <p className="text-fg-disabled text-label-1">검색 결과가 없습니다.</p>
              </div>
            )}
          </>
        )}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2 px-8 py-4 border-t border-stroke bg-bg-surface">
          <button
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page <= 1}
            className="px-3 py-1.5 text-label-1 rounded bg-bg-elevated text-fg-disabled hover:bg-bg-card hover:text-fg transition-colors disabled:opacity-40"
          >
            이전
          </button>
          {Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
            <button
              key={p}
              onClick={() => setPage(p)}
              className={`px-3 py-1.5 text-label-1 rounded ${
                page === p
                  ? 'bg-color-accent text-white font-semibold'
                  : 'bg-bg-elevated text-fg-disabled hover:bg-bg-card hover:text-fg transition-colors'
              }`}
            >
              {p}
            </button>
          ))}
          <button
            onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
            disabled={page >= totalPages}
            className="px-3 py-1.5 text-label-1 rounded bg-bg-elevated text-fg-disabled hover:bg-bg-card hover:text-fg transition-colors disabled:opacity-40"
          >
            다음
          </button>
        </div>
      )}
    </div>
  );
}
