"use client";
import { usePermission } from "@/utils/auth/permission";
import getData, { putData } from "@/utils/fetch";
import { cellIndex, useParseError, useParseFloat } from "@/utils/lib/helpers";
import {
  keepPreviousData,
  useMutation,
  useQuery,
  useQueryClient,
} from "@tanstack/react-query";
import { FC, useEffect, useState } from "react";
import { GrUpdate } from "react-icons/gr";
import { toast } from "react-toastify";
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";

type props = {
  filterValue?: string | null;
  setClientCount?: (x: number) => void;
  setMatchCount?: (x: number) => void;
  setNotMatchCount?: (x: number) => void;
  setSummary?: (x: string) => void;
};

const ClientAutoSyncList: FC<props> = ({
  filterValue,
  setClientCount = () => {},
  setMatchCount = () => {},
  setNotMatchCount = () => {},
  setSummary = () => {},
}) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [pagination, setPagination] = useState<any>();
  const onPageChange = (page: number) => setCurrentPage(page);
  let base_url = `/api/v1/client-sync?page=${currentPage}`;
  let url = filterValue ? `${base_url}&${filterValue}` : base_url;
  const queryClient = useQueryClient();

  const getClients = async () => {
    const clients_data = await getData(url);

    if (!clients_data?.success) {
      toast.error(useParseError(clients_data));
      return;
    }

    const {
      data: { data },
      data: { pagination },
      data: { match_count },
      data: { not_match_count },
      data: { summary },
    } = clients_data;
    let clients = useParseFloat(pagination?.total);
    setClientCount(clients);
    setMatchCount(match_count);
    setNotMatchCount(not_match_count);
    setSummary(summary);
    setPagination(pagination);
    return data;
  };

  const {
    data: clients,
    isLoading,
    isFetching,
    isError,
    refetch,
    error = {} as any,
  } = useQuery({
    queryKey: ["client-sync", { currentPage }],
    placeholderData: keepPreviousData,
    queryFn: () => getClients(),
    refetchOnWindowFocus: false,
    retry: 0,
  });
  useEffect(() => {
    if (!filterValue?.includes("#")) {
      setCurrentPage(1);
      refetch();
    }
  }, [filterValue]);

  const { mutate: clientIndividualSync, isPending } = useMutation({
    mutationFn: async (sync_id: any) => {
      const data = await putData(`/api/v1/client-individual-sync/${sync_id}`, {
        test: "test",
      });
      if (!data?.success) {
        throw data;
      }
      return data;
    },
    onSuccess: (data) => {
      toast.success("Sync successful!");
      queryClient.invalidateQueries({ queryKey: ["client-sync"] });
    },
    onError: (error: any) => {
      if (useParseError(error)) {
        toast.error(useParseError(error));
      }
    },
  });

  const columns = [
    {
      header: "SL",
      cell: ({ row }: any) => (
        <div className="font-bold">{cellIndex(row.index, pagination)}</div>
      ),
    },
    {
      header: "Reseller",
      accessorKey: "reseller",
      cell: ({ row }: any) => {
        const client = row.original;
        return <p>{client?.reseller?.name ?? ""}</p>;
      },
    },
    {
      header: "Client In Mikrotik",
      accessorKey: "client_in_mikrotik",
    },
    {
      header: "Client In App",
      accessorKey: "client_in_app",
    },
    {
      header: "Mikrotik Profile",
      accessorKey: "mikrotik_profile",
      cell: ({ row }: any) => {
        const client = row.original;
        return (
          <p
            className={`${client?.profile_match === "not-match" ? "text-red-600" : "text-green-600"}`}
          >
            {client?.mikrotik_profile}
          </p>
        );
      },
    },
    {
      header: "App Profile",
      accessorKey: "app_profile",
      cell: ({ row }: any) => {
        const client = row.original;
        return (
          <p
            className={`${client?.profile_match === "not-match" ? "text-red-600" : "text-green-600"}`}
          >
            {client?.app_profile}
          </p>
        );
      },
    },
    {
      header: "Mikrotik Status",
      accessorKey: "client_status_mikrotik",
      cell: ({ row }: any) => {
        const client = row.original;
        return (
          <p
            className={`${client?.client_status_mikrotik === "Inactive" ? "text-red-600" : "text-green-600"}`}
          >
            {client?.client_status_mikrotik}
          </p>
        );
      },
    },
    {
      header: "App Status",
      accessorKey: "client_status_app",
      cell: ({ row }: any) => {
        const client = row.original;
        return (
          <p
            className={`${client?.client_status_app === "Inactive" ? "text-red-600" : "text-green-600"}`}
          >
            {client?.client_status_app}
          </p>
        );
      },
    },

    {
      header: "Actions",
      id: "testing",
      cell: ({ row }: any) => {
        const client = row.original;
        const client_id: string = String(client.id);
        return (
          <>
            <div className=" flex">
              {client?.mikrotik_match === 0 &&
                client?.syncable === 1 &&
                usePermission("client-sync.individual-sync") && (
                  <div className="mr-2">
                    <ActionButton
                      size="sm"
                      type="any"
                      onClick={() => clientIndividualSync(client_id)}
                    >
                      <GrUpdate className="text-md font-bold" />
                    </ActionButton>
                  </div>
                )}
              {client?.mikrotik_match === 0 &&
                client?.syncable === 0 &&
                usePermission("client-sync.delete") && (
                  <div className="mr-2">
                    <DeleteItem
                      name="client-sync"
                      url={`/api/v1/client-sync/${client_id}`}
                      keys="client-sync"
                    />
                  </div>
                )}
            </div>
          </>
        );
      },
    },
  ];

  return (
    <>
      {(isLoading || isFetching || isPending) && (
        <div className="relative">
          <div className="grid fixed left-2/4 top-1/2 z-50">
            <Spinner size="xl" color="purple" />
          </div>
        </div>
      )}
      {clients !== undefined && (
        <div className="user-list pb-20 shadow-md min-h-96">
          <div className="border-b overflow-x-auto">
            <DataTable data={clients} columns={columns} />
          </div>
          <CustomPagination
            pagination={pagination}
            currentPage={currentPage}
            onPageChange={onPageChange}
            keys="sync-clients"
          />
        </div>
      )}
    </>
  );
};
export default ClientAutoSyncList;
