"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 {useSearchParams} from "next/navigation";
import {Pencil} from "lucide-react";
import DeleteUserButton from "./deleteUserButton";
import Link from "next/link";
import RoleGuard from "./RoleGuard";
import RestoreUserButton from "./restoreUserButton";

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

export type Data = {
  id: string;
  pid: string;
  firstName: string;
  lastName: string;
  nationality: {
    id: number;
    name: string;
    callCode: string;
  };
  nationalityCode: string | null;
  passportCode: string | null;
  countryCode: string | null;
  phone: string | null;
  email: string | null;
  preferredLanguage: string | null;
  age: number | null;
  address: string | null;
  birthDate: Date | null;
  sex: "male" | "female" | "other" | null;
  postalCode: string | null;
  createdAt: Date;
  documents: {
    id: string;
    createdAt: Date;
    caseId: string | null;
    patientId: string | null;
    uploadedById: string | null;
    type: DocumentType;
  }[];
};
async function fetchData(
  page: number,
  pageSize: number,
  queries?: string,
): Promise<ApiResponse<Data>> {
  const res = await fetch(
    `${API_URL}/patient/get/all?lang=fa&page=${page}&limit=${pageSize}${
      queries ? `&${queries}` : ""
    }`,
    {
      cache: "no-store",
      credentials: "include",
    },
  );

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

  return res.json();
}
export default function PatientsTable() {
  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);

  const URLSearch = useSearchParams();

  const searchParams = new URLSearchParams(URLSearch);
  const is_deleted = searchParams.get("is_deleted") ? true : false;
  const totalPages = Math.ceil(total / pageSize);

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

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

    return () => {
      active = false;
    };
  }, [page, pageSize, URLSearch]);
  if (loading) {
    return (
      <div className="text-sm text-muted-foreground">
        <Loader />
      </div>
    );
  }
  return (
    <>
      <div className="grid gap-4"></div>
      <div className="overflow-x-auto w-full" 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>

              <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>
              <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) => (
              <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?.pid}
                </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?.firstName}
                </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?.lastName}
                </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?.nationalityCode} / {post?.passportCode}
                </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>
                  {post?.sex === "male"
                    ? "مرد"
                    : post.sex === "female"
                      ? "زن"
                      : "سایر"}
                </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>
                  {post?.birthDate &&
                    new Date(post?.birthDate).toLocaleDateString()}
                </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?.nationality?.name}
                </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?.phone &&
                    post?.phone.toString().toLocaleLowerCase("fa-IR")}
                </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>
                  {post?.email}
                </td>
                <td className="px-4 py-6 block md:table-cell text-center border-b border-b-neutral-200 wrap-break-word">
                  <span className="md:hidden font-medium text-gray-500">
                    آدرس
                  </span>
                  {post?.address}
                </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>
                  {post?.preferredLanguage}
                </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={["ADMIN", "DEVELOPER"]}>
                      {!is_deleted && (
                        <DeleteUserButton id={post.id} route="patient" />
                      )}
                      {is_deleted && (
                        <RestoreUserButton id={post.id} route="patient" />
                      )}
                    </RoleGuard>
                    <RoleGuard roles={["ADMIN", "DEVELOPER", "COORDINATOR"]}>
                      <Link
                        className="bg-primary text-white p-1.5 rounded-md"
                        href={`/patients/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>
      )}
    </>
  );
}
