"use client";

import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useMemo } from "react";

interface PaginationProps {
  currentPage: number;
  totalPages: number;
  perPage: number;
  total: number;
  from: number;
  to: number;
  onPageChange: (page: number) => void;
  onPerPageChange?: (perPage: number) => void;
}

export function Pagination({
  currentPage,
  totalPages,
  perPage,
  total,
  from,
  to,
  onPageChange,
  onPerPageChange,
}: PaginationProps) {
  const t = useTranslations();
  const locale = useLocale();
  const isArabic = locale === "ar";
  const pageSizeOptions = useMemo(
    () => Array.from(new Set([perPage, 10, 20, 25, 50, 100])).sort((a, b) => a - b),
    [perPage],
  );

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

    if (totalPages <= 5) {
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      // Always show first page
      pages.push(1);

      if (currentPage > 3) {
        pages.push("...");
      }

      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("...");
      }

      if (totalPages > 1) {
        pages.push(totalPages);
      }
    }

    return pages;
  };

  if (totalPages <= 0 || total <= 0) {
    return null;
  }

  return (
    <div className="flex items-center justify-between px-6 py-4 border-border bg-card rounded-b-xl">

      {/* Center: Page numbers */}
      <div className="flex flex-end items-center gap-2">
        {/* Previous button */}
        <Button
          variant="ghost"
          size="sm"
          onClick={() => onPageChange(currentPage - 1)}
          disabled={currentPage === 1}
          className="h-6 w-6 p-0"
        >
          {isArabic ? (
            <ChevronRight className="h-4 w-4" />
          ) : (
            <ChevronLeft className="h-4 w-4" />
          )}
        </Button>

        {/* Page numbers */}
        <div className="flex flex-1 items-center justify-center gap-2">
          {getPageNumbers().map((page, index) => {
            if (page === "...") {
              return (
                <div
                  key={`ellipsis-${index}`}
                  className="flex items-center justify-center h-6 min-w-6 px-1 border border-border rounded text-sm"
                >
                  ...
                </div>
              );
            }

            const isCurrentPage = currentPage === page;

            return (
              <button
                key={page}
                onClick={() => onPageChange(page as number)}
                className={`relative flex flex-col items-center justify-center h-6 min-w-6 px-1 rounded text-sm transition-colors ${isCurrentPage
                    ? "text-foreground"
                    : "text-foreground hover:bg-muted"
                  }`}
              >
                {page}
                {isCurrentPage && (
                  <div className="absolute bottom-0 left-1/2 -translate-x-1/2 w-4 h-[3px] bg-primary rounded-full" />
                )}
              </button>
            );
          })}
        </div>

        {/* Next button */}
        <Button
          variant="ghost"
          size="sm"
          onClick={() => onPageChange(currentPage + 1)}
          disabled={currentPage === totalPages}
          className="h-6 w-6 p-0"
        >
          {isArabic ? (
            <ChevronLeft className="h-4 w-4" />
          ) : (
            <ChevronRight className="h-4 w-4" />
          )}
        </Button>
      </div>


      {/* Left: Per page selector */}
      {onPerPageChange && (
        <div className="flex items-center gap-4">
          <Select
            value={perPage.toString()}
            onValueChange={(value) => onPerPageChange(Number(value))}
          >
            <SelectTrigger className="h-10 w-20">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {pageSizeOptions.map((option) => (
                <SelectItem key={option} value={option.toString()}>
                  {option}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <p className="text-sm text-muted-foreground">
            {t("common.itemsPerPage")}
          </p>
        </div>
      )}
    </div>
  );
}
