import { FC, useEffect, useState } from "react";
import { Loader, Modal, Table } from "venice-ui";
import { apiCall } from "../../untils/apiCall";
import { invoiceListHeader } from "../../definitions/ListDefinition";
import { IInvoicesType, getInvoiceUrl } from "../../helpers/settingsHelper";
import { getMonthNames, t, weekDaysShortName } from "../../helpers/userHelper";
import { dictionary } from "../../untils/dictionary";
import { useStoreState } from "../../store";

interface IInvoicesModalProps {
  show: boolean;
  onClose: () => void;
  fakturowniaCustomerID: string;
}
interface IInvoicesPropsType {
  loading: boolean;
  invoices: IInvoicesType[];
}

export const InvoicesModal: FC<IInvoicesModalProps> = ({
  show,
  onClose,
  fakturowniaCustomerID,
}) => {
  const { uid } = useStoreState((state) => state.user.userDetails);

  const [pageProps, updatePageProps] = useState<IInvoicesPropsType>({
    loading: true,
    invoices: [],
  });

  const getInvoices = async () => {
    const options = {
      userID: uid,
      fakturowniaCustomerId: fakturowniaCustomerID,
    };
    await apiCall("payments/getInvoices", options, (response: any) => {
      updatePageProps({
        loading: false,
        invoices: response.invoices,
      });
    });
  };

  useEffect(() => {
    if (show) {
      getInvoices();
    }
  }, [show]);

  const downloadInvoice = (id: string) => {
    const url = getInvoiceUrl(pageProps.invoices, id);
    const download = window.open(url, "_blank");
    if (download) {
      download.focus();
    }
  };

  return (
    <>
      {show && (
        <Modal
          title={t(dictionary.invoicesList)}
          handleClose={onClose}
          size="md"
          isOpen={show}
          exitOnEsc={true}
          headerDivader={true}
          labels={{
            secondary: t(dictionary.close),
          }}
        >
          {pageProps.loading ? (
            <Loader />
          ) : (
            <Table
              headers={invoiceListHeader}
              elements={pageProps.invoices}
              sortable={true}
              filtrable={true}
              pagination={true}
              tableHeight="calc(100vh - 34.6rem)"
              tableWrapperHeight="calc(100vh - 30.6rem)"
              onRowClick={downloadInvoice}
              filterLabels={{
                title: t(dictionary.filters),
                close: t(dictionary.close),
                confirm: t(dictionary.confirm),
                trigger: t(dictionary.filters),
                clearAll: t(dictionary.resetFilters),
                clear: t(dictionary.clear),
              }}
              paginationLabel={{
                label: t(dictionary.itemPerPage),
              }}
              calendarLabels={{
                placeholder: t(dictionary.selectDate),
              }}
              calendarLocaleLabels={{
                months: getMonthNames(),
                weekdaysShort: weekDaysShortName(),
                firstDayOfWeek: 1,
              }}
              paginationZIndex={1001}
              searchInputPlaceholder={t(dictionary.invoiceSection)}
              noResultsText={t(dictionary.noResultsFound)}
            />
          )}
        </Modal>
      )}
    </>
  );
};
