"use client";

import * as React from "react";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import {API_URL} from "@/constants";
import Loader from "./Loader";
import {useRouter, useSearchParams} from "next/navigation";
import {Pencil} from "lucide-react";
import Link from "next/link";
import RoleGuard from "./RoleGuard";
import DeleteExpertiseButton from "./DeleteExpertiseButton";

export type ApiResponse<T> = {
  status: number;
  message: string;
  data: {
    data: T[];
    page: string;
    limit: string;
    total: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
};
type Translation = {
  displayName: string;
  lang: string;
};

type Expertise = {
  slug: string;
  translations: Translation[];
};

type UserTranslation = {
  firstName: string;
  lastName: string;
  lang: string;
  position: string;
};

export type Data = {
  slug: string;
  id: number;
  translations: {
    displayName: string | null;
    lang: {
      title: string;
    } | null;
  }[];
};
async function fetchData(
  page: number,
  pageSize: number,
  queries?: string,
): Promise<ApiResponse<Data>> {
  console.log("doctors table");

  const res = await fetch(
    `${API_URL}/case/get/all?page=${page}&limit=${pageSize}${queries ? `&${queries}` : ""}`,
    {
      cache: "no-store",
      credentials: "include",
    },
  );

  if (!res.ok) {
    throw new Error("Failed to fetch data");
  }

  return await res.json();
}
export default function OnlineCasesTable() {
  const [page, setPage] = React.useState(1);
  const [pageSize] = React.useState(20);
  const [data, setData] = React.useState<Data[]>([]);
  const [total, setTotal] = React.useState(0);
  const [loading, setLoading] = React.useState(false);

  console.log(data);
  const searchParams = useSearchParams();
  const totalPages = Math.ceil(total / pageSize);

  const router = useRouter();
  React.useEffect(() => {
    let active = true;

    setLoading(true);
    fetchData(page, pageSize, searchParams.toString())
      .then((res) => {
        if (!active) return;
        console.log(res.data);
        setData(res.data?.data);
        setTotal(res.data?.total);
      })
      .catch(console.error)
      .finally(() => active && setLoading(false));

    return () => {
      active = false;
    };
  }, [page, pageSize, searchParams]);
  if (loading) {
    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>
              <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">
            {data.map((post, index) => (
              <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>
                  {index + 1}
                </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 text-sm border-b border-b-neutral-200">
                  <span className="md:hidden font-medium text-gray-500">
                    نام
                  </span>
                  {post?.translations[0]?.displayName}
                </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?.translations[0]?.lang?.title}
                </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"]}>
                      <DeleteExpertiseButton id={post.id} route="expertise" />
                    </RoleGuard>
                    <RoleGuard roles={["ADMIN", "DEVELOPER", "COORDINATOR"]}>
                      <Link
                        className="bg-primary text-white p-1.5 rounded-md"
                        href={`/expertise/edit/${post.id}`}
                      >
                        <Pencil />
                      </Link>
                    </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>
      )}
    </>
  );
}
