import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IYeelightConfig } from './yeelight.types.js';

const defaultPort = 55443;

export class YeelightConfigFlow implements IConfigFlow<IYeelightConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IYeelightConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Yeelight',
      description: 'Configure local LAN control for a Yeelight bulb. LAN control must be enabled on the bulb for live commands.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number' },
        { name: 'model', label: 'Model', type: 'text' },
        { name: 'name', label: 'Name', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || candidateArg.host;
        if (!host) {
          return { kind: 'error', title: 'Missing Yeelight host', error: 'Host is required for Yeelight local LAN control.' };
        }
        return {
          kind: 'done',
          title: 'Yeelight configured',
          config: {
            host,
            port: this.numberValue(valuesArg.port) || candidateArg.port || defaultPort,
            model: this.stringValue(valuesArg.model) || candidateArg.model,
            name: this.stringValue(valuesArg.name) || candidateArg.name,
            id: candidateArg.id,
          },
        };
      },
    };
  }

  private stringValue(valueArg: unknown): string | undefined {
    return typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim() : undefined;
  }

  private numberValue(valueArg: unknown): number | undefined {
    return typeof valueArg === 'number' && Number.isFinite(valueArg) ? valueArg : undefined;
  }
}
