"use client";

import { useState, useEffect } from "react";
import { cn, numberWithCommas } from "@/lib/utils";

// 원본 CommonPaginationRenderer 대응
// 좌: [page input] / 총 N 페이지 [go]
// 중앙: 1 2 3 ... 10 페이지 번호
// 우: [pageSize select] TOTAL 건
interface PaginationProps {
  currentPage: number;
  totalCount: number;
  pageSize?: number;
  maxPage?: number; // 외부에서 직접 지정할 때 (서버사이드 페이징)
  onPageChange: (page: number) => void;
  onPageSizeChange?: (size: number) => void;
  pageSizeOptions?: number[];
  className?: string;
}

export function Pagination({
  currentPage,
  totalCount,
  pageSize = 20,
  maxPage: maxPageProp,
  onPageChange,
  onPageSizeChange,
  pageSizeOptions = [10, 20, 50, 100, 200],
  className,
}: PaginationProps) {
  const maxPage = maxPageProp ?? Math.max(1, Math.ceil(totalCount / pageSize));
  const [goInput, setGoInput] = useState(String(currentPage));

  useEffect(() => { setGoInput(String(currentPage)); }, [currentPage]);

  const PAGE_WINDOW = 10;
  const windowStart = Math.floor((currentPage - 1) / PAGE_WINDOW) * PAGE_WINDOW + 1;
  const windowEnd = Math.min(windowStart + PAGE_WINDOW - 1, maxPage);
  const pages = Array.from({ length: windowEnd - windowStart + 1 }, (_, i) => windowStart + i);

  const go = () => {
    const n = Number(goInput);
    if (!isNaN(n) && n >= 1 && n <= maxPage) onPageChange(n);
    else setGoInput(String(currentPage));
  };

  return (
    <div className={cn("flex items-center justify-between gap-2 py-3 px-2 text-sm", className)}>
      {/* 좌: page input + total pages + go */}
      <div className="flex items-center gap-2 w-[260px]">
        <input
          type="text" value={goInput}
          onChange={(e) => setGoInput(e.target.value)}
          onKeyDown={(e) => { if (e.key === "Enter") go(); }}
          className="w-12 h-7 border border-gray-300 rounded px-2 text-sm text-center"
        />
        <span className="text-gray-600">/ 총 {numberWithCommas(maxPage)} 페이지</span>
        <button
          onClick={go}
          className="h-7 px-3 border border-gray-300 rounded text-xs hover:bg-gray-50"
        >go</button>
      </div>

      {/* 중앙: 페이지 번호 */}
      <div className="flex items-center gap-1">
        {windowStart > 1 && (
          <button
            onClick={() => onPageChange(Math.max(1, windowStart - 1))}
            className="min-w-[28px] h-7 px-2 text-xs rounded hover:bg-gray-100 text-gray-600"
          >＜</button>
        )}
        {pages.map((p) => (
          <button
            key={p}
            onClick={() => onPageChange(p)}
            className={cn(
              "min-w-[28px] h-7 px-2 text-sm rounded",
              p === currentPage
                ? "border border-primary text-primary font-bold"
                : "hover:bg-gray-100 text-gray-700",
            )}
          >{p}</button>
        ))}
        {windowEnd < maxPage && (
          <button
            onClick={() => onPageChange(windowEnd + 1)}
            className="min-w-[28px] h-7 px-2 text-xs rounded hover:bg-gray-100 text-gray-600"
          >＞</button>
        )}
      </div>

      {/* 우: pageSize + total count */}
      <div className="flex items-center gap-3 w-[260px] justify-end">
        {onPageSizeChange && (
          <select
            value={pageSize}
            onChange={(e) => onPageSizeChange(Number(e.target.value))}
            className="h-7 border border-gray-300 rounded px-1 text-sm"
          >
            {pageSizeOptions.map((s) => <option key={s} value={s}>{s}</option>)}
          </select>
        )}
        <span className="text-primary font-bold">
          {numberWithCommas(totalCount)} <span className="text-gray-500 font-normal">건</span>
        </span>
      </div>
    </div>
  );
}
