"use client";
import getData from "@/utils/fetch";
import { cellIndex } from "@/utils/lib/helpers";
import { FC, useEffect, useState } from "react";
import ErrorMessages from "../common/error-messages";
import MoneyFormat from "../common/money";
import CustomPagination from "../common/pagination";
import DataTable from "../dataTable/data-table-fb";
import { TSpaymentSchema } from "../forms/schema/payment";
import Spinner from "../spinner";

type props = {
  initPayments?: TSpaymentSchema;
  initPagination?: Pagination;
  filterValue?: string | null;
  clientId?: string | null;
  setReports: (x: any) => void;
};

const ClientPayments: FC<props> = ({
  initPayments,
  initPagination,
  clientId,
  filterValue,
  setReports,
}) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [pagination, setPagination] = useState<any>(initPagination);
  const [payments, setPayments] = useState<any>(initPayments);
  const [isLoading, setLoading] = useState(false);

  const getPayments = async (page: number) => {
    setLoading(true);
    let url = `/api/v1/payments?page=${page}&client_uuid=${clientId}`;
    console.log(url);
    let api_url = filterValue ? `${url}&${filterValue}` : url;
    const response = await getData(api_url);
    if (!response?.success) {
      return <ErrorMessages message={response?.message} />;
    }
    const {
      data: { data: payment },
      data: { pagination },
      data: { reports },
    } = response;
    setPagination(pagination);
    setPayments(payment);
    if (reports) {
      setReports(reports);
    }
    setLoading(false);
  };
  const onPageChange = (page: number) => {
    setCurrentPage(page);
    getPayments(page);
  };

  useEffect(() => {
    if (!filterValue?.includes("#")) {
      setCurrentPage(1);
      getPayments(1);
    }
  }, [filterValue]);

  const columns = [
    {
      header: "SL",
      cell: ({ row }: any) => (
        <div className="font-bold">{cellIndex(row.index, pagination)}</div>
      ),
    },
    {
      header: "Received Date",
      accessorKey: "payment_date",
    },
    {
      header: "Title",
      accessorKey: "title",
    },
    {
      header: "Client",
      cell: ({ row }: any) => {
        const payment = row.original;
        return <p>{payment?.client?.name}</p>;
      },
    },
    {
      header: "Collect By",
      cell: ({ row }: any) => {
        const payment = row.original;
        return <p>{payment?.staff?.name}</p>;
      },
    },
    {
      header: "Paid",
      accessorKey: "amount",
      cell: ({ row }: any) => {
        const payment = row.original;
        return (
          <>
            {payment?.amount === "0.00" ? (
              <></>
            ) : (
              <MoneyFormat amount={payment?.amount} />
            )}
          </>
        );
      },
    },
    {
      header: "Due",
      accessorKey: "amount",
      cell: ({ row }: any) => {
        const payment = row.original;
        return (
          <>
            {payment?.amount === "0.00" ? (
              <></>
            ) : (
              <MoneyFormat amount={payment?.amount} />
            )}
          </>
        );
      },
    },
    {
      header: "method",
      accessorKey: "fund",
    },
    {
      header: "status",
      accessorKey: "status",
    },
  ];

  return (
    <>
      {isLoading && (
        <div className="relative">
          <div className="fixed left-2/4 top-1/2 z-50">
            <Spinner size="xl" color="purple" />
          </div>
        </div>
      )}
      {payments !== undefined && (
        <div className="user-list pb-20 shadow-md">
          <div className="border-b overflow-x-auto">
            <DataTable data={payments} columns={columns} />
          </div>
          <CustomPagination
            pagination={pagination}
            currentPage={currentPage}
            onPageChange={onPageChange}
          />
        </div>
      )}
    </>
  );
};
export default ClientPayments;
