"use client";
import { usePermission } from "@/utils/auth/permission";
import getData from "@/utils/fetch";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { FC, useState } from "react";
import ActionButton from "../action-button";
import DeleteItem from "../common/delete-item";
import CustomPagination from "../common/pagination";
import DataTable from "../dataTable/data-table-fb";
import Spinner from "../spinner";
import MyWallet from "../wallets/my-wallet";
import { useSession } from "next-auth/react";

const CommunicationGatewayList: FC = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const { data: session }: any = useSession();
  const [pagination, setPagination] = useState<any>({});

  const getCommunicationGateways = async () => {
    const {
      data: { data },
      data: { pagination },
    } = await getData(`/api/v1/communication-gateways?page=${currentPage}`);
    setPagination(pagination);
    return data;
  };

  const { data: gateways, isLoading, isFetching } = useQuery({
    queryKey: ["communicationGateways", { currentPage }],
    placeholderData: keepPreviousData,
    queryFn: getCommunicationGateways,
  });
  const isSuperAdmin =
    session?.company?.domain === "localhost" ||
    session?.company?.domain === "app.isptik.com" ||
    session?.company?.domain === "softwarebd.net";

  const columns = [
    { header: "Name", accessorKey: "name" },
    { header: "Type", accessorKey: "type" },
    {
      header: "API", accessorKey: "api",
      cell: ({ row }: any) => {
        const gw = row.original;
        return (
          <>
            {gw.access_type === 'view' && !isSuperAdmin && (
              <p className="text-sm text-gray-500">{`https://api.isptik.com/${gw.type}`}</p>
            )}
            {(gw.access_type === 'edit' || isSuperAdmin) && (
              <p className="text-sm text-gray-500">{gw.api}</p>
            )}

          </>
        )
      },
    },
    { header: "Unit price", accessorKey: "rates_per_unit" },
    {
      header: "Balance",
      cell: ({ row }: any) => {
        const gw = row.original;
        return <MyWallet label={false} />;
      },
    },
    {
      header: "Status",
      accessorKey: "status",
      cell: ({ row }: any) => {
        const gw = row.original;
        const color =
          gw?.status === "active"
            ? "text-green-600"
            : gw?.status === "test"
              ? "text-yellow-600"
              : "text-red-600";
        return <p className={`${color} capitalize`}>{gw?.status}</p>;
      },
    },
    {
      header: "Actions",
      id: "actions",
      cell: ({ row }: any) => {
        const gw = row.original;
        const gwId: string = String(gw.id);
        return (
          <div className="flex">
            {(gw.access_type === 'edit' || isSuperAdmin) && usePermission("communication-gateways.show") && (
              <Link href={`/communication-gateways?id=${gwId}`}>
                <ActionButton type="edit" />
              </Link>
            )}
            {(gw.access_type === 'edit' || isSuperAdmin) && usePermission("communication-gateways.delete") && (
              <DeleteItem
                name="Communication gateway"
                keys="communicationGateways"
                url={`/api/v1/communication-gateways/${gwId}`}
              />
            )}
          </div>
        );
      },
    },
  ];

  return (
    <>
      {(isLoading || isFetching) && (
        <div className="relative">
          <div className="fixed left-2/4 top-1/2 z-50">
            <Spinner size="xl" color="purple" />
          </div>
        </div>
      )}
      {gateways !== undefined && (
        <div className="user-list pb-20 shadow-md">
          <div className="border-b overflow-x-auto">
            <DataTable data={gateways} columns={columns} />
          </div>
          <CustomPagination
            pagination={pagination}
            currentPage={currentPage}
            onPageChange={(page) => setCurrentPage(page)}
          />
        </div>
      )}
    </>
  );
};

export default CommunicationGatewayList;
