import backgroundImage from "@Assets/images/background_refonte.svg";
import CoffreIcon from "@Assets/logo_small_blue.svg";
import Auth from "@Front/Api/Auth/IdNot";
import Loader from "@Front/Components/DesignSystem/Loader";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import HelpBox from "@Front/Components/Elements/HelpBox";
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
import Module from "@Front/Config/Module";
import UserStore from "@Front/Stores/UserStore";
import Image from "next/image";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import classes from "./classes.module.scss";

// Importer les composants de UI pour les barres de progression
import { LinearProgress, Box, Typography as MuiTypography } from "@mui/material";

import AuthModal from "src/sdk/AuthModal";

import MessageBus from "src/sdk/MessageBus";
import Iframe from "src/sdk/Iframe";

import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import ImportData, { ProgressInfo } from "src/common/Api/LeCoffreApi/sdk/ImportData";
import RoleService from "src/common/Api/LeCoffreApi/sdk/RoleService";
import OfficeService from "src/common/Api/LeCoffreApi/sdk/OfficeService";
import OfficeRoleService from "src/common/Api/LeCoffreApi/sdk/OfficeRoleService";
import CollaboratorService from "src/common/Api/LeCoffreApi/sdk/CollaboratorService";

export default function LoginCallBack() {
  const router = useRouter();
  const [idNotUser, setIdNotUser] = useState<any>(null);
  const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);
  const [isConnected, setIsConnected] = useState(false);

  // États pour les barres de progression
  const [showProgress, setShowProgress] = useState(false);
  const [progressInfo, setProgressInfo] = useState<ProgressInfo>({
    globalProgress: 0,
    currentStep: '',
    stepProgress: 0,
    description: ''
  });

  const getOffice = async (idNotUser: any) => {
    return await new Promise<any>((resolve: (office: any) => void) => {
      OfficeService.getOffices().then((processes: any[]) => {
        const officeFound: any = processes.length > 0 ? processes.map((process: any) => process.processData).find((office: any) => office.idNot === idNotUser.office.idNot) : null;
        if (officeFound) {
          resolve(officeFound);
        } else {
          const officeData: any = {
            idNot: idNotUser.office.idNot,
            name: idNotUser.office.name,
            crpcen: idNotUser.office.crpcen,
            address: {
              create: {
                address: idNotUser.office.address.address,
                zip_code: idNotUser.office.address.zip_code,
                city: idNotUser.office.address.city
              }
            },
            office_status: 'ACTIVATED'
          };
          const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
          OfficeService.createOffice(officeData, validatorId).then((process: any) => {
            if (process) {
              const office: any = process.processData;
              resolve(office);
            }
          });
        }
      });
    });
  };

  const getCollaborator = async (collaboratorData: any) => {
    return await new Promise<any>(async (resolve: (role: any) => void) => {
      const processFound: any | null = await CollaboratorService.getCollaboratorBy({ idNot: idNotUser.idNot });
      if (processFound) {
        resolve(processFound.processData);
      } else {
        const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
        CollaboratorService.createCollaborator(collaboratorData, validatorId).then((process: any) => {
          if (process) {
            const collaborator: any = process.processData;
            resolve(collaborator);
          }
        });
      }
    });
  };

  useEffect(() => {
    async function getUser() {
      UserStore.instance.disconnect();

      // TODO: review
      // HACK: If start with http://local.lecoffreio.4nkweb:3000/authorized-client 
      //       Replace with http://localhost:3000/authorized-client
      if (window.location.href.startsWith('http://local.lecoffreio.4nkweb:3000/authorized-client')) {
        window.location.href = window.location.href.replace('http://local.lecoffreio.4nkweb:3000/authorized-client', 'http://localhost:3000/authorized-client');
        return;
      }

      const code = router.query["code"];
      if (code) {
        try {
          // Nettoyer l'URL pour ne garder que la racine
          const rootUrl = window.location.origin;
          if (window.location.href !== rootUrl) {
            window.history.replaceState({}, document.title, rootUrl);
          }

          const user: any = await Auth.getInstance().getIdNotUser(code as string);
          setIdNotUser(user.idNotUser);
          setIsAuthModalOpen(true);
          /*
          const token: any = null;
          if (!token) return router.push(Module.getInstance().get().modules.pages.Login.props.path);
          await UserStore.instance.connect(token.accessToken, token.refreshToken);
          const jwt = JwtService.getInstance().decodeJwt();
          if (!jwt) return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1");
          if (jwt.rules && !jwt.rules.includes("GET folders")) {
            return router.push(Module.getInstance().get().modules.pages.Subscription.pages.New.props.path);
          }
          setIsAuthModalOpen(true);
          //return router.push(Module.getInstance().get().modules.pages.Folder.props.path);
          */
          return;
        } catch (e: any) {
          if (e.http_status === 401 && e.message === "Email not found") {
            return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=3");
          }
          if (e.http_status === 409) {
            return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=4");
          }
          return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1");
        }
      }
      /*
      const refreshToken = CookieService.getInstance().getCookie("leCoffreRefreshToken");
      if (!refreshToken) return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1");
      const isTokenRefreshed = await JwtService.getInstance().refreshToken(refreshToken);
      const jwt = JwtService.getInstance().decodeJwt();
      if (!jwt) return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1");
      if (!jwt.rules.includes("GET folders")) {
        return router.push(Module.getInstance().get().modules.pages.Subscription.pages.New.props.path);
      }
      if (isTokenRefreshed) {
        //setIsAuthModalOpen(true);
        //return router.push(Module.getInstance().get().modules.pages.Folder.props.path);
        return;
      }
      */
      return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=2");
    }
    getUser();
  }, [router]);

  return (
    <DefaultDoubleSidePage title={"Login"} image={backgroundImage}>
      <div className={classes["root"]} style={showProgress ? { width: 'calc(75vw - 70px)', maxWidth: '1130px', margin: '80px 0 80px 70px' } : undefined}>
        <div className={classes["title-container"]}>
          <Image alt="coffre" src={CoffreIcon} width={56} />
          <Typography typo={ETypo.TITLE_H1} color={ETypoColor.TEXT_ACCENT}>
            Connexion à votre espace professionnel
          </Typography>
        </div>

        {!showProgress ? (
          <Loader color={"var(--secondary-default-base, #FF4617)"} width={29} />
        ) : (
          <Box sx={{ width: '100%', mb: 4, p: 4, px: 6, borderRadius: 2, boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)' }}>
            <MuiTypography variant="h6" align="center" sx={{ mb: 2, fontWeight: 600, color: 'var(--primary-default-base, #006BE0)' }}>
              Importation des données
            </MuiTypography>
            {/* Progression globale */}
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
              <MuiTypography variant="body2" sx={{ fontWeight: 500, color: 'text.primary' }}>
                Progression globale: <span style={{ color: 'var(--secondary-default-base, #FF4617)', fontWeight: 600 }}>{Math.round(progressInfo.globalProgress)}%</span>
              </MuiTypography>
              <MuiTypography variant="body2" sx={{ fontWeight: 500, color: 'text.secondary' }}>
                <span style={{ fontStyle: 'italic' }}>{progressInfo.currentStep}</span>
              </MuiTypography>
            </Box>
            <LinearProgress
              variant="determinate"
              value={progressInfo.globalProgress}
              sx={{
                height: 12,
                borderRadius: 6,
                backgroundColor: 'rgba(255, 70, 23, 0.15)',
                '& .MuiLinearProgress-bar': {
                  backgroundColor: 'var(--secondary-default-base, #FF4617)',
                  transition: 'transform 0.5s ease'
                }
              }}
            />

            {/* Progression par étape */}
            <Box sx={{ mt: 2, mb: 1 }}>
              <MuiTypography variant="body2" sx={{ display: 'flex', justifyContent: 'space-between', fontWeight: 500, color: 'text.primary' }}>
                <span>Progression de l'étape: <span style={{ color: 'var(--primary-default-base, #006BE0)', fontWeight: 600 }}>{Math.round(progressInfo.stepProgress)}%</span></span>
                <span style={{ maxWidth: '60%', textAlign: 'right', color: 'text.secondary' }}>{progressInfo.description || ''}</span>
              </MuiTypography>
            </Box>
            <LinearProgress
              variant="determinate"
              value={progressInfo.stepProgress}
              sx={{
                height: 8,
                borderRadius: 4,
                backgroundColor: 'rgba(0, 107, 224, 0.15)',
                '& .MuiLinearProgress-bar': {
                  backgroundColor: 'var(--primary-default-base, #006BE0)',
                  transition: 'transform 0.3s ease'
                }
              }}
            />
          </Box>
        )}
        <div />
        <HelpBox
          title="Vous n'arrivez pas à vous connecter ?"
          description="Notre équipe de support est là pour vous aider."
          button={{ text: "Contacter l'administrateur", link: "mailto:support@lecoffre.io" }}
        />
        {isAuthModalOpen && <AuthModal
          isOpen={isAuthModalOpen}
          onClose={() => {
            setIsAuthModalOpen(false);
            setIsConnected(true);
            setTimeout(() => {
              LoaderService.getInstance().show();
              MessageBus.getInstance().initMessageListener();
              MessageBus.getInstance().isReady().then(async () => {
                const office: any = await getOffice(idNotUser);
                LoaderService.getInstance().hide();

                setShowProgress(true);
                await ImportData.import(office, (info: ProgressInfo) => {
                  setProgressInfo(info);
                });
                setShowProgress(false);

                LoaderService.getInstance().show();

                const role: any = (await RoleService.getRoles())
                  .map((process: any) => process.processData)
                  .find((role: any) => role.name === idNotUser.role.name);

                const officeRole: any = (await OfficeRoleService.getOfficeRoles())
                  .map((process: any) => process.processData)
                  .filter((officeRole: any) => officeRole.office.uid === office.uid)
                  .find((officeRole: any) => officeRole.name === idNotUser.office_role.name);

                const collaboratorData: any = {
                  idNot: idNotUser.idNot,
                  contact: idNotUser.contact,
                  office: {
                    uid: office.uid
                  },
                  role: {
                    uid: role.uid
                  },
                  office_role: {
                    uid: officeRole.uid
                  }
                };
                const collaborator: any = await getCollaborator(collaboratorData);
                UserStore.instance.connect(collaborator);

                MessageBus.getInstance().destroyMessageListener();
                LoaderService.getInstance().hide();

                /*
                if (jwt.rules && !jwt.rules.includes("GET folders")) {
                  router.push(Module.getInstance().get().modules.pages.Subscription.pages.New.props.path);
                }
                */

                window.location.href = Module.getInstance().get().modules.pages.Folder.props.path;
              });
            }, 100);
          }}
        />}
        {isConnected && <Iframe />}
      </div>
    </DefaultDoubleSidePage>
  );
}
