"use client";
import getData from "@/utils/fetch";
import { cellIndex, useParseFloat } from "@/utils/lib/helpers";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { Alert, Popover, theme } from "flowbite-react";
import { FC, useEffect, useState } from "react";
import { BsThreeDots } from "react-icons/bs";
import CustomPagination from "../common/pagination";
import DataTable from "../dataTable/data-table-fb";
import Spinner from "../spinner";
import ResellerAction from "./reseller-actions";
import MacStatus from "./reseller-status";

type props = {
  filterValue?: string | null;
};

const ResellerList: FC<props> = ({ filterValue }) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [pagination, setPagination] = useState<any>({});

  const onPageChange = (page: number) => setCurrentPage(page);

  let base_url = `/api/v1/resellers?page=${currentPage}`;
  let url = filterValue ? `${base_url}&${filterValue}` : base_url;
  const getResellers = async () => {
    const {
      data: { data },
      data: { pagination },
    } = await getData(url);
    setPagination(pagination);
    return data;
  };
  const {
    data: resellers,
    isLoading,
    isError,
    refetch,
    error = {} as any,
  } = useQuery({
    queryKey: ["resellers", { currentPage }],
    placeholderData: keepPreviousData,
    queryFn: () => getResellers(),
  });
  useEffect(() => {
    setCurrentPage(1);
    refetch();
  }, [filterValue]);

  const columns = [
    {
      header: "SL",
      cell: ({ row }: any) => (
        <div className="font-bold">
          {useParseFloat(cellIndex(row.index, pagination) as any)}
        </div>
      ),
    },
    {
      header: "Reseller name",
      accessorKey: "name",
    },
    {
      header: "username",
      cell: ({ row }: any) => {
        const reseller = row.original;
        return <>{reseller?.user?.username}</>;
      },
    },
    {
      header: "Phone",
      accessorKey: "phone",
    },
    {
      header: "clients",
      cell: ({ row }: any) => {
        const reseller = row.original;
        return <>{reseller?.clients?.length}</>;
      },
    },
    {
      header: "Prefix",
      accessorKey: "prefix",
    },
    {
      header: "Due",
      accessorKey: "due",
      cell: ({ row }: any) => {
        const reseller = row.original;
        const due = reseller?.invoices?.reduce(
          (accumulator: number, item: any) =>
            accumulator + useParseFloat(item?.after_discount_amount),
          0
        );
        const paid = reseller?.invoices?.reduce(
          (accumulator: number, item: any) =>
            accumulator + useParseFloat(item?.amount_paid),
          0
        );
        const actual_due = useParseFloat(due) - useParseFloat(paid);
        return <p>{actual_due}</p>;
      },
    },
    {
      header: "Paid",
      accessorKey: "paid",
      cell: ({ row }: any) => {
        const reseller = row.original;
        const paid = reseller?.invoices?.reduce(
          (accumulator: number, item: any) =>
            accumulator + useParseFloat(item?.amount_paid),
          0
        );
        return <p>{useParseFloat(paid)}</p>;
      },
    },
    {
      header: "Status",
      accessorKey: "status",
      cell: ({ row }: any) => {
        const reseller = row.original;
        return <MacStatus reseller={reseller} />;
      },
    },
    {
      header: "Actions",
      cell: ({ row }: any) => {
        const reseller = row.original;
        return (
          <div className="relative">
            <Popover
              placement="bottom"
              className="border border-gray-100 rounded-md z-10"
              content={
                <div className="text-sm text-gray-500 dark:text-gray-400">
                  <ResellerAction reseller={reseller} />
                </div>
              }>
              <div className="cursor-pointer align-center text-center dark:bg-gray-800 dark:border px-3 py-2 bg-gray-200 rounded-md w-10">
                <BsThreeDots />
              </div>
            </Popover>
          </div>
        );
      },
    },
  ];

  return (
    <>
      {isLoading && (
        <div className="text-center">
          <Spinner
            aria-label="Center-aligned spinner example"
            className="mt-20"
            size="xl"
          />
        </div>
      )}
      {resellers !== undefined && (
        <div className="reseller-table">
          <DataTable data={resellers} columns={columns} />
          <CustomPagination
            pagination={pagination}
            currentPage={currentPage}
            onPageChange={onPageChange}
          />
        </div>
      )}
    </>
  );
};
export default ResellerList;
