import { Button, GlassSurface, Icon, StatusBadge } from "@nodedc/ui-react";

import { useDevicePluginHost } from "../core/device-plugins/DevicePluginHost";
import type { RegisteredDeviceModel } from "../core/device-plugins/contracts";

function ModelCard({
  registered,
  onSelect,
}: {
  registered: RegisteredDeviceModel;
  onSelect: () => void;
}) {
  const { model, plugin } = registered;
  return (
    <article className="device-model-card">
      <header>
        <div className="device-model-card__mark" aria-hidden="true">
          <Icon name="network" />
        </div>
        <div>
          <span>{model.vendor}</span>
          <h3>{model.displayName}</h3>
        </div>
        <StatusBadge tone={model.verified ? "success" : "warning"}>
          {model.verified ? "Проверено" : "Экспериментально"}
        </StatusBadge>
      </header>
      <p>{model.description}</p>
      <dl>
        <div><dt>Категория</dt><dd>{model.category}</dd></div>
        <div><dt>Плагин</dt><dd>{plugin.manifest.metadata.displayName} · v{plugin.manifest.metadata.version}</dd></div>
      </dl>
      <div className="device-model-card__capabilities" aria-label="Возможности модели">
        {model.capabilities.map((capability) => <span key={capability.id}>{capability.label}</span>)}
      </div>
      <Button width="full" variant="primary" onClick={onSelect}>
        Выбрать модель
      </Button>
    </article>
  );
}

export function DeviceWorkspace({
  onOpenSpatialScene,
  onActivateAutomaticSpatialSource,
}: {
  onOpenSpatialScene: () => void;
  onActivateAutomaticSpatialSource: () => void;
}) {
  const {
    registry,
    selection,
    selectionTransitionPending,
    selectionTransitionError,
    selectModel,
    clearSelection,
  } = useDevicePluginHost();

  if (!selection) {
    return (
      <div className="device-workspace device-workspace--model-picker">
        <section className="workspace-lead workspace-lead--compact">
          <div>
            <span className="section-eyebrow">ЛОКАЛЬНОЕ УСТРОЙСТВО · ШАГ 01</span>
            <h2>Выберите модель устройства</h2>
            <p>
              Mission Core покажет только сценарий выбранного плагина. До выбора модели нет
              поиска оборудования, сетевых реквизитов, управления потоком или фиктивных метрик.
            </p>
          </div>
          <div className="workspace-lead__status">
            <StatusBadge tone="neutral">Модель не выбрана</StatusBadge>
            <span>{registry.models.length} моделей доступно в локальной сборке</span>
          </div>
        </section>

        <GlassSurface className="device-model-catalog" padding="lg">
          <header className="panel-heading">
            <div>
              <span className="section-eyebrow">УСТАНОВЛЕННЫЕ ПЛАГИНЫ</span>
              <h2>Парк поддерживаемых моделей</h2>
            </div>
            <StatusBadge tone="neutral">{registry.plugins.length} плагин</StatusBadge>
          </header>
          <div className="device-model-grid">
            {registry.models.map((registered) => (
              <ModelCard
                key={registered.model.id}
                registered={registered}
                onSelect={() => void selectModel(registered.model.id)}
              />
            ))}
          </div>
        </GlassSurface>
      </div>
    );
  }

  const ConnectionView = selection.ConnectionView;
  return (
    <div className="device-plugin-slot">
      <div className="device-plugin-slot__bar">
        <div>
          <span className="section-eyebrow">АКТИВНАЯ МОДЕЛЬ</span>
          <strong>{selection.model.displayName}</strong>
          <small>{selection.plugin.manifest.metadata.displayName} · v{selection.plugin.manifest.metadata.version}</small>
          {selectionTransitionError ? (
            <small className="device-plugin-slot__error" role="alert">
              {selectionTransitionError}
            </small>
          ) : null}
        </div>
        <Button
          variant="secondary"
          size="compact"
          disabled={selectionTransitionPending}
          onClick={() => void clearSelection()}
        >
          {selectionTransitionPending ? "Завершаем текущую сессию…" : "Выбрать другую модель"}
        </Button>
      </div>
      <ConnectionView
        model={selection.model}
        host={{
          openSpatialScene: onOpenSpatialScene,
          activateAutomaticSpatialSource: onActivateAutomaticSpatialSource,
        }}
      />
    </div>
  );
}
