import type { ReactNode } from 'react';
import { Button, type ButtonVariant } from './Button';
import { ActionMenu, type ActionMenuItem } from './ActionMenu';

export type ServiceControlState = 'checking' | 'missing' | 'installed' | 'running' | 'stopped' | 'error';

export interface ServicePrimaryAction {
  label: string;
  onClick: () => void;
  variant?: ButtonVariant;
  loading?: boolean;
  loadingLabel?: string;
  disabled?: boolean;
}

export interface ServiceControlRowProps {
  state: ServiceControlState;
  title: string;
  detail: string;
  primaryAction?: ServicePrimaryAction;
  menu?: {
    label: string;
    open: boolean;
    onOpenChange: (open: boolean) => void;
    items: ActionMenuItem[];
    disabled?: boolean;
  };
  visualState?: 'working' | 'settling' | null;
  className?: string;
  inlineActions?: ReactNode;
  children?: ReactNode;
}

export function ServiceControlRow({
  state,
  title,
  detail,
  primaryAction,
  menu,
  visualState,
  className,
  inlineActions,
  children,
}: ServiceControlRowProps) {
  const classes = [
    'ui-service-row',
    `ui-service-row--${state}`,
    visualState ? `ui-service-row--${visualState}` : '',
    className ?? '',
  ].filter(Boolean).join(' ');

  return (
    <div className={classes}>
      <span className="ui-service-border-glow" aria-hidden="true">
        <span className="ui-service-border-glow-segment top" />
        <span className="ui-service-border-glow-segment right" />
        <span className="ui-service-border-glow-segment bottom" />
        <span className="ui-service-border-glow-segment left" />
      </span>
      <span className="ui-service-dot" aria-hidden="true" />
      <div className="ui-service-text">
        <div className="ui-service-title-line">
          <strong>{title}</strong>
          {inlineActions ? <div className="ui-service-inline-actions">{inlineActions}</div> : null}
        </div>
        <span>{detail}</span>
      </div>
      <div className="ui-service-actions">
        {primaryAction ? (
          <Button
            type="button"
            variant={primaryAction.variant ?? 'neutral'}
            onClick={primaryAction.onClick}
            disabled={primaryAction.disabled}
            loading={primaryAction.loading}
            loadingLabel={primaryAction.loadingLabel}
          >
            {primaryAction.label}
          </Button>
        ) : null}
        {menu ? (
          <ActionMenu
            label={menu.label}
            open={menu.open}
            onOpenChange={menu.onOpenChange}
            items={menu.items}
            disabled={menu.disabled}
          />
        ) : null}
      </div>
      {children}
    </div>
  );
}

