import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  static values = {
        logoType: String,
        employerName: String
    }
  static targets = ["preview", "previewContainer", "logoSelect", "logoIdField", "logoNameField", "initialLogoFile"];

  async connect() {
    console.log('in connect');
    this.setPreviewImage()
    // Remember to revoke the URL when the controller is disconnected if necessary
    // this.disconnect = () => URL.revokeObjectURL(objectUrl);
  }

  async setPreviewImage() {
    const initValue = this.logoIdFieldTarget.value
    console.log(initValue)
    console.log(this.logoTypeValue)
    if (initValue) {
      const response = await fetch(`/id_card/${this.logoTypeValue}_logos/${initValue}/image`); // Fetch the binary data
      const logoType = this.logoTypeValue
      if (logoType == "employer") {
        const contentDisposition = response.headers.get('Content-Disposition');
        const filename = contentDisposition.match(/filename="?([^"]+)"?/)[1];
        this.logoNameFieldTarget.value = filename;
      }
      const blob = await response.blob();
      const objectUrl = URL.createObjectURL(blob);
      this.previewTarget.src = objectUrl;
      this.previewContainerTarget.classList.remove("hidden");
    } else {
      this.previewContainerTarget.classList.add("hidden");
    }
  }

  setSelectPreview(event) {
    this.setPreviewImage()
  }

  uploadLogo(event) {
    console.log('in uploadLogo');
    event.preventDefault()
    let logoFile = event.target.files[0];
    if (!logoFile) return;

    const logoType = this.logoTypeValue

    let newFileName = logoFile.name
    if (logoType == "network") {
      console.log("n " + newFileName);
      newFileName = this.determineNetworkFilename(logoFile)
    } else if (logoType == "employer") {
      newFileName = this.determineEmployerFilename(logoFile)
    }
    logoFile = new File([logoFile], newFileName)
    
    this.uploadLogoToServer(logoFile)
      .then((result) => {
        console.log(result);
        const logoId = result.id
        this.previewFile(logoFile);
        if (logoType == "network") {
          this.addOptionToSelect(newFileName, logoId)
        } else {
          this.logoNameFieldTarget.value = newFileName;
        }
        
        this.logoIdFieldTarget.value = logoId;
        

      })
      .catch((error) => {
        // Handle any errors that occurred
        console.error(error);
      });
  }

  previewFile(logoFile) {
    console.log('in previewFile');
    const reader = new FileReader();
    reader.onload = (e) => {
      this.previewTarget.src = e.target.result;
      this.previewContainerTarget.classList.remove("hidden");
    };
    reader.readAsDataURL(logoFile);
  }

  async uploadLogoToServer(logoFile) {
    console.log('in uploadLogoToServer');
    const formData = new FormData();
    formData.append(`id_card_${this.logoTypeValue}_logo[logo_file]`, logoFile);

    const csrfToken = document.querySelector("meta[name='csrf-token']").content;

    try {
      const response = await fetch(`/id_card/${this.logoTypeValue}_logos/`, {
        method: "POST",
        headers: {
          "X-CSRF-Token": csrfToken
        },
        body: formData
      });

      if (response.ok) {
        console.log('Upload successful!')
        const data = await response.json();
        return data;
      } else {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
    } catch (error) {
      console.error("Network error:", error);
      throw new Error("Network error:", error);
    }
  }

  addOptionToSelect(name, id) {
    const blankOptionIndex = 0;
    const newOption = new Option(name, id, true, true)

    if (this.logoIdFieldTarget.options.length > blankOptionIndex + 1) {
      this.logoIdFieldTarget.insertBefore(newOption, this.logoIdFieldTarget.options[blankOptionIndex + 1]);
    } else {
      this.logoIdFieldTarget.appendChild(newOption);
    }

  }

  determineNetworkFilename(logoFile) {
    const fileExtension = logoFile.name.split('.').pop();
    const primaryNetworkName = prompt("Enter the name for the primary network (Usually 'Cigna' or 'MedCost':");
    const secondaryNetworkName = prompt("Enter the name for the partner network (ex: Health Partners):");
    const logoFilename = this.titleizeText(primaryNetworkName).concat(this.titleizeText(secondaryNetworkName)).concat("Logo.").concat(fileExtension).replaceAll(' ', '');

    return logoFilename
  }

  determineEmployerFilename(logoFile) {
    const fileExtension = logoFile.name.split('.').pop();
    const employerName = this.employerNameValue
    const logoFilename = this.titleizeText(employerName).concat("Logo.").concat(fileExtension).replaceAll(' ', '');

    return logoFilename
  }

  titleizeText(text) {
    const titleized = text.toLowerCase();

    return titleized.replace(/(^|\s)\S/g, function(match) {
      return match.toUpperCase();
    });
  }  
}

