"use client";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import axios from "axios";
import { Alert, Pagination, Spinner } from "flowbite-react";
import { FC, useState } from "react";
import { HiInformationCircle } from "react-icons/hi";
import DataTable from "../dataTable/data-table-fb";
import BillingEdit from "./billing-edit";

type props = {
  setBillingIds: (x: any) => void;
  billingIds: string[];
};

const BillingList: FC<props> = ({ setBillingIds, billingIds }) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [pagination, setPagination] = useState<any>({});
  const [isOpen, setOpen] = useState(false);
  const [billing_id, setBillingId] = useState<string | null>(null);

  const onPageChange = (page: number) => setCurrentPage(page);
  const getBillings = async () => {
    const {
      data: { data },
      data: {
        data: { pagination },
      },
    } = await axios.get(`/api/billings?page=${currentPage}`);
    setPagination(pagination);
    return data?.data;
  };
  const {
    data: billings,
    isLoading,
    isError,
    error = {} as any,
  } = useQuery({
    queryKey: ["billings", { currentPage }],
    placeholderData: keepPreviousData,
    queryFn: () => getBillings(),
    retry: 0,
  });

  const columns = [
    {
      header: "zone",
      accessorKey: "zone",
      cell: ({ row }: any) => {
        const billing = row.original;
        return (
          <div>{`${billing?.zone?.name ?? ""} ${
            billing?.zone?.name_bn ?? ""
          } `}</div>
        );
      },
    },
    {
      header: "Bill Generated",
      accessorKey: "generated_bill",
    },
    {
      header: "Collections",
      accessorKey: "collections",
    },
    {
      header: "Discount",
      accessorKey: "discount",
    },
    {
      header: "Total due",
      accessorKey: "total_due",
    },
  ];

  return (
    <>
      {isLoading && (
        <div className="text-center">
          <Spinner
            aria-label="Center-aligned spinner example"
            className="mt-20"
            size="xl"
          />
        </div>
      )}
      {isError && (
        <Alert color="failure" icon={HiInformationCircle}>
          <span className="font-medium">Info alert!</span>
          {error?.response?.data?.error?.message}
        </Alert>
      )}
      {isOpen && (
        <BillingEdit
          billingId={billing_id}
          setOpen={setOpen as () => void}
          isOpen={isOpen}
        />
      )}
      {billings !== undefined && (
        <div className="user-list pb-20 shadow-md">
          <div className="border-b">
            <DataTable
              data={billings}
              columns={columns}
              initSorting={{ id: "generated_bill", desc: false }}
            />
          </div>

          <div className="flex justify-between overflow-x-auto">
            <div className="flex">
              <Pagination
                className="ml-2 mt-2"
                layout="navigation"
                currentPage={currentPage}
                totalPages={pagination.total_pages || 0}
                onPageChange={onPageChange}
                showIcons
                nextLabel=""
                previousLabel=""
              />
              <div className="ml-2 mt-5">
                <p className="text-gray-500">
                  Showing
                  <span className="ml-2 mr-1 mt-1 text-gray-900">
                    {(pagination.current_page - 1) * 10 < 1
                      ? 1
                      : (pagination.current_page - 1) * 10}{" "}
                    - {pagination.current_page * 10}
                  </span>{" "}
                  of <span className="text-gray-900"> {pagination.total}</span>{" "}
                </p>
              </div>
            </div>
            <Pagination
              currentPage={currentPage}
              totalPages={pagination.total_pages || 0}
              onPageChange={onPageChange}
              className="mr-2 mt-2 text-blue-900 sm:justify-end"
              showIcons
              color="blue"
            />
          </div>
        </div>
      )}
    </>
  );
};
export default BillingList;
