import type { SchemetaModel, SelectionSlice } from "../state";

type RightInspectorProps = {
  model: SchemetaModel | null;
  selection: SelectionSlice;
  compileResult: unknown | null;
  jsonText: string;
  jsonError: string | null;
  onJsonTextChange: (value: string) => void;
  onApplyJson: () => void;
  onValidateJson: () => void;
  onFormatJson: () => void;
  onSortJson: () => void;
  onCopyRepro: () => void;
};

function asRecord(value: unknown): Record<string, unknown> | null {
  if (typeof value !== "object" || value === null) {
    return null;
  }
  return value as Record<string, unknown>;
}

function asList(value: unknown): unknown[] {
  return Array.isArray(value) ? value : [];
}

function toSnippet(value: unknown, fallback: string): string {
  if (value == null) {
    return fallback;
  }

  if (typeof value === "string") {
    return value;
  }

  try {
    return JSON.stringify(value, null, 2);
  } catch {
    return fallback;
  }
}

export function RightInspector({
  model,
  selection,
  compileResult,
  jsonText,
  jsonError,
  onJsonTextChange,
  onApplyJson,
  onValidateJson,
  onFormatJson,
  onSortJson,
  onCopyRepro
}: RightInspectorProps) {
  const selectedRef = selection.selectedRefs[0] ?? null;
  const selectedInstance = selectedRef ? (model?.instances ?? []).find((instance) => instance.ref === selectedRef) : null;

  const compile = asRecord(compileResult);
  const errors = asList(compile?.errors);
  const warnings = asList(compile?.warnings);
  const topology = compile?.topology;
  const layoutMetrics = compile?.layout_metrics;

  return (
    <aside className="panel panel--right" aria-label="Right inspector">
      <h2 className="panel__title">Selection Summary</h2>
      <p className="panel__body">Refs: {selection.selectedRefs.length > 0 ? selection.selectedRefs.join(", ") : "None"}</p>
      <p className="panel__body">Net: {selection.selectedNet ?? "None"}</p>
      <p className="panel__body">
        Pin: {selection.selectedPin ? `${selection.selectedPin.ref}.${selection.selectedPin.pin}` : "None"}
      </p>
      <p className="panel__body">
        Focused Component: {selectedInstance ? `${selectedInstance.ref} (${selectedInstance.symbol ?? selectedInstance.part ?? "component"})` : "None"}
      </p>

      <h2 className="panel__title">Diagnostics</h2>
      <p className="panel__body">Errors: {errors.length}</p>
      <p className="panel__body">Warnings: {warnings.length}</p>
      <pre>{toSnippet(errors[0], "No error diagnostics yet.")}</pre>
      <pre>{toSnippet(warnings[0], "No warning diagnostics yet.")}</pre>

      <h2 className="panel__title">Topology Snippet</h2>
      <pre>{toSnippet(topology, "No topology available yet.")}</pre>

      <h2 className="panel__title">Layout Metrics</h2>
      <pre>{toSnippet(layoutMetrics, "No layout metrics available yet.")}</pre>

      <h2 className="panel__title">JSON Editor</h2>
      <div className="json-tools">
        <button type="button" onClick={onValidateJson}>
          Validate
        </button>
        <button type="button" onClick={onFormatJson}>
          Format
        </button>
        <button type="button" onClick={onSortJson}>
          Sort Keys
        </button>
        <button type="button" onClick={onCopyRepro}>
          Copy Repro
        </button>
        <button type="button" onClick={onApplyJson}>
          Apply JSON
        </button>
      </div>
      <textarea
        className="json-editor"
        value={jsonText}
        onChange={(event) => onJsonTextChange(event.target.value)}
        spellCheck={false}
        aria-label="Schematic JSON editor"
      />
      <p className={`panel__body ${jsonError ? "json-status--error" : "json-status--ok"}`}>
        {jsonError ? `JSON error: ${jsonError}` : "JSON ready"}
      </p>
    </aside>
  );
}
