'use client';

import { useMemo } from 'react';
import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';
import type { PaginationConfig } from '@/types/invyone-component';

const DEFAULT_CONFIG: PaginationConfig = {
  pageSize: 20,
  showSizeSelector: true,
  sizeOptions: [10, 20, 50, 100],
};

interface FcPaginationProps {
  config?: Partial<PaginationConfig>;
  total: number;
  page: number;
  pageSize?: number;
  onPageChange?: (params: { page: number; size: number }) => void;
}

export function FcPagination({
  config: configOverride,
  total,
  page,
  pageSize: pageSizeOverride,
  onPageChange,
}: FcPaginationProps) {
  const config = useMemo(() => ({ ...DEFAULT_CONFIG, ...configOverride }), [configOverride]);
  const size = pageSizeOverride ?? config.pageSize;
  const totalPages = Math.max(1, Math.ceil(total / size));

  const goTo = (p: number) => {
    const clamped = Math.max(1, Math.min(p, totalPages));
    if (clamped !== page) onPageChange?.({ page: clamped, size });
  };

  // 보여줄 페이지 번호 계산 (최대 5개)
  const pages = useMemo(() => {
    const maxVisible = 5;
    let start = Math.max(1, page - Math.floor(maxVisible / 2));
    const end = Math.min(totalPages, start + maxVisible - 1);
    start = Math.max(1, end - maxVisible + 1);
    const arr: number[] = [];
    for (let i = start; i <= end; i++) arr.push(i);
    return arr;
  }, [page, totalPages]);

  return (
    <div className="flex items-center justify-between gap-4 text-xs text-[var(--v5-text-sec)]">
      <div className="flex items-center gap-1.5">
        <span>총 {total.toLocaleString()}건</span>
        {config.showSizeSelector && (
          <select
            value={size}
            onChange={(e) => onPageChange?.({ page: 1, size: Number(e.target.value) })}
            className="h-6 rounded border border-[var(--v5-border)] bg-[var(--v5-surface)]
              px-1 text-xs text-[var(--v5-text)] outline-none"
          >
            {config.sizeOptions.map((s) => (
              <option key={s} value={s}>{s}건</option>
            ))}
          </select>
        )}
      </div>

      <div className="flex items-center gap-0.5">
        <PgBtn onClick={() => goTo(1)} disabled={page <= 1}><ChevronsLeft className="h-3 w-3" /></PgBtn>
        <PgBtn onClick={() => goTo(page - 1)} disabled={page <= 1}><ChevronLeft className="h-3 w-3" /></PgBtn>
        {pages.map((p) => (
          <button
            key={p}
            onClick={() => goTo(p)}
            className={`h-6 min-w-[24px] rounded text-xs transition-colors
              ${p === page
                ? 'bg-[var(--v5-primary)] text-white shadow-[var(--v5-glow-sm)]'
                : 'hover:bg-[var(--v5-surface-hover)] text-[var(--v5-text-sec)]'}`}
          >
            {p}
          </button>
        ))}
        <PgBtn onClick={() => goTo(page + 1)} disabled={page >= totalPages}><ChevronRight className="h-3 w-3" /></PgBtn>
        <PgBtn onClick={() => goTo(totalPages)} disabled={page >= totalPages}><ChevronsRight className="h-3 w-3" /></PgBtn>
      </div>
    </div>
  );
}

function PgBtn({ children, onClick, disabled }: { children: React.ReactNode; onClick: () => void; disabled: boolean }) {
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      className="flex h-6 w-6 items-center justify-center rounded
        text-[var(--v5-text-muted)] hover:text-[var(--v5-primary)] hover:bg-[var(--v5-surface-hover)]
        disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
    >
      {children}
    </button>
  );
}
