import { useState, useEffect, useCallback } from 'react'
import './App.css'

import MessageConsole from './components/MessageConsole'
import ControlPanel from './components/ControlPanel'
import ProfileModal from './components/ProfileModal'
import AuthModal from './sdk/AuthModal';
import MessageBus from './sdk/MessageBus';
import EventBus from './sdk/EventBus';
import UserStore from './sdk/UserStrore';
import Iframe from './sdk/Iframe'
import BlockchainViewer from './components/ProcessesViewer';
import FolderModal from './components/FolderModal';
import { ProfilePrivateFields, setDefaultProfileRoles, type ProfileCreated, type ProfileData } from './sdk/models/ProfileData'
import { FolderPrivateFields, setDefaultFolderRoles, type FolderCreated, type FolderData } from './sdk/models/FolderData'

export const iframeUrl = 'https://dev3.4nkweb.com'

function App() {
  const [receivedMessages, setReceivedMessages] = useState<{ timestamp: string; data: any }[]>([])
  const [isConnected, setIsConnected] = useState(false)
  const [showProfileModal, setShowProfileModal] = useState(false)
  const [showAuthModal, setShowAuthModal] = useState(false)
  const [showFolderModal, setShowFolderModal] = useState(false)
  const [processes, setProcesses] = useState<any>(null)
  const [myProcesses, setMyProcesses] = useState<string[]>([])
  const [userPairingId, setUserPairingId] = useState<string | null>(null)

  useEffect(() => {
    setIsConnected(UserStore.getInstance().isConnected());
  });

  useEffect(() => {
    setUserPairingId(UserStore.getInstance().getUserPairingId());
  });

  useEffect(() => {
    if (isConnected) {
      const messageBus = MessageBus.getInstance(iframeUrl);
      messageBus.isReady().then(() => {
        messageBus.getProcesses().then((processes: any) => {
          setProcesses(processes);
        });
      });
    }
  }, [isConnected, iframeUrl]);

  useEffect(() => {
    if (isConnected && processes !== null) {
      const messageBus = MessageBus.getInstance(iframeUrl);
      messageBus.isReady().then(() => {
        messageBus.getMyProcesses().then((res: string[]) => {
          setMyProcesses(res);
        })
      });
    }
  }, [isConnected, processes]);

  useEffect(() => {
    if (isConnected && userPairingId === null) {
      const messageBus = MessageBus.getInstance(iframeUrl);
      messageBus.isReady().then(() => {
        messageBus.getUserPairingId().then((userPairingId: string) => {
          UserStore.getInstance().pair(userPairingId);
          setUserPairingId(UserStore.getInstance().getUserPairingId());
        })
      });
    }
  }, [isConnected, userPairingId, processes]);

  // Gestionnaire pour afficher la modale de connexion
  const handleLogin = useCallback(() => {
    // Afficher la modale de connexion
    setShowAuthModal(true);
  }, []);

  // Gestionnaire pour la déconnexion
  const handleLogout = useCallback(() => {
    // Déconnecter l'utilisateur
    UserStore.getInstance().disconnect();
    setIsConnected(false);

    // Émettre un événement pour vider aussi les messages locaux dans MessageConsole
    EventBus.getInstance().emit('CLEAR_CONSOLE');

    // Vider les processes
    setProcesses(null);
  }, []);

  // Gestionnaire pour ouvrir la modale de profil
  const handleOpenProfileModal = useCallback(() => {
    setShowProfileModal(true);
  }, []);

  // Gestionnaire pour ouvrir la modale de création de dossier
  const handleOpenFolderModal = useCallback(() => {
    setShowFolderModal(true);
  }, []);

  // Gestionnaire pour fermer la modale de création de dossier
  const handleCloseFolderModal = useCallback(() => {
    setShowFolderModal(false);
  }, []);

  // Gestionnaire pour fermer la modale de création de profil
  const handleCloseProfileModal = useCallback(() => {
    setShowProfileModal(false);
  }, []);

  // Gestionnaire pour soumettre les données du profil
  const handleProfileSubmit = useCallback((profileData: ProfileData, validatorId: string | null, ownerId: string | null) => {
    if (userPairingId !== null) {
      if (validatorId === null && ownerId === null) {
        console.error("No validator or owner ID provided");
        return;
      }
      const messageBus = MessageBus.getInstance(iframeUrl);
      if (validatorId === null) {
        validatorId = userPairingId;
      } else if (ownerId === null) {
        ownerId = userPairingId;
      }
      const roles = setDefaultProfileRoles([ownerId!], validatorId!);
      const profilePrivateFields = ProfilePrivateFields;
      messageBus.createProfile(profileData, profilePrivateFields, roles).then((_profileCreated: ProfileCreated) => {
        messageBus.notifyProcessUpdate(_profileCreated.processId, _profileCreated.process.states[0].state_id).then(() => {
          messageBus.validateState(_profileCreated.processId, _profileCreated.process.states[0].state_id).then((_updatedProcess: any) => {
            messageBus.getProcesses().then((processes: any) => {
              setProcesses(processes);
            });
          });
        })
      });

      setShowProfileModal(false);
    }
  }, [userPairingId]);

  // Gestionnaire pour soumettre les données du dossier
  const handleFolderSubmit = useCallback((folderData: FolderData) => {
    if (userPairingId !== null) {
      const roles = setDefaultFolderRoles(userPairingId, [], []);
      const folderPrivateFields = FolderPrivateFields;
      MessageBus.getInstance(iframeUrl).createFolder(folderData, folderPrivateFields, roles).then((_folderCreated: FolderCreated) => {
        MessageBus.getInstance(iframeUrl).notifyProcessUpdate(_folderCreated.processId, _folderCreated.process.states[0].state_id).then(() => {
          MessageBus.getInstance(iframeUrl).validateState(_folderCreated.processId, _folderCreated.process.states[0].state_id).then((_updatedProcess: any) => {
            MessageBus.getInstance(iframeUrl).getProcesses().then((processes: any) => {
              setProcesses(processes);
            });
          });
        })
      });

      setShowFolderModal(false);
    }
  }, [userPairingId]);

  // Gestionnaire du clic sur le bouton Vider les messages
  const handleClearMessages = useCallback(() => {
    setReceivedMessages([]);
  }, []);

  return (
    <div className="home-container">
      <header className="home-header">
        <h1>[4NK]</h1>
      </header>

      <main className="home-main">
        <div className="welcome-section">
          {/* Panneau de contrôle avec iframe */}
          <ControlPanel
            isConnected={isConnected}
            onLogin={handleLogin}
            onLogout={handleLogout}
            onCreateProfile={handleOpenProfileModal}
            onCreateFolder={handleOpenFolderModal}
            iframeUrl={iframeUrl}
          />

          {/* Structure flexible avec console à gauche et contenu à droite */}
          <div className="app-content-layout">
            {/* Console de messages (largeur fixe à gauche) */}
            <MessageConsole
              messages={receivedMessages}
              onClearMessages={handleClearMessages}
            />

            {/* Espace pour contenu supplémentaire à droite */}
            <div className="content-area">
              {/* Affichage des blocs de la blockchain */}
              <BlockchainViewer processes={processes} myProcesses={myProcesses} onProcessesUpdate={setProcesses}/>
            </div>
          </div>

          {/* Modales */}
          {showAuthModal && (
            <AuthModal
              isOpen={showAuthModal}
              onConnect={() => {
                setIsConnected(true);
                setShowAuthModal(false);
              }}
              onClose={() => setShowAuthModal(false)}
              iframeUrl={iframeUrl}
            />
          )}
          {showProfileModal && (
            <ProfileModal
              isOpen={showProfileModal}
              onClose={handleCloseProfileModal}
              onSubmit={(profileData: ProfileData, validatorId: string | null, ownerId: string | null) => handleProfileSubmit(profileData, validatorId, ownerId)}
            />
          )}
          {showFolderModal && (
            <FolderModal
              isOpen={showFolderModal}
              onClose={handleCloseFolderModal}
              onSave={handleFolderSubmit}
              onCancel={handleCloseFolderModal}
            />
          )}

          {/* N'afficher l'iframe que si l'utilisateur est connecté */}
          {isConnected && <Iframe iframeUrl={iframeUrl} />}
        </div>
      </main>
    </div>
  )
}

export default App
