import React, { useEffect, useState } from "react";
import { useTenants } from "../../hooks/useTenant";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import { getTenantStatus } from "../../utils/dateUtils";
import IconButton from "../common/IconButton";
import Pagination from "../common/Pagination";
import { TenantTableSkeleton } from "./TenanatSkeleton";
import { useTenantContext } from "../../pages/Tenant/TenantPage";
import { useNavigate } from "react-router-dom";

const TenantsList = ({
  filters,
  searchText,
  setIsRefetching,
  setRefetchFn,
}) => {
  const [currentPage, setCurrentPage] = useState(1);
  const navigate = useNavigate();
  const {
    data,
    isLoading,
    isError,
    isInitialLoading,
    error,
    refetch,
    isFetching,
  } = useTenants(currentPage, filters, searchText);

  const { setRefetching } = useTenantContext();

  const paginate = (page) => {
    if (page >= 1 && page <= (data?.totalPages ?? 1)) {
      setCurrentPage(page);
    }
  };

  // Pass the refetch function to parent when component mounts
  useEffect(() => {
    setRefetchFn(() => refetch); // store in parent
  }, [setRefetchFn, refetch]);

  // Sync fetching status with parent
  useEffect(() => {
    setIsRefetching(isFetching);
  }, [isFetching, setIsRefetching]);

  const TenantColumns = [
    {
      key: "name",
      label: "Organization",
      getValue: (t) => (
        <div
          className="d-flex align-items-center py-1 cursor-pointer"
          onClick={() => navigate(`/tenant/${t.id}`)}
        >
          {t.logoImage ? (
            <img
              src={t.logoImage}
              alt={`${t.name} Logo`}
              style={{
                height: "25px",
                width: "25px",
                objectFit: "contain",
                borderRadius: "4px",
              }}
              className="me-2"
            />
          ) : (
            <IconButton
              iconClass="bx bx-sm bx-building"
              color="warning"
              size={8}
            />
          )}

          {t.name || "N/A"}
        </div>
      ),
      align: "text-start",
    },
    {
      key: "domainName",
      label: "Domain",
      getValue: (t) => (
        <div style={{ width: "160px" }} className="text-truncate">
          <a href={t.domainName} className="text-decoration-none">
            <i className="bx bx-globe text-primary bx-xs me-2"></i>
            {t.domainName || "N/A"}
          </a>
        </div>
      ),
      align: "text-start",
    },
    {
      key: "contactName",
      label: "Contact Person",
      getValue: (t) => (
        <div className="d-flex align-items-center text-start">
          <i className="bx bx-sm bx-user me-1" />
          {t.contactName || "N/A"}
        </div>
      ),
      align: "text-start",
    },
    {
      key: "contactNumber",
      label: "Contact",
      getValue: (t) => t.contactNumber || "N/A",
      isAlwaysVisible: true,
    },
    {
      key: "status",
      label: "Status",
      align: "text-center",
      getValue: (t) => (
        <span
          className={`badge ${
            getTenantStatus(t.tenantStatus?.id) || "secondary"
          }`}
        >
          {t.tenantStatus?.name || "Unknown"}
        </span>
      ),
    },
  ];
  if (isInitialLoading)
    return <TenantTableSkeleton columns={TenantColumns} rows={13} />;
  if (isError)
    return (
      <div className="">
        <div className="text-center my-4 p-2">
          <i className="fa-solid fa-triangle-exclamation fs-5"></i>
          <p>{error.message}</p>
        </div>
      </div>
    );
  return (
    <>
      <div className="p-2 mt-3">
        <div className="card-datatable text-nowrap table-responsive">
          <table className="table border-top dataTable text-nowrap">
            <thead>
              <tr className="shadow-sm">
                {TenantColumns.map((col) => (
                  <th key={col.key} className="sorting d-table-cell">
                    <div className={col.align}>{col.label}</div>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {data?.data.length > 0 ? (
                data.data.map((tenant) => (
                  <tr key={tenant.id}>
                    {TenantColumns.map((col) => (
                      <td
                        key={col.key}
                        className={`d-table-cell px-3 py-2 align-middle ${
                          col.align ?? ""
                        }`}
                      >
                        {col.customRender
                          ? col.customRender(tenant)
                          : col.getValue(tenant)}
                      </td>
                    ))}
                  </tr>
                ))
              ) : (
                <tr>
                  <td
                    colSpan={TenantColumns.length + 1}
                    className="text-center py-4 border-0"
                  >
                    No Tenants Found
                  </td>
                </tr>
              )}
            </tbody>
          </table>
          {data?.data?.length > 0 && (
            <Pagination
              currentPage={currentPage}
              totalPages={data.totalPages}
              onPageChange={paginate}
            />
          )}
        </div>
      </div>
    </>
  );
};

export default TenantsList;
