"use client";

import { ChevronRight, MoreHorizontal } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";

interface PaginationProps {
  currentPage: number;
  totalPages: number;
  totalItems: number;
  itemsPerPage: number;
  onPageChange?: (page: number) => void;
  onItemsPerPageChange?: (itemsPerPage: number) => void;
  className?: string;
  pageParamName?: string;
  perPageParamName?: string;
  perPageOptions?: number[];
  showItemsPerPage?: boolean;
  labels?: {
    itemsPerPage?: string;
    previous?: string;
    next?: string;
    showing?: string;
    of?: string;
  };
}

export function Pagination({
  currentPage,
  totalPages,
  totalItems,
  itemsPerPage,
  onPageChange,
  onItemsPerPageChange,
  className,
  pageParamName = "page",
  perPageParamName = "perPage",
  perPageOptions = [8, 16, 24, 50],
  showItemsPerPage = true,
  labels = {},
}: PaginationProps) {
  const t = useTranslations("dashboard.pagination");
  const router = useRouter();
  const searchParams = useSearchParams();

  const {
    itemsPerPage: itemsPerPageLabel = t("itemsPerPage"),
    previous: previousLabel = t("previous"),
    next: nextLabel = t("next"),
    showing: showingLabel = t("showing"),
    of: ofLabel = t("of"),
  } = labels;

  const handlePageChange = (page: number) => {
    if (page < 1 || page > totalPages) return;

    const params = new URLSearchParams(searchParams);
    params.set(pageParamName, page.toString());
    router.push(`?${params.toString()}`, { scroll: false });
    onPageChange?.(page);
  };

  const handleItemsPerPageChange = (newItemsPerPage: string) => {
    const params = new URLSearchParams(searchParams);
    params.set(perPageParamName, newItemsPerPage);
    params.set(pageParamName, "1");
    router.push(`?${params.toString()}`, { scroll: false });
    onItemsPerPageChange?.(parseInt(newItemsPerPage));
  };

  const getPageNumbers = () => {
    const pages: (number | "ellipsis")[] = [];

    if (totalPages <= 5) {
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      if (currentPage <= 3) {
        pages.push(1, 2, 3);
        pages.push("ellipsis");
        pages.push(totalPages);
      } else if (currentPage >= totalPages - 2) {
        pages.push(1);
        pages.push("ellipsis");
        pages.push(totalPages - 2, totalPages - 1, totalPages);
      } else {
        pages.push(1);
        pages.push("ellipsis");
        pages.push(currentPage);
        pages.push("ellipsis");
        pages.push(totalPages);
      }
    }

    return pages;
  };

  const displayedItems = Math.min(
    itemsPerPage,
    Math.max(totalItems - (currentPage - 1) * itemsPerPage, 0)
  );

  return (
    <div
      className={cn(
        "flex w-full items-center justify-between border-t border-border px-6 py-4",
        className
      )}
    >
      {/* RIGHT: Items per page dropdown */}
      {showItemsPerPage && (
        <div className="flex items-center gap-4">
          <Select
            value={itemsPerPage.toString()}
            onValueChange={handleItemsPerPageChange}
          >
            <SelectTrigger className="h-10 w-[70px] border-border rounded-lg">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {perPageOptions.map((option) => (
                <SelectItem key={option} value={option.toString()}>
                  {option}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <span className="text-sm text-muted-foreground font-sans">
            {itemsPerPageLabel}
          </span>
        </div>
      )}

      {/* CENTER: Pagination controls */}
      <div className="flex items-center gap-4">
        {/* Previous button */}
        <Button
          variant="outline"
          onClick={() => handlePageChange(currentPage - 1)}
          disabled={currentPage === 1}
          className={cn(
            "h-10 px-4 gap-2 border-border rounded-[12px] font-sans text-sm",
            currentPage === 1
              ? "text-muted-foreground"
              : "text-primary border-primary"
          )}
        >
          <ChevronRight className="size-5" />
          <span>{previousLabel}</span>
        </Button>

        {/* Page numbers */}
        <div className="flex items-center gap-2">
          {getPageNumbers().map((page, index) => {
            if (page === "ellipsis") {
              return (
                <div
                  key={`ellipsis-${index}`}
                  className="flex items-center justify-center size-8"
                >
                  <MoreHorizontal className="size-4 text-muted-foreground" />
                </div>
              );
            }

            const pageNumber = page as number;
            const isActive = pageNumber === currentPage;

            return (
              <button
                key={pageNumber}
                onClick={() => handlePageChange(pageNumber)}
                className={cn(
                  "flex items-center justify-center size-8 rounded-lg text-xs font-sans transition-colors",
                  isActive
                    ? "border border-primary-100 bg-primary-50 text-foreground font-medium"
                    : "bg-card text-muted-foreground hover:bg-muted"
                )}
              >
                {pageNumber}
              </button>
            );
          })}
        </div>

        {/* Next button */}
        <Button
          variant="outline"
          onClick={() => handlePageChange(currentPage + 1)}
          disabled={currentPage === totalPages}
          className={cn(
            "h-10 px-4 gap-2 border-border rounded-[12px] font-sans text-sm",
            currentPage === totalPages
              ? "text-muted-foreground"
              : "text-primary border-primary"
          )}
        >
          <ChevronRight className="size-5 rotate-180" />
          <span>{nextLabel}</span>
        </Button>
      </div>

      {/* LEFT: Total count */}
      <div className="text-sm text-muted-foreground font-sans">
        {showingLabel} {displayedItems} {ofLabel} {totalItems}
      </div>
    </div>
  );
}
