import { useState } from "react";
import {
  useOrganizationModal,
  useOrganizationsList,
} from "../../hooks/useOrganization";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import Label from "../common/Label";
import Pagination from "../common/Pagination";
import "./OrgPicker.css"

const OrgPickerfromTenant = ({ title }) => {
  const [searchText, setSearchText] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const { data, isLoading } = useOrganizationsList(
    ITEMS_PER_PAGE - 10,
    1,
    true,
    null,
    searchText
  );

  const paginate = (page) => {
    if (page >= 1 && page <= (data?.totalPages ?? 1)) {
      setCurrentPage(page);
    }
  };
  const { isOpen, orgData, startStep, onOpen, flowType, prevStep } =
    useOrganizationModal();

  const handleBack = () => {
    if (prevStep == 1 && flowType == "assign") {
      onOpen({ startStep: prevStep });
    } else if (prevStep == 1 && flowType == "assign") {
      onOpen({ startStep: 1 });
    } else {
      onOpen({ startStep: 2 });
    }
  };

  const contactList = [
    {
      key: "name",
      label: "Name",
      getValue: (org) => (
        <div className="d-flex gap-2 py-1 ">
          <i class="bx bx-buildings"></i>
          <span
            className="text-truncate d-inline-block "
            style={{ maxWidth: "150px" }}
          >
            {org?.name || "N/A"}
          </span>
        </div>
      ),
      align: "text-start",
    },
    {
      key: "sprid",
      label: "SPRID",
      getValue: (org) => (
        <span
          className="text-truncate d-inline-block"
          style={{ maxWidth: "200px" }}
        >
          {org?.sprid || "N/A"}
        </span>
      ),
      align: "text-center",
    },
  ];

  return (
    <div className="d-block">
      <div className="d-flex align-items-center gap-2 mb-1">
        <Label className="mb-0">{title}</Label>
        <input
          type="text"
          value={searchText}
          onChange={(e) => setSearchText?.(e.target.value)}
          className="form-control form-control-sm w-auto"
          placeholder="Enter Organization Name"
        />
      </div>


      {/* ---- Organization list ---- */}
      {isLoading ? (
        <div>Loading....</div>
      ) : data && data?.data?.length > 0 ? (
        <div className="dataTables_wrapper no-footer pb-5">
          <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>
          </table>

          <div
            className="scrollable-tbody overflow-y-auto"
            style={{ maxHeight: "350px" }}
          >
            <table className="table dataTable text-nowrap mb-0">
              <tbody>
                {Array.isArray(data.data) && data.data.length > 0
                  ? data.data.map((row, i) => (
                    <tr key={i}>
                      {contactList.map((col) => (
                        <td key={col.key} className={col.align}>
                          {col.getValue(row)}
                        </td>
                      ))}
                      <td className="sticky-action-column p-0 bg-white">
                        <div className="p-1">
                          <span
                            type="submit"
                            className="btn btn-sm"
                            onClick={() =>
                              onOpen({ startStep: 3, orgData: row })
                            }
                          >
                            <i class='bx bx-right-arrow-circle text-primary'></i>
                          </span>
                        </div>
                      </td>
                    </tr>
                  ))
                  : null}
              </tbody>
            </table>
          </div>
        </div>
      ) : null}
      <div className="d-flex flex-column align-items-center text-center text-wrap text-black gap-2">
        <small className="mb-1">
          Could not find organization in your database? Please search within the
          global database.
        </small>
        <button
          type="button"
          className="btn btn-sm btn-primary w-auto"
          onClick={() => onOpen({ startStep: 2 })}
        >
          Search Using SPRID
        </button>
      </div>
      {/* ---- Footer buttons ---- */}
      <div
        className={`d-flex justify-content-end
         text-secondary mt-3`}
      >
        {flowType == "default" && (
          <button
            type="button"
            className="btn btn-sm btn-outline-secondary"
            onClick={handleBack}
          >
            <i className="bx bx-left-arrow-alt"></i> Back
          </button>
        )}

        {/* <button
          type="button"
          className="btn btn-sm btn-secondary"
          onClick={() => onOpen({ startStep: 4 })}
        >
          <i className="bx bx-plus-circle me-2"></i>
          Add New Organization
        </button> */}
      </div>
    </div>
  );
};

export default OrgPickerfromTenant;
