import React, { createContext, useContext, useState, useMemo } from "react";
import { useParams } from "react-router-dom";
import Breadcrumb from "../../components/common/Breadcrumb";
import Profile from "../../components/Tenant/Profile";
import { useTenantDetails } from "../../hooks/useTenant";
import { ComingSoonPage } from "../Misc/ComingSoonPage";
import GlobalModel from "../../components/common/GlobalModel";
import EditProfile from "../../components/Tenant/EditProfile";
import SubScriptionHistory from "../../components/Tenant/SubScriptionHistory";
import { SpinnerLoader } from "../../components/common/Loader";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { MANAGE_TENANTS, SUPPER_TENANT } from "../../utils/constants";

const TenantDetailsContext = createContext();
export const useTenantDetailsContext = () => useContext(TenantDetailsContext);

const TenantDetails = ({
  tenantId: tenantIdProp,
  wrapInContainer = true,
  showBreadcrumb = true,
  iTSelf = true,
}) => {
  const { tenantId: tenantIdFromUrl } = useParams();
  const activeTenantId = tenantIdFromUrl || tenantIdProp;
  const { data, isLoading, isError, error } = useTenantDetails(activeTenantId);
  const ManageTenant = useHasUserPermission(SUPPER_TENANT);
  const ModifyTenant = useHasUserPermission(MANAGE_TENANTS);
  const [editTenant, setEditTenant] = useState(false);
  const contextValues = useMemo(
    () => ({ editTenant, setEditTenant }),
    [editTenant]
  );

  const tabs = useMemo(() => {
    const allTabs = [
      {
        id: "navs-left-home",
        label: "Profile",
        icon: "bx bx-user-circle",
        iconSize: "bx-sm",
        content: <Profile data={data} />,
      },
      {
        id: "navs-left-bill",
        label: "Bills and Plan",
        icon: "bx bx-receipt",
        iconSize: "bx-sm",
        content: (
          <div className="text-center">
            <SubScriptionHistory tenantId={activeTenantId} />
          </div>
        ),
      },
      {
        id: "navs-left-messages",
        label: "Messages",
        icon: "bx bx-message-rounded",
        iconSize: "bx-sm",
        content: (
          <div className="text-center">
            <ComingSoonPage />
          </div>
        ),
      },
    ];

    return ManageTenant
      ? allTabs
      : [allTabs[0], allTabs[allTabs.length - 1]];
  }, [data, activeTenantId, ManageTenant, ModifyTenant]);
  if (!activeTenantId) return <div className="my-4">No tenant selected.</div>;
  if (isLoading)
    return (
      <div
        className="page-min-h d-flex justify-content-center align-items-center"
        style={{ minHeight: "80vh" }}
      >
        <SpinnerLoader />
      </div>
    );

  if (isError)
    return (
      <div className="container-fluid">
        {error.status === 403 ? (
          <div className="card text-center my-4 p-2">
            <i className="fa-solid fa-triangle-exclamation fs-5"></i>
            <p>
              Access Denied: You don't have permission to perform this action!
            </p>
          </div>
        ) : (
          <div className="card text-center my-4 p-2">
            <i className="fa-solid fa-triangle-exclamation fs-5"></i>
            <p>{error.message}</p>
          </div>
        )}
      </div>
    );

  const Shell = ({ children }) =>
    wrapInContainer ? (
      <div className="container-fluid py-0">{children}</div>
    ) : (
      <>{children}</>
    );

  return (
    <>
      <TenantDetailsContext.Provider value={contextValues}>
        <Shell>
          {showBreadcrumb && (
            <Breadcrumb
              data={
                iTSelf
                  ? [
                    { label: "Home", link: "/dashboard" },
                    { label: "Tenant Details", link: null },
                  ]
                  : [
                    { label: "Home", link: "/dashboard" },
                    { label: "Tenant", link: "/tenants" },
                    { label: "Tenant Details", link: null },
                  ]
              }
            />
          )}

          <div className="nav-align-left nav-tabs-shadow mb-6">
            <ul className="nav nav-tabs py-2 page-min-h" role="tablist">
              {tabs.map((tab, index) => (
                <li key={tab.id} className="nav-item">
                  <button
                    type="button"
                    className={`nav-link d-flex align-items-center text-tiny gap-2 ${index === 0 ? "active" : ""
                      }`}
                    role="tab"
                    data-bs-toggle="tab"
                    data-bs-target={`#${tab.id}`}
                    aria-controls={tab.id}
                    aria-selected={index === 0}
                  >
                    {tab.icon && (
                      <i className={`${tab.icon} ${tab.iconSize}`} />
                    )}
                    {tab.label}
                  </button>
                </li>
              ))}
            </ul>

            <div className="tab-content">
              {tabs.map((tab, index) => (
                <div
                  key={tab.id}
                  className={`tab-pane fade ${index === 0 ? "show active" : ""
                    } text-start`}
                  id={tab.id}
                >
                  {tab.content}
                </div>
              ))}
            </div>
          </div>
        </Shell>
      </TenantDetailsContext.Provider>

      {editTenant && (
        <GlobalModel
          size="lg"
          isOpen={editTenant}
          closeModal={() => setEditTenant(false)}
        >
          <EditProfile
            TenantId={activeTenantId}
            onClose={() => setEditTenant(false)}
          />
        </GlobalModel>
      )}
    </>
  );
};

export default TenantDetails;
