import React, { useState } from "react";
import Avatar from "../common/Avatar";
import Pagination from "../common/Pagination";
import { useDirectoryContext } from "../../pages/Directory/DirectoryPage";
import { useActiveInActiveContact } from "../../hooks/useDirectory";
import ConfirmModal from "../common/ConfirmModal";

const ListViewContact = ({ data, Pagination }) => {
  const { showActive, setManageContact, setContactOpen } =
    useDirectoryContext();
  const [deleteContact, setDeleteContact] = useState({
    contactId: null,
    Open: false,
  });
  const [activeContact, setActiveContact] = useState(null);

  const contactList = [
    {
      key: "name",
      label: "Name",
      getValue: (e) => (
        <div className="d-flex align-items-center ps-1">
          <Avatar
            size="xs"
            classAvatar="m-0"
            firstName={(e?.name || "").trim().split(" ")[0] || ""}
            lastName={(e?.name || "").trim().split(" ")[1] || ""}
          />
          <span
            className="text-truncate d-inline-block "
            style={{ maxWidth: "150px" }}
          >
            {e?.name || "N/A"}
          </span>
        </div>
      ),
      align: "text-center",
    },
    {
      key: "email",
      label: "Email",
      getValue: (e) => (
        <span
          className="text-truncate d-inline-block"
          style={{ maxWidth: "200px" }}
        >
          {e?.contactEmails?.[0]?.emailAddress || "N/A"}
        </span>
      ),
      align: "text-start",
    },
    {
      key: "organization",
      label: "Organization",
      getValue: (e) => (
        <span
          className="text-truncate d-inline-block"
          style={{ maxWidth: "200px" }}
        >
          {e?.organization || "N/A"}
        </span>
      ),
      align: "text-start",
    },
    {
      key: "category",
      label: "Category",
      getValue: (e) => (
        <span
          className="text-truncate d-inline-block"
          style={{ maxWidth: "150px" }}
        >
          {e?.contactCategory?.name || "N/A"}
        </span>
      ),
      align: "text-start",
    },
  ];

  const { mutate: ActiveInActive, isPending } = useActiveInActiveContact(() =>
    setDeleteContact({ contactId: null, Open: false })
  );

  const handleActiveInactive = (contactId) => {
    ActiveInActive({ contactId: contactId, contactStatus: !showActive });
  };

  return (
    <>
      <ConfirmModal
        type="delete"
        header="Delete Contact"
        message="Are you sure you want delete?"
        onSubmit={handleActiveInactive}
        onClose={() => setDeleteContact({ contactId: null, Open: false })}
        loading={isPending}
        paramData={deleteContact.contactId}
        isOpen={deleteContact.Open}
      />
      <div className="card ">
        <div
          className="card-datatable table-responsive"
          id="horizontal-example"
        >
          <div className="dataTables_wrapper no-footer mx-5 pb-2">
            <table className="table dataTable text-nowrap">
              <thead>
                <tr className="table_header_border">
                  {contactList?.map((col) => (
                    <th key={col.key} className={col.align}>
                      {col.label}
                    </th>
                  ))}
                  <th className="sticky-action-column bg-white text-center">
                    Action
                  </th>
                </tr>
              </thead>
              <tbody >
                {Array.isArray(data) && data.length > 0 ? (
                  data.map((row, i) => (
                    <tr
                      key={i}
                      style={{ background: `${!showActive ? "#f8f6f6" : ""}` }}
                    >
                      {contactList.map((col) => (
                        <td key={col.key} className={col.align}>
                          {col.getValue(row)}
                        </td>
                      ))}
                      <td className="text-center">
                        {showActive ? (
                          <div className="d-flex justify-content-center gap-2">
                            <i
                              className="bx bx-show text-primary cursor-pointer"
                              onClick={() =>
                                setContactOpen({ contact: row, Open: true })
                              }
                            ></i>

                            <i
                              className="bx bx-edit text-secondary cursor-pointer"
                              onClick={() =>
                                setManageContact({
                                  isOpen: true,
                                  contactId: row.id,
                                })
                              }
                            ></i>

                            <i
                              className="bx bx-trash text-danger cursor-pointer"
                              onClick={() =>
                                setDeleteContact({
                                  contactId: row.id,
                                  Open: true,
                                })
                              }
                            ></i>
                          </div>
                        ) : (
                          <i
                            className={`bx  ${
                              isPending && activeContact === row.id
                                ? "bx-loader-alt bx-spin"
                                : "bx-recycle"
                              } me-1 text-primary cursor-pointer`}
                            title="Restore"
                            onClick={() => {
                              setActiveContact(row.id);
                              handleActiveInactive(row.id);
                            }}
                          ></i>
                        )}
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr style={{ height: "200px" }}>
                    <td
                      colSpan={contactList.length + 1}
                      className="text-center align-middle"
                    >
                      No contacts found
                    </td>
                  </tr>

                )}
              </tbody>
            </table>
            {Pagination && (
              <div className="d-flex justify-content-start">
                {Pagination}
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default ListViewContact;
