import { useEffect, useState } from "react";
import { useTenants, useSelectTenant, useLogout } from "../../hooks/useAuth.jsx";
import { Link, useNavigate } from "react-router-dom";
import Dashboard from "../../components/Dashboard/Dashboard.jsx";
import Loader from "../../components/common/Loader.jsx";

const TenantSelectionPage = () => {
  const [pendingTenant, setPendingTenant] = useState(null);
  const navigate = useNavigate();

  const { data, isLoading, isError, error } = useTenants();
  const { mutate: chooseTenant, isPending } = useSelectTenant(() => {
    navigate("/dashboard");
  });
  const handleTenantselection = (tenantId) => {
    setPendingTenant(tenantId);
    localStorage.setItem("ctnt", tenantId);
    chooseTenant(tenantId);
  };
  
  const {mutate:handleLogout,isPending:isLogouting} = useLogout(()=>{})


  useEffect(() => {
    if (localStorage.getItem("ctnt")) {
      navigate("/dashboard");
    }
  }, [navigate]);

  useEffect(() => {
    if (!isLoading && data?.data?.length === 1) {
      const tenant = data.data[0];
      handleTenantselection(tenant.id);
    }
  }, [isLoading, data]);

  if (isLoading) return <Loader />;

  if (isLoading) {
    return <Loader />;
  }

  if (!data?.data?.length) {
    return (
      <div className="text-center py-5">
        <p>No tenant assigned to your account.</p>
      </div>
    );
  }


  return (
    <div className="container-fluid">
      {/* Logo */}
      <div className="text-center">
        <img
          src="/img/brand/marco.png"
          alt="marco-logo"
          className="app-brand-logo-login img-fluid"
          style={{ maxHeight: "80px" }}
        />
      </div>

      {/* Heading */}
      <div className="text-center mb-4">
        <p className="fs-4 fw-bold mb-1">Welcome</p>
        <p className="fs-6 fs-md-5">
          Please select which dashboard you want to explore!!!
        </p>
        <div  onClick={()=>handleLogout()}>
          {isLogouting ? "Please Wait...":<span className="fs-6 fw-semibold cursor-pointer text-decoration-underline"><i className='bx bx-log-out'></i>SignOut</span>}
        </div>
      
      </div>

      {/* Card Section */}
      <div className="row justify-content-center g-4 ">
        {data?.data.map((tenant) => (
          <div key={tenant.id} className="col-12 col-md-10 col-lg-8">
            <div className="d-flex flex-column flex-md-row gap-4 align-items-center align-items-md-start p-3 border rounded shadow-sm bg-white h-100">

              {/* Image */}
              <div className="flex-shrink-0 text-center">
                <img
                  src={tenant?.logoImage || "/assets/img/SP-Placeholdeer.svg"}
                  alt={tenant.name}
                  className="img-fluid rounded"
                  style={{
                    maxWidth: "140px",
                    aspectRatio: "3 / 2",
                    objectFit: "contain",
                  }}
                />
              </div>

              {/* Content */}
              <div className="d-flex flex-column text-start gap-2 w-100">
                {/* Title */}
                <p className="fs-5 fs-md-4 text-dark fw-semibold mb-1">
                  {tenant?.name}
                </p>

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

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

                {/* Button */}
                <button
                  className="btn btn-primary btn-sm mt-2 align-self-start"
                  onClick={() => handleTenantselection(tenant?.id)}
                  disabled={pendingTenant === tenant.id && isPending}
                >
                  {isPending && pendingTenant === tenant.id
                    ? "Please Wait.."
                    : "Go To Dashboard"}
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>

  );
};

export default TenantSelectionPage;