import posthog from "posthog-js";

posthog.init("phc_aUO790jHd7z1SXwsYCz8dRApxueplZlZWeDSpKc5hol", {
  api_host: "https://us.i.posthog.com",
  defaults: "2025-05-24",
  disable_session_recording: true,
});

const vscode = window.vscode;
const topWrapper = document.getElementById("initview-container");
const loadingWrapper = document.querySelector(".loading-wrapper");
const initMessageElement = document.getElementById("init-message");
const stepsContainer = document.getElementById("steps-container");
const stepProgressContainer = document.getElementById("step-progress");
const helpBtn = document.getElementById("help-btn");

helpBtn?.addEventListener("click", () => {
  vscode.postMessage({
    command: "vscodeCommand",
    cmd: "vscode.open",
    args: ["https://docs.codeflash.ai/"],
  });
});

/**
 * Constant representing the step value that indicates progress should be hidden
 */
const HIDE_PROGRESS_STEP = 0;

/**
 * Renders the horizontal step progress indicator at the top
 * @param {number} currentStep - Current step (1-indexed), HIDE_PROGRESS_STEP (0) means completed/hidden
 * @param {number} totalSteps - Total number of steps
 * @param {Array<{id: string, title: string, shortTitle: string}>} steps - Step definitions
 */
function renderStepProgress(currentStep, totalSteps, steps) {
  if (!stepProgressContainer) {
    return;
  }

  // Hide progress indicator when all steps are complete
  if (currentStep === HIDE_PROGRESS_STEP) {
    stepProgressContainer.style.display = "none";
    stepProgressContainer.innerHTML = "";
    return;
  }

  stepProgressContainer.style.display = "flex";
  stepProgressContainer.innerHTML = "";

  steps.forEach((step, index) => {
    const stepNum = index + 1;
    const isCompleted = stepNum < currentStep;
    const isCurrent = stepNum === currentStep;
    const isPending = stepNum > currentStep;

    // Step item container
    const stepItem = document.createElement("div");
    stepItem.className = "step-progress-item";
    if (isCompleted) {
      stepItem.classList.add("completed");
    }
    if (isCurrent) {
      stepItem.classList.add("current");
    }
    if (isPending) {
      stepItem.classList.add("pending");
    }

    // Step circle/indicator
    const stepCircle = document.createElement("div");
    stepCircle.className = "step-progress-circle";
    if (isCompleted) {
      const checkIcon = document.createElement("span");
      checkIcon.className = "codicon codicon-check";
      stepCircle.appendChild(checkIcon);
    } else {
      stepCircle.textContent = stepNum.toString();
    }

    // Step label
    const stepLabel = document.createElement("span");
    stepLabel.className = "step-progress-label";
    stepLabel.textContent = step.shortTitle;

    stepItem.appendChild(stepCircle);
    stepItem.appendChild(stepLabel);
    stepProgressContainer.appendChild(stepItem);

    // Add connector line between steps (except after the last step)
    if (index < steps.length - 1) {
      const connector = document.createElement("div");
      connector.className = "step-progress-connector";
      if (stepNum < currentStep) {
        connector.classList.add("completed");
      }
      stepProgressContainer.appendChild(connector);
    }
  });
}

function renderStepsUI(steps) {
  if (!stepsContainer) {
    return;
  }

  stepsContainer.innerHTML = "";

  steps.forEach((step) => {
    const hasError = step.status === "failed";
    const {
      message,
      details,
      helperCmdText,
      helperCmd,
      vscodeActionCommand,
      installAction,
      icon,
      iconFill,
    } = hasError ? step.error : {};

    const iconElementStr = icon
      ? `<span class="codicon codicon-${icon}" style="color: ${
          iconFill || "var(--vscode-editorError-foreground)"
        }"></span>`
      : "";
    const stepDiv = document.createElement("div");
    stepDiv.className = "step " + step.status;

    const indicator = document.createElement("div");
    indicator.className = "step-indicator";

    // const icon = document.createElement("span");
    // icon.className = "codicon codicon-" + step.icon;
    // indicator.appendChild(icon);

    const card = document.createElement("div");
    card.className = "step-card";

    const header = document.createElement("div");
    header.className = "step-header";

    const title = document.createElement("div");
    title.className = "step-title";
    title.textContent = step.title;
    header.appendChild(title);
    card.appendChild(header);

    // if (message) {
    //   const error = document.createElement("div");
    //   error.className = "step-error";
    //   error.innerHTML = iconElementStr + " " + message;
    //   card.appendChild(error);
    // }

    if (details) {
      const description = document.createElement("div");
      description.className = "step-description";
      description.innerHTML = iconElementStr + " " + details;
      card.appendChild(description);
    }

    if (helperCmd) {
      if (helperCmdText) {
        const cmdTextElem = document.createElement("p");
        cmdTextElem.className = "cmd-text";
        cmdTextElem.textContent = helperCmdText;
        card.appendChild(cmdTextElem);
      }

      const shell = document.createElement("div");
      shell.className = "shell-command-container";
      // wrapper will have the dollar sign and the command itself
      const wrapper = document.createElement("div");
      wrapper.className = "shell-wrapper";

      const dollarSign = document.createElement("span");
      dollarSign.className = "dollarSign";
      wrapper.appendChild(dollarSign);

      const shellCmdElem = document.createElement("div");
      shellCmdElem.className = "shell-command";
      shellCmdElem.textContent = helperCmd;
      wrapper.appendChild(shellCmdElem);

      const copyBtn = document.createElement("button");
      copyBtn.className = "copy-btn";
      const copyIcon = document.createElement("span");
      copyIcon.className = "codicon codicon-copy";
      copyBtn.appendChild(copyIcon);
      copyBtn.addEventListener("click", () => {
        navigator.clipboard.writeText(helperCmd);
        copyIcon.className = "codicon codicon-check";
        setTimeout(() => {
          copyIcon.className = "codicon codicon-copy";
        }, 2000);
      });

      shell.appendChild(wrapper);
      shell.appendChild(copyBtn);

      card.appendChild(shell);
    }

    // Create a container for action buttons (centered)
    if (installAction || vscodeActionCommand) {
      const actionsContainer = document.createElement("div");
      actionsContainer.className = "step-actions-container";

      if (installAction) {
        const { btnText, command, disclaimer, showCommand } = installAction;

        // Show interpreter path first
        if (disclaimer) {
          const disclaimerLabel = document.createElement("p");
          disclaimerLabel.className = "step-disclaimer-label";
          disclaimerLabel.textContent = "Will install to active interpreter:";
          actionsContainer.appendChild(disclaimerLabel);

          const disclaimerElem = document.createElement("div");
          disclaimerElem.className = "step-disclaimer";
          const iconSpan = document.createElement("span");
          iconSpan.className = "codicon codicon-folder";
          disclaimerElem.appendChild(iconSpan);
          const textSpan = document.createElement("span");
          textSpan.textContent = disclaimer;
          disclaimerElem.appendChild(textSpan);
          actionsContainer.appendChild(disclaimerElem);
        }

        // Install button
        const installBtn = document.createElement("button");
        installBtn.id = "install-codeflash-btn";
        installBtn.innerHTML = `<span class="codicon codicon-python"></span> ${btnText}`;
        installBtn.className = "step-action-btn install-btn";

        const cancelBtn = document.createElement("button");
        cancelBtn.id = "cancel-install-btn";
        cancelBtn.innerHTML = `<span class="codicon codicon-close"></span> Cancel`;
        cancelBtn.className = "step-action-btn cancel-btn";
        cancelBtn.style.display = "none";

        installBtn.addEventListener("click", () => {
          installBtn.disabled = true;
          installBtn.innerHTML = `<span class="codicon codicon-loading spin"></span> Installing...`;
          cancelBtn.style.display = "block";
          vscode.postMessage({
            command: "runInstallCommand",
            installCommand: command,
          });
        });

        cancelBtn.addEventListener("click", () => {
          vscode.postMessage({ command: "cancelInstallCommand" });
          installBtn.disabled = false;
          installBtn.innerHTML = `<span class="codicon codicon-python"></span> ${btnText}`;
          cancelBtn.style.display = "none";
        });

        actionsContainer.appendChild(installBtn);
        actionsContainer.appendChild(cancelBtn);

        // Show "select different interpreter" option after install button
        if (vscodeActionCommand) {
          const {
            title,
            btnText: vscodeBtnText,
            command: vscodeCmd,
            args = [],
          } = vscodeActionCommand;
          if (title) {
            const detailsElem = document.createElement("p");
            detailsElem.className = "step-action";
            detailsElem.textContent = title;
            actionsContainer.appendChild(detailsElem);
          }

          const actionBtn = document.createElement("button");
          actionBtn.textContent = vscodeBtnText;
          actionBtn.className = "step-action-btn secondary-btn";
          actionBtn.addEventListener("click", () => {
            vscode.postMessage({
              command: "vscodeCommand",
              cmd: vscodeCmd,
              args,
            });
          });
          actionsContainer.appendChild(actionBtn);
        }

        // Show manual command collapsible after install button
        if (showCommand) {
          const detailsElem = document.createElement("details");
          detailsElem.className = "manual-command-details";

          const summaryElem = document.createElement("summary");
          summaryElem.className = "manual-command-summary";
          summaryElem.textContent = "Or run this installation command manually";
          detailsElem.appendChild(summaryElem);

          const shell = document.createElement("div");
          shell.className = "shell-command-container";

          const wrapper = document.createElement("div");
          wrapper.className = "shell-wrapper";

          const dollarSign = document.createElement("span");
          dollarSign.className = "dollarSign";
          wrapper.appendChild(dollarSign);

          const shellCmdElem = document.createElement("div");
          shellCmdElem.className = "shell-command";
          shellCmdElem.textContent = command;
          wrapper.appendChild(shellCmdElem);

          const copyBtn = document.createElement("button");
          copyBtn.className = "copy-btn";
          const copyIcon = document.createElement("span");
          copyIcon.className = "codicon codicon-copy";
          copyBtn.appendChild(copyIcon);
          copyBtn.addEventListener("click", () => {
            navigator.clipboard.writeText(command);
            copyIcon.className = "codicon codicon-check";
            setTimeout(() => {
              copyIcon.className = "codicon codicon-copy";
            }, 2000);
          });

          shell.appendChild(wrapper);
          shell.appendChild(copyBtn);
          detailsElem.appendChild(shell);
          actionsContainer.appendChild(detailsElem);
        }
      } else if (vscodeActionCommand) {
        // Only show vscodeActionCommand separately if there's no installAction
        const { title, btnText, command, args = [] } = vscodeActionCommand;
        if (title) {
          const detailsElem = document.createElement("p");
          detailsElem.className = "step-action";
          detailsElem.textContent = title;
          actionsContainer.appendChild(detailsElem);
        }

        const actionBtn = document.createElement("button");
        actionBtn.textContent = btnText;
        actionBtn.className = "step-action-btn secondary-btn";
        actionBtn.addEventListener("click", () => {
          vscode.postMessage({ command: "vscodeCommand", cmd: command, args });
        });
        actionsContainer.appendChild(actionBtn);
      }

      card.appendChild(actionsContainer);
    }

    stepDiv.appendChild(indicator);
    stepDiv.appendChild(card);
    stepsContainer.appendChild(stepDiv);
  });
  // restart button
  const existingRestartBtn = document.getElementById("restart-btn");
  if (existingRestartBtn) {
    return;
  }
  // create it
  const restartBtn = document.createElement("button");
  restartBtn.id = "restart-btn";
  restartBtn.className = "restart-btn";
  restartBtn.textContent = "Restart Codeflash";
  restartBtn.addEventListener("click", () => {
    restartBtn.disabled = true;
    vscode.postMessage({ command: "restartCodeflash" });
  });
  topWrapper.appendChild(restartBtn);
}

function showInstallError(errorMessage) {
  // Remove any existing error alert
  const existingError = document.querySelector(".install-error-alert");
  if (existingError) {
    existingError.remove();
  }

  const actionsContainer = document.querySelector(".step-actions-container");
  if (!actionsContainer) return;

  const errorAlert = document.createElement("div");
  errorAlert.className = "install-error-alert";
  const errorIcon = document.createElement("span");
  errorIcon.className = "codicon codicon-error";
  errorAlert.appendChild(errorIcon);
  const errorText = document.createElement("span");
  errorText.textContent = errorMessage;
  errorAlert.appendChild(errorText);

  // Insert after the cancel button or at the end
  const cancelBtn = document.getElementById("cancel-install-btn");
  if (cancelBtn) {
    cancelBtn.after(errorAlert);
  } else {
    actionsContainer.appendChild(errorAlert);
  }

  // Reset install button
  const installBtn = document.getElementById("install-codeflash-btn");
  if (installBtn) {
    installBtn.disabled = false;
    installBtn.innerHTML = `<span class="codicon codicon-python"></span> Install codeflash Python package`;
  }
  if (cancelBtn) {
    cancelBtn.style.display = "none";
  }
}

window.addEventListener("message", (event) => {
  console.log("Message received:", event.data);
  const outgoingMessage = event.data;
  if (outgoingMessage.command === "updateStepProgress") {
    renderStepProgress(
      outgoingMessage.currentStep,
      outgoingMessage.totalSteps,
      outgoingMessage.steps,
    );
  } else if (outgoingMessage.command === "updateInitMessage") {
    if (initMessageElement) {
      initMessageElement.textContent = outgoingMessage.message;
    }
  } else if (outgoingMessage.command === "renderSteps") {
    if (typeof window.hideInitForm === "function") {
      window.hideInitForm();
    }
    if (loadingWrapper && stepsContainer) {
      loadingWrapper.style.display = "none";
      stepsContainer.style.display = "flex";
      showRestartButton();
      renderStepsUI(outgoingMessage.steps);
    }
  } else if (outgoingMessage.command === "showLoadingView") {
    if (typeof window.hideInitForm === "function") {
      window.hideInitForm();
    }
    if (loadingWrapper && stepsContainer) {
      stepsContainer.style.display = "none";
      loadingWrapper.style.display = "flex";
      showRestartButton(false);
    }
  } else if (outgoingMessage.command === "showInitForm") {
    // defined in main.tsx
    window.renderInitForm(
      outgoingMessage.suggestions,
      outgoingMessage.errorDetails,
      outgoingMessage.pyprojectPath,
    );
  } else if (outgoingMessage.command === "setInitFormFieldErrors") {
    // Send field errors to the form component
    if (window.setInitFormFieldErrors) {
      window.setInitFormFieldErrors(outgoingMessage.fieldErrors);
    }
  } else if (outgoingMessage.command === "startSessionRecording") {
    posthog.identify(outgoingMessage.userId);
    posthog.startSessionRecording();
    posthog.capture("session_recording_started", {});
  } else if (outgoingMessage.command === "stopSessionRecording") {
    posthog.stopSessionRecording();
  } else if (outgoingMessage.command === "installError") {
    showInstallError(outgoingMessage.error);
  } else if (outgoingMessage.command === "installCancelled") {
    const installBtn = document.getElementById("install-codeflash-btn");
    const cancelBtn = document.getElementById("cancel-install-btn");
    if (installBtn) {
      installBtn.disabled = false;
      installBtn.innerHTML = `<span class="codicon codicon-python"></span> Install codeflash Python package`;
    }
    if (cancelBtn) {
      cancelBtn.style.display = "none";
    }
  }
});
function showRestartButton(show = true) {
  const restartBtn = document.getElementById("restart-btn");
  if (restartBtn) {
    restartBtn.style.display = show ? "block" : "none";
  }
}
vscode.postMessage({ command: "webviewLoaded" });
// so it's treated like a module
module.exports = {};
