import React from "react";
import {
  Illustration,
  renderArray,
  Table,
  Typography,
  useConfirmationModal,
} from "@komi-app/components";
import { useState } from "react";
import { Link } from "react-router-dom";
import notification from "utils/notification";
import {
  deleteFans,
  epochToDateTimeString,
  FanTableSchema,
  exportFans,
  triggerFileDownload,
  useFansList,
} from "./Utils";
import { MarketingPermission } from "@komi-app/fans-sdk";

export interface ContactsTableProps {
  searchTerm: string;
  searchFilter?: MarketingPermission;
}

const ContactsWithCursorTable = ({
  searchTerm = "",
  searchFilter = MarketingPermission.Any,
}: ContactsTableProps) => {
  const [selectedRows, setSelectedRows] = useState<FanTableSchema[]>([]);

  const confirmationModal = useConfirmationModal();

  const {
    currentPageIndex,
    data,
    isLoading,
    pageCount,
    rowCount,
    changePageIndex,
    reset,
  } = useFansList(searchTerm, searchFilter);

  const handleRowsDelete = (
    rows: FanTableSchema[],
    isAllRowsSelected: boolean,
  ) => {
    confirmationModal.open({
      title: `Are you sure you want to delete the contacts selected?`,
      description: `The contacts will be permanently deleted and you won’t be able to recover them or undo this action.`,
      buttons: [
        {
          label: "No thanks",
          variant: "primary",
          action: "cancel",
        },
        {
          label: "Delete",
          variant: "secondary",
          action: "confirm",
        },
      ],
      onConfirm: () => {
        try {
          deleteFans(rows, isAllRowsSelected).then(() => {
            setSelectedRows([]);
            reset();

            notification.success({
              message: `You have deleted ${
                isAllRowsSelected ? rowCount : rows.length
              } contacts`,
            });
          });
        } catch (error) {
          notification.error({
            message: <p>Unable to delete contacts</p>,
          });
        }
      },
      fullWidthButtons: true,
    });
  };
  const handleExportAsCSV = (
    rows: FanTableSchema[],
    isAllRowsSelected: boolean,
  ) => {
    confirmationModal.open({
      title: `You’re About to Export Audience Contact Data`,
      description: `By continuing with this export you agree to only use this data in line with our terms of service, your privacy policy and the relevant laws of your jurisdiction.`,
      buttons: [
        {
          label: "Cancel",
          variant: "secondary",
          action: "cancel",
        },
        {
          label: "Export",
          variant: "primary",
          action: "confirm",
        },
      ],
      onConfirm: async () => {
        const response = await exportFans(rows, isAllRowsSelected);

        if (response.ok) {
          const url: string = response?.response;
          triggerFileDownload(url);
        } else {
          notification.error({
            message: "Unable to export file",
          });
        }
      },
      fullWidthButtons: true,
    });
  };

  return (
    <div>
      {data.length > 0 || isLoading ? ( // If no rows are received, show empty state in else.
        <Table
          loading={isLoading}
          onPageChangeCallback={changePageIndex}
          pageCount={pageCount}
          hasExternalPagination={true}
          currentPageIndex={currentPageIndex}
          inputData={data}
          enableRowSelection={!isLoading}
          onDeleteRows={handleRowsDelete}
          selectedRows={selectedRows}
          onExportRows={handleExportAsCSV}
          noResultsRender={"No contacts matching the selected criteria"}
          totalNumberOfRecordWithPagination={rowCount}
          isSortingEnabled={false}
          columns={[
            {
              id: "name",
              accessor: "full_name",
              header: "Name",
              maxWidth: 200,
            },
            {
              id: "email",
              accessor: "email",
              header: "Email address",
              cell: ({ rowValue }) => {
                return renderArray(rowValue.email);
              },
            },
            {
              id: "phone",
              accessor: "phone_number",
              header: "Phone number",
            },
            {
              id: "firstSignedUp",
              accessor: (row: FanTableSchema) => {
                const date = new Date(row.createdAt);
                return date.toLocaleString("en-US", {
                  year: "numeric",
                  month: "short",
                  day: "2-digit",
                  hour: "numeric",
                  minute: "2-digit",
                  hour12: true,
                });
              },
              header: "First signed up",
            },
          ]}
        />
      ) : (
        <div className="contacts-page__table-placeholder">
          <Illustration
            className="placeholder-illustration"
            name="empty-state"
            width={164}
          />
          <Typography.Heading className="placeholder-heading" level={4}>
            Nothing Here Yet
          </Typography.Heading>
          <Typography.Body className="placeholder-tagline" color="gray-700">
            You haven’t collected any contact data yet. Create a
            <Link
              className="placeholder-link"
              to={{
                pathname: "/admin/modules",
              }}
            >
              {" "}
              Data Capture module{" "}
            </Link>
            to start collecting fan data.
          </Typography.Body>
        </div>
      )}
    </div>
  );
};

export default ContactsWithCursorTable;
