"use client";

import * as React from "react";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import Loader from "./Loader";
import {useRouter} from "next/navigation";

import RoleGuard from "./RoleGuard";
import DeleteLanguageButton from "./DeleteLanguageButton";
import {useGetLanguages, useUpdateLanguage} from "@/hooks/languages";
import {Dialog} from "./ui/dialog";
import UpdateLanguageForm from "./forms/languages/update/UpdateLanguageForm";
import { useQueryClient } from "@tanstack/react-query";

export type ApiResponse<T> = {
  status: number;
  message: string;
  data: T[];

};

export type Data = {
  id: number;
  title: string;
  slug: string;
};

export default function LanguagesTable() {
  const [page, setPage] = React.useState(1);
  const [pageSize] = React.useState(20);
  const {data, isLoading} = useGetLanguages();
  const [total] = React.useState(0);
  const {mutateAsync, isPending} = useUpdateLanguage();
  const totalPages = Math.ceil(total / pageSize);
  const queryClient = useQueryClient();
  const router = useRouter();

  const languages = data ? (data?.data as Data[]) : [];
  if (isLoading) {
    return (
      <div className="text-sm text-muted-foreground">
        <Loader />
      </div>
    );
  }
  return (
    <>
      <div className="grid gap-4"></div>
      <div className="overflow-x-auto " dir="rtl">
        <table className="min-w-full border border-gray-200 rounded-lg bg-white">
          <thead className="bg-gray-100 hidden md:table-header-group">
            <tr>
              <th className="px-4 py-2 text-center text-sm font-semibold">
                عنوان
              </th>
              <th className="px-4 py-2 text-center text-sm font-semibold">
                اسلاگ
              </th>

              <th className="px-4 py-2 text-center text-sm font-semibold">
                اکشن ها
              </th>
            </tr>
          </thead>

          <tbody className="divide-y divide-gray-400">
            {languages?.map((post) => (
              <tr
                key={post.id}
                className="block md:table-row border-b md:border-none"
              >
                <td className="px-4 py-6 block md:table-cell text-center text-sm border-b border-b-neutral-200">
                  <span className="md:hidden font-medium text-gray-500">
                    عنوان
                  </span>
                  {post?.title}
                </td>

                <td className="px-4 py-6 block md:table-cell text-center text-sm border-b border-b-neutral-200">
                  <span className="md:hidden font-medium text-gray-500">
                    اسلاگ
                  </span>
                  {post?.slug}
                </td>

                <td className="px-4 py-6 block md:table-cell text-center border-b border-b-neutral-200">
                  <span className="md:hidden font-medium text-gray-500">
                    اکشن ها
                  </span>
                  <div className="flex items-center justify-center gap-x-4">
                    <RoleGuard roles={["DEVELOPER"]}>
                      <DeleteLanguageButton id={post.id} route="language" />
                    </RoleGuard>
                    <RoleGuard roles={["ADMIN", "DEVELOPER", "COORDINATOR"]}>
                      <Dialog>
                        <UpdateLanguageForm
                          router={router}
                          updateFn={mutateAsync}
                          updatePending={isPending}
                          id={post.id ? String(post.id) : ""}
                          queryClient={queryClient}
                          preValues={post}
                        />
                      </Dialog>
                    </RoleGuard>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {total > 0 && (
        <Pagination dir="ltr">
          <PaginationContent>
            <PaginationItem>
              <PaginationPrevious
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                className={
                  page === 1
                    ? "pointer-events-none opacity-50"
                    : "cursor-pointer"
                }
              />
            </PaginationItem>

            {Array.from({length: totalPages}).map((_, i) => {
              const pageNumber = i + 1;
              return (
                <PaginationItem key={pageNumber}>
                  <PaginationLink
                    isActive={page === pageNumber}
                    onClick={() => setPage(pageNumber)}
                    className="cursor-pointer"
                  >
                    {pageNumber}
                  </PaginationLink>
                </PaginationItem>
              );
            })}

            <PaginationItem>
              <PaginationNext
                title="بعدی"
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                className={
                  page === totalPages
                    ? "pointer-events-none opacity-50"
                    : "cursor-pointer"
                }
              />
            </PaginationItem>
          </PaginationContent>
        </Pagination>
      )}
    </>
  );
}
