import React, { useState } from "react";
import Modal from "../../components/common/Modal";
import { useAuthModal, useSelectTenant, useTenants } from "../../hooks/useAuth";
import { useProfile } from "../../hooks/useProfile";
import { useQueryClient } from "@tanstack/react-query";
import AuthRepository from "../../repositories/AuthRepository";
import Loader from "../../components/common/Loader";

const SwitchTenant = () => {
  const queryClient = useQueryClient();
  const { profile } = useProfile();
  const [pendingTenant, setPendingTenant] = useState(null);
  const { isOpen, onClose, onOpen } = useAuthModal();
  const { data, isLoading, isError, error } = useTenants();
  const { mutate: chooseTenant, isPending } = useSelectTenant(() => {
    onClose();
    queryClient.clear();

    // 2. Force fetch profile fresh for the new tenant
    queryClient.fetchQuery({
      queryKey: ["profile"],
      queryFn: () => AuthRepository.profile(),
    });
  });
  const currentTenant = localStorage.getItem("ctnt");
  const handleTenantselection = (tenantId) => {
    setPendingTenant(tenantId);
    localStorage.setItem("ctnt", tenantId);
    chooseTenant(tenantId);
  };

 
  const contentBody = (
    <div className="container text-black">
      <p className=" fs-5">Switch Workplace</p>
      <div className="row justify-content-center g-4">
        {data?.data.map((tenant) => (
          <div key={tenant.id} className="col-12 ">
            <div
              className={`d-flex flex-column flex-md-row gap-3 align-items-center align-items-md-start p-1 border ${
                currentTenant === tenant.id ? "border-primary" : ""
              }  `}
            >
              <div
                className="flex-shrink-0 text-center"
                style={{
                  width: "80px",
                  aspectRatio: "1 / 1",
                  overflow: "hidden",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                }}
              >
                <img
                  src={tenant?.logoImage || "/assets/img/SP-Placeholdeer.svg"}
                  alt={tenant.name}
                  className="img-fluid"
                  style={{
                    width: "100%",
                    height: "100%",
                    objectFit: "contain",
                  }}
                />
              </div>

              <div className="d-flex flex-column text-start gap-2">
                <p className="fs-5 text-muted fw-semibold mb-1">
                  {tenant?.name}
                </p>

                <div className="d-flex flex-wrap gap-2 align-items-center">
                  <p className="fw-semibold m-0">Industry:</p>
                  <p className="m-0">
                    {tenant?.industry?.name || "Not Available"}
                  </p>
                </div>

                {tenant?.description && (
                  <p className="text-start text-wrap m-0">
                    {tenant?.description}
                  </p>
                )}

                <button
                  className="btn btn-primary btn-sm mt-2 align-self-start"
                  onClick={() => handleTenantselection(tenant?.id)}
                  disabled={isPending && pendingTenant === tenant.id || currentTenant === tenant.id }
                >
                  {isPending && pendingTenant === tenant.id
                    ? "Please Wait.."
                    : "Go To Dashboard"}
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
  return <Modal isOpen={isOpen} onClose={onClose} body={isLoading ? <Loader/>:contentBody} />;
};

export default SwitchTenant;