// Module IIFE pour éviter la pollution de l'espace global
(function () {
  // Variables globales du module
  let parcours, contrat, client, matricule;

  // Initialisation du formulaire et des données
  function init() {
    const token = localStorage.getItem('jwtToken');

    if (token) {
      const decoded = jwt_decode(token);
      matricule = decoded.userMatricule;
    }

    // Accéder aux informations stockées du parcours
    parcours = JSON.parse(sessionStorage.getItem('parcours'));
    contrat = JSON.parse(sessionStorage.getItem('contrat'));
    client = contrat?.["@expand"]?.client || null;

    console.log("Matricule user actuel:", matricule);
    console.log("Initialisation pour formulaire client :", contrat);

    // Materialize init Modal
    var modals = document.querySelectorAll('.modal');
    M.Modal.init(modals);

    // Appel des différentes fonctions d'initialisation
    setupEventListeners();
    populateFormData();
    updateSubmitButtonState('clientForm');
  }

  // Configuration des écouteurs d'événements
  function setupEventListeners() {
    document.getElementById('clientFormBtn').addEventListener('click', handleSubmitForm);
    document.getElementById('creditsafe').addEventListener('click', (event) => handleOpenLink(event, 'creditsafeURL'));
    document.getElementById('easyQP').addEventListener('click', (event) => handleOpenLink(event, 'easyQPURL'));
    document.getElementById('refNoteFi').addEventListener('click', (event) => handleOpenLink(event, 'refNoteFiURL'));
    document.getElementById('cl063-client').addEventListener('click', (event) => handleExtractClient(event));
    document.getElementById('modalExtraireClient').addEventListener('click', (event) => handleModalExtract(event));

    // Controle de saisie et format sur les champs du formulaire        
    document.getElementById('noteFinanciereClient').addEventListener('input', function () {
      validateField('noteFinanciereClient', true);
      updateSubmitButtonState('clientForm');
    });

    document.getElementById('numClient').addEventListener('input', function () {
      validateField('numClient', true);
      updateSubmitButtonState('clientForm');
    });

    document.getElementById('nomClient').addEventListener('input', function () {
      validateField('nomClient', true);
      updateSubmitButtonState('clientForm');
    });

    document.getElementById('emailClient').addEventListener('input', function () {
      validateField('emailClient', true);
      updateSubmitButtonState('clientForm');
    });

    document.getElementById('adresseClient').addEventListener('input', function () {
      validateField('adresseClient', true);
      updateSubmitButtonState('clientForm');
    });

    document.getElementById('codePostalClient').addEventListener('input', function () {
      validateField('codePostalClient', true);
      updateSubmitButtonState('clientForm');
    });

    document.getElementById('villeClient').addEventListener('input', function () {
      validateField('villeClient', true);
      updateSubmitButtonState('clientForm');
    });

    document.getElementById('modalNumClient').addEventListener('input', function () {
      validateField('modalNumClient', true);
      updateSubmitButtonState('modalExtraireClient');
    });
  }

  // Peupler le formulaire avec les données
  function populateFormData() {
    const clientStorage = JSON.parse(sessionStorage.getItem('tmp'));

    if (client) {
      document.getElementById('nomClient').value = client.nom || '';
      document.getElementById('numClient').value = client.numClient || '';
      document.getElementById('adresseClient').value = client.adresse || '';
      document.getElementById('emailClient').value = client.mail || '';
      document.getElementById('codePostalClient').value = client.codePostal || '';
      document.getElementById('villeClient').value = client.ville || '';
      document.getElementById('noteFinanciereClient').value = client.noteFinanciere || '';
    }

    if (clientStorage) {
      document.getElementById('nomClient').value = clientStorage.nomClient || '';
      document.getElementById('numClient').value = clientStorage.numClient || '';
      document.getElementById('adresseClient').value = clientStorage.adresseClient || '';
      document.getElementById('codePostalClient').value = clientStorage.postalClient || '';
      document.getElementById('villeClient').value = clientStorage.villeClient || '';
    }
  }

  // Gérer l'ouverture de liens externes
  function handleOpenLink(event, urlType) {
    event.preventDefault();
    let url = '';

    switch (urlType) {
      case 'creditsafeURL':
        url = 'https://www.creditsafe.fr/csfr?UserName=735265dorothee&Password=UH04EuLocXZMxIRqY19w6A%3d%3d&BackOfficeCountry=FR&origincountry=FR&linkages=Y';
        break;
      case 'easyQPURL':
        if (document.getElementById('numClient').value != "") {
          url = `https://qualite-portefeuille-iard-ent.axa-fr.intraxa/client/${document.getElementById('numClient').value}`;
        } else {
          url = `https://qualite-portefeuille-iard-ent.axa-fr.intraxa/`;
        }
        break;
      case 'refNoteFiURL':
        url = 'https://app.powerbi.com/groups/me/apps/7b48f9a2-bd97-4178-bc1a-a5f7ef6e985f/reports/d29a9f83-cafe-4a0f-bc38-0929921e8cd3/ReportSection?ctid=396b38cc-aa65-492b-bb0e-3d94ed25a97b';
        break;
    }

    window.open(url, '_blank');
  }

  // Gérer l'extraction axaPAC
  async function handleExtractClient(event) {
    event.preventDefault();

    // Affiche le modal
    const elem = document.getElementById('modalExtractAxAPAC');
    const instance = M.Modal.getInstance(elem);
    instance.open();
  }

  async function handleModalExtract() {
    document.getElementById('modalExtraireClient').disabled = true;
    
    const response = await fetch(`/client/extract`, {
      method: 'POST',
      body: JSON.stringify({
        "matricule": matricule,
        "numClient": document.getElementById("modalNumClient").value
      }),
      headers: {
        'Content-Type': 'application/json',
      },
    });
    const res = await response.json();

    if (res.valid) {
      document.getElementById("error-extract").style.display = "none";
      document.getElementById('modalExtraireClient').disabled = false;
      console.log(res);

      // Save sessionStorage for Intermediaire
      sessionStorage.setItem('tmp', JSON.stringify(res.data));

      // Populate data
      document.getElementById("numClient").value = (res.data.numClient) ? res.data.numClient : null;
      document.getElementById("nomClient").value = (res.data.nomClient) ? res.data.nomClient : null;
      document.getElementById("adresseClient").value = (res.data.adresseClient) ? res.data.adresseClient : null;
      document.getElementById("codePostalClient").value = (res.data.postalClient) ? res.data.postalClient : null;
      document.getElementById("villeClient").value = (res.data.villeClient) ? res.data.villeClient : null;
      
      validateField('numClient', true);
      validateField('nomClient', true);
      validateField('adresseClient', true);
      validateField('codePostalClient', true);
      validateField('villeClient', true);
      updateSubmitButtonState('clientForm');

      // close le modal
      const elem = document.getElementById('modalExtractAxAPAC');
      const instance = M.Modal.getInstance(elem);
      instance.close();
    } else {
      document.getElementById("error-extract").style.display = "block";
      document.getElementById('modalExtraireClient').disabled = false;
      console.log("Problème rencontré lors de l'extraction cl063 AxA PAC :", res.error);
    }
  }

  // Gérer la soumission du formulaire
  async function handleSubmitForm(event) {
    event.preventDefault();

    let idClient = client?.id;
    const numClient = document.getElementById('numClient').value;

    let responseClient;

    if (numClient) {
      responseClient = await fetch(`/client/read/${numClient}`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
      });
    }
    const dataClient = await responseClient.json();

    if (dataClient.valid) {
      idClient = dataClient.idClient;
    } else {
      // Créez le client ici si non trouvé
      const responseCreateClient = await fetch(`/client/create`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
      });
      const dataCreateClient = await responseCreateClient.json();

      if (dataCreateClient.valid) {
        idClient = dataCreateClient.client.id;
      }
    }

    // Mettre à jour le contrat avec l'ID du client
    if (idClient) {
      const response = await fetch(`/client/update/${idClient}`, {
        method: 'POST',
        body: JSON.stringify({
          "nom": document.getElementById('nomClient').value.toUpperCase(),
          "numClient": document.getElementById('numClient').value,
          "adresse": document.getElementById('adresseClient').value.toUpperCase(),
          "mail": document.getElementById('emailClient').value,
          "codePostal": document.getElementById('codePostalClient').value,
          "ville": document.getElementById('villeClient').value.toUpperCase(),
          "noteFinanciere": document.getElementById('noteFinanciereClient').value
        }),
        headers: {
          'Content-Type': 'application/json',
        },
      });
      const data = await response.json();

      if (data.valid) {
        const idContrat = contrat?.id;

        fetch(`/contrat/update/client/${idContrat}/${idClient}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
        })
        .then(response => response.json())
        .then(data => {
          if (data.valid) {
            // Update Session storage
            const clientStorage = JSON.parse(sessionStorage.getItem('tmp'));

            if (clientStorage) {
              clientStorage.nomClient = document.getElementById('nomClient').value.toUpperCase();
              clientStorage.numClient = document.getElementById('numClient').value;
              clientStorage.adresseClient = document.getElementById('adresseClient').value.toUpperCase();
              clientStorage.postalClient = document.getElementById('codePostalClient').value;
              clientStorage.villeClient = document.getElementById('villeClient').value.toUpperCase();

              sessionStorage.setItem('tmp', JSON.stringify(clientStorage))
            }

            // Redirect vers intermédiaire
            window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=intermediaire`;
          } else {
            console.log('Echec lors de la mise à jour de la relation id contrat - id client :', data);
          }
        });
      }
    }
  }

  // Exposer init globalement pour y accéder depuis l'extérieur
  window.initSubmenuForm = init;
})();
