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

type LeftPanelProps = {
  model: SchemetaModel | null;
  selection: SelectionSlice;
  onSelectInstance: (ref: string) => void;
  onSelectNet: (name: string) => void;
};

type NetRow = {
  id: string;
  label: string;
};

function asNetLabel(net: Record<string, unknown>, index: number): NetRow {
  const name = typeof net.name === "string" && net.name.length > 0 ? net.name : null;
  const id = name ?? `net-${index + 1}`;
  return {
    id,
    label: name ?? `Net ${index + 1}`
  };
}

export function LeftPanel({ model, selection, onSelectInstance, onSelectNet }: LeftPanelProps) {
  const [filterText, setFilterText] = useState("");

  const filter = filterText.trim().toLowerCase();
  const instances = model?.instances ?? [];
  const netsRaw = (model?.nets ?? []).filter((item): item is Record<string, unknown> => typeof item === "object" && item !== null);
  const nets = netsRaw.map(asNetLabel);

  const filteredInstances = useMemo(
    () =>
      instances.filter((instance) => {
        if (!filter) {
          return true;
        }
        const symbol = typeof instance.symbol === "string" ? instance.symbol : "";
        const part = typeof instance.part === "string" ? instance.part : "";
        return `${instance.ref} ${symbol} ${part}`.toLowerCase().includes(filter);
      }),
    [filter, instances]
  );

  const filteredNets = useMemo(
    () =>
      nets.filter((net) => {
        if (!filter) {
          return true;
        }
        return net.label.toLowerCase().includes(filter) || net.id.toLowerCase().includes(filter);
      }),
    [filter, nets]
  );

  return (
    <aside className="panel panel--left" aria-label="Left panel">
      <h2 className="panel__title">Model Browser</h2>
      <input
        aria-label="Filter instances and nets"
        type="search"
        value={filterText}
        onChange={(event) => setFilterText(event.target.value)}
        placeholder="Filter refs, parts, nets..."
      />

      <h3>Instances ({filteredInstances.length})</h3>
      <ul>
        {filteredInstances.map((instance) => {
          const isSelected = selection.selectedRefs.includes(instance.ref);
          const descriptor = instance.symbol ?? instance.part ?? "component";
          return (
            <li key={instance.ref}>
              <button type="button" onClick={() => onSelectInstance(instance.ref)}>
                {isSelected ? "[x]" : "[ ]"} {instance.ref} - {descriptor}
              </button>
            </li>
          );
        })}
      </ul>

      <h3>Nets ({filteredNets.length})</h3>
      <ul>
        {filteredNets.map((net) => {
          const isSelected = selection.selectedNet === net.id;
          return (
            <li key={net.id}>
              <button type="button" onClick={() => onSelectNet(net.id)}>
                {isSelected ? "[x]" : "[ ]"} {net.label}
              </button>
            </li>
          );
        })}
      </ul>
    </aside>
  );
}
