import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import Loader from "../components/Loader";
import ThankYou from "../ThankYou/";
import { Box, Typography } from "@mui/material";
import SuperAdmin from "./components/SuperAdmin";
import { selectUserRole, setUserRole } from "../../redux/userRoleSlice";
import Totals from "./Tiles/Totals";
import { useStyles } from "./dashboardStyles";
import { NOTIFICATION, USER_ROLES } from "../../constants";
import { generatePaymentSession, getClinicsById } from "../../services/clinics.service";
import { pushNotification } from "../../utils/notification";
import { useNavigate } from "react-router-dom";
import { updateFormDetails } from "../Signup/signupAction";
import { convertToSignupForm } from "./helper";

function Dashboard() {
  const classes = useStyles();

  const [isLoading, setIsLoading] = React.useState(true);
  const [data, setData] = useState({
    draftedJobs: 0,
    activeJobs: 0,
    closedJobs: 0,
    totalJobs: 0,
    totalMaxJobPostings: 0,
    totalMaxResumeDownloads: 0,
    resumeDownloadedCount: 0,
    remainingJobPosts: 0,
    remainingResumeDownload: 0,
    accounts: null,
    lastPlanPurchase: null,
  });
  const [isActive, setIsActive] = useState(false);
  const dispatch = useDispatch();
  const userRole = useSelector(selectUserRole);
  const user = useSelector((state) => state.login.user);

  const navigation = useNavigate();

  const getClinic = async () => {
    setIsLoading(true);
    const resp = await getClinicsById(user.created_clinics[0].id);


    // if(resp?.data?.data?.error){
    //   setIsActive(false);
    //   pushNotification("Error while fetching clinic data", NOTIFICATION.ERROR);
    //   navigation("/auth/signup/your-details?status=error");
    // }

    const status = resp?.data?.data?.clinic?.status;

    if(status == "rejected"){
      setIsActive(false);

      // update user state with latest clinic
      localStorage.setItem("user", JSON.stringify({
        ...user,
        created_clinics: resp?.data?.data?.clinic
      }))

      dispatch(setUserRole(USER_ROLES.CLINIC_ADMIN, "rejected"));

      pushNotification(resp?.data?.data?.fileStatus?.reason || "Your clinic registration has been rejected", NOTIFICATION.WARNING);
      navigation("/docs");
    }

    if(status=="payment_due"){
      setIsActive(false);
      pushNotification("Payment due", NOTIFICATION.WARNING);
      const session = await generatePaymentSession();

      if(session?.data?.error){
        pushNotification(session?.data?.message, NOTIFICATION.ERROR);
        return;
      }

      const newWindow = window.open(session?.data?.data, "_blank", "noopener,noreferrer");
      // if (!newWindow || newWindow.closed || typeof newWindow.closed === 'undefined') {
      //   // Fallback in case popup is blocked
      //   window.location.href = session?.data?.data;
      // }
    }

    // if(status=="payment_due"){
    //   setIsActive(false);
    //   pushNotification("Payment due", NOTIFICATION.WARNING);
    // }

    // if(status=="requested_doc"){
    //   setIsActive(false);
    //   pushNotification("Documents requested", NOTIFICATION.WARNING);
    // }

    setIsLoading(false);
  };

  useEffect(() => {
    // Determine user role based on user data from login reducer
    if (user) {
      // Check if user is a super admin
      // This logic can be adjusted based on your specific role criteria
      const isSuperAdmin =
        user.userType == USER_ROLES.SUPER_ADMIN.toLowerCase();
      
      if (isSuperAdmin) {
        dispatch(setUserRole(USER_ROLES.SUPER_ADMIN, ""));
      } else {
        const clinicStatus = user.created_clinics[0].status;
        setIsActive(clinicStatus == "active");
        dispatch(setUserRole(USER_ROLES.CLINIC_ADMIN, clinicStatus));
        getClinic();
      }
    }
    setIsLoading(false);
  }, [user, dispatch]);

  const superAdmin = (
    <Box>
      <SuperAdmin />
    </Box>
  );

  const clinicAdmin = (
    <Box>
      {!isActive && (
        <ThankYou />
      )}
      <Box>
        <Box>
          <Box className={classes.dashboardTitleBox}>
            <Typography variant="h4" className={classes.dashboardTitle}>
              Dashboard
            </Typography>
          </Box>
          <Totals data={data} setData={setData} />
        </Box>
      </Box>
    </Box>
  );

  return (
    <>
      {isLoading ? (
        <Loader />
      ) : userRole === USER_ROLES.SUPER_ADMIN ? (
        superAdmin
      ) : (
        clinicAdmin
      )}
    </>
  );
}

export default Dashboard;
