import { $, component$, isBrowser, useSignal, useVisibleTask$ } from '@qwik.dev/core';
import { getDevtoolsRpc } from '../../devtools/rpc';

const BUILD_ANALYSIS_VIEW_PATH = '/__qwik_devtools/build-analysis/report';

export function getBuildAnalysisIframeSrc(version: number, origin?: string): string {
  const baseOrigin = origin ?? (isBrowser ? location.origin : '');
  if (!baseOrigin) {
    return '';
  }

  const url = new URL(BUILD_ANALYSIS_VIEW_PATH, baseOrigin);
  url.searchParams.set('v', String(version));
  return url.href;
}

export const BuildAnalysis = component$(() => {
  const iframeVersion = useSignal(0);
  const isChecking = useSignal(true);
  const isBuilding = useSignal(false);
  const hasReport = useSignal(false);
  const canTriggerBuild = useSignal(false);
  const reportPath = useSignal('');
  const buildCommand = useSignal<string | null>(null);
  const buildTriggerHint = useSignal('');
  const errorMessage = useSignal('');

  const loadStatus = $(async () => {
    isChecking.value = true;
    errorMessage.value = '';

    try {
      const rpc = await getDevtoolsRpc();
      const status = await rpc.getBuildAnalysisStatus();

      hasReport.value = status.exists;
      canTriggerBuild.value = status.canTriggerBuild;
      reportPath.value = status.reportPath;
      buildCommand.value = status.buildCommand;
      buildTriggerHint.value = status.buildTriggerHint || '';
    } catch (error) {
      errorMessage.value =
        error instanceof Error ? error.message : 'Failed to load build analysis status.';
    } finally {
      isChecking.value = false;
    }
  });

  const refreshFrame = $(() => {
    iframeVersion.value += 1;
  });

  const buildReport = $(async () => {
    if (!buildCommand.value) {
      errorMessage.value =
        'No build script found. Expected "build.client" or "build" in package.json.';
      return;
    }

    if (!canTriggerBuild.value) {
      errorMessage.value =
        buildTriggerHint.value || 'Automatic rebuild is unavailable from this DevTools client.';
      return;
    }

    const confirmed =
      globalThis.confirm?.(
        `Build analysis needs a fresh build to generate the report.\n\nRun: ${buildCommand.value} ?`
      ) ?? true;

    if (!confirmed) {
      return;
    }

    isBuilding.value = true;
    errorMessage.value = '';

    try {
      const rpc = await getDevtoolsRpc();
      const result = await rpc.buildBuildAnalysisReport();

      if (!result.success) {
        errorMessage.value = result.error || 'Build failed.';
        return;
      }

      await loadStatus();
      iframeVersion.value += 1;
    } catch (error) {
      errorMessage.value = error instanceof Error ? error.message : 'Build failed.';
    } finally {
      isBuilding.value = false;
    }
  });

  useVisibleTask$(async () => {
    await loadStatus();
  });

  return (
    <div class="flex h-full min-h-0 flex-col gap-4">
      <div class="border-glass-border bg-card-item-bg rounded-2xl border p-5">
        <div class="flex flex-col gap-3">
          <div class="text-lg font-semibold">Build Analysis</div>
          <div class="text-muted-foreground max-w-3xl text-sm leading-6">
            This tab embeds the HTML report generated by the visualizer plugin after a build.
          </div>
          {buildCommand.value ? (
            <code class="text-muted-foreground bg-foreground/5 rounded-lg px-3 py-2 text-xs">
              {buildCommand.value}
            </code>
          ) : null}
          {buildTriggerHint.value ? (
            <div class="rounded-xl border border-amber-500/20 bg-amber-500/10 px-3 py-2 text-sm text-amber-200">
              {buildTriggerHint.value}
            </div>
          ) : null}
          {errorMessage.value ? (
            <div class="rounded-xl border border-red-500/20 bg-red-500/10 px-3 py-2 text-sm text-red-300">
              {errorMessage.value}
            </div>
          ) : null}
        </div>
      </div>

      {isChecking.value ? (
        <div class="border-glass-border bg-card-item-bg text-muted-foreground rounded-2xl border p-6 text-sm">
          Checking build analysis report...
        </div>
      ) : hasReport.value ? (
        <>
          <div class="flex items-center justify-end gap-3">
            {buildCommand.value && canTriggerBuild.value ? (
              <button
                type="button"
                onClick$={buildReport}
                disabled={isBuilding.value}
                class="border-border bg-foreground/5 hover:bg-foreground/10 rounded-xl border px-4 py-2 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50"
              >
                {isBuilding.value ? 'Rebuilding...' : 'Rebuild Report'}
              </button>
            ) : null}
            <button
              type="button"
              onClick$={refreshFrame}
              class="border-border bg-foreground/5 hover:bg-foreground/10 rounded-xl border px-4 py-2 text-sm transition-colors"
            >
              Reload Report
            </button>
          </div>

          <div class="border-glass-border bg-card-item-bg min-h-0 flex-1 overflow-hidden rounded-2xl border">
            <iframe
              key={getBuildAnalysisIframeSrc(iframeVersion.value)}
              src={getBuildAnalysisIframeSrc(iframeVersion.value)}
              title="Build Analysis Report"
              class="h-full min-h-[680px] w-full border-0 bg-white"
            />
          </div>
        </>
      ) : (
        <div class="border-glass-border bg-card-item-bg rounded-2xl border p-6">
          <div class="flex max-w-3xl flex-col gap-4">
            <div class="text-base font-semibold">No build analysis report yet</div>
            <div class="text-muted-foreground text-sm leading-6">
              {canTriggerBuild.value
                ? 'The visualizer HTML file does not exist yet. You need to build the current project first, and DevTools will ask for your confirmation before running that build.'
                : 'The visualizer HTML file does not exist yet. Run the build command locally to generate it, or reconnect from localhost if you want DevTools to trigger it for you.'}
            </div>
            <code class="text-muted-foreground bg-foreground/5 rounded-lg px-3 py-2 text-xs">
              {reportPath.value}
            </code>
            <div>
              {buildCommand.value && canTriggerBuild.value ? (
                <button
                  type="button"
                  onClick$={buildReport}
                  disabled={isBuilding.value}
                  class="border-border bg-foreground/5 hover:bg-foreground/10 rounded-xl border px-4 py-2 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {isBuilding.value ? 'Building...' : 'Build Report'}
                </button>
              ) : null}
            </div>
          </div>
        </div>
      )}
    </div>
  );
});
