"use client";

import React from "react";
import { ComponentData } from "@/types/screen";
import { componentRegistry, ComponentRenderer } from "../DynamicComponentRenderer";
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";

// 페이지네이션 컴포넌트 렌더러
const PaginationRenderer: ComponentRenderer = ({ component, ...props }) => {
  const config = component.componentConfig || {};
  const { currentPage = 1, totalPages = 10, showPrevNext = true, showEllipsis = true, style = {} } = config;

  const generatePageNumbers = () => {
    const pages = [];
    const maxVisible = 5;

    if (totalPages <= maxVisible) {
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      pages.push(1);
      if (currentPage > 3) {
        pages.push("ellipsis1");
      }

      const start = Math.max(2, currentPage - 1);
      const end = Math.min(totalPages - 1, currentPage + 1);

      for (let i = start; i <= end; i++) {
        pages.push(i);
      }

      if (currentPage < totalPages - 2) {
        pages.push("ellipsis2");
      }
      pages.push(totalPages);
    }

    return pages;
  };

  const pageNumbers = generatePageNumbers();

  return (
    <div className="flex h-full w-full items-center justify-center" style={style}>
      <Pagination>
        <PaginationContent>
          {showPrevNext && (
            <PaginationItem>
              <PaginationPrevious href="#" className="pointer-events-none" />
            </PaginationItem>
          )}

          {pageNumbers.map((page, index) => (
            <PaginationItem key={index}>
              {typeof page === "string" && page.startsWith("ellipsis") ? (
                showEllipsis && <PaginationEllipsis />
              ) : (
                <PaginationLink href="#" isActive={page === currentPage} className="pointer-events-none">
                  {page}
                </PaginationLink>
              )}
            </PaginationItem>
          ))}

          {showPrevNext && (
            <PaginationItem>
              <PaginationNext href="#" className="pointer-events-none" />
            </PaginationItem>
          )}
        </PaginationContent>
      </Pagination>
    </div>
  );
};

// 레지스트리에 등록
componentRegistry.register("pagination", PaginationRenderer);

export { PaginationRenderer };
