import type { RoomProfile } from '../../types/garden';
import { formatGardenValue } from './coreFormatters';

type DeviceFrequency = 'never' | 'occasionally' | 'all_the_time';
type DeviceReach = 'never' | 'only_extreme' | 'when_bit_warm' | 'basically_always' | 'when_hot_cold';

function positiveFiniteNumber(value: unknown): number | undefined {
  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
}

function normalizeFrequency(value: unknown): DeviceFrequency | undefined {
  if (value === true) return 'all_the_time';
  if (value === false) return 'never';
  if (value === 'never' || value === 'occasionally' || value === 'all_the_time') return value;
  if (value && typeof value === 'object' && !Array.isArray(value)) {
    return normalizeFrequency((value as { freq?: unknown }).freq);
  }
  return undefined;
}

function normalizeReach(value: unknown): DeviceReach | undefined {
  if (value === true) return 'basically_always';
  if (value === false) return 'never';

  if (
    value === 'never'
    || value === 'only_extreme'
    || value === 'when_bit_warm'
    || value === 'basically_always'
    || value === 'when_hot_cold'
  ) {
    return value;
  }

  if (value === 'all_the_time') return 'basically_always';
  if (value === 'occasionally') return 'when_bit_warm';

  if (value && typeof value === 'object' && !Array.isArray(value)) {
    const device = value as { reach?: unknown; freq?: unknown };
    return normalizeReach(device.reach) || normalizeReach(device.freq);
  }

  return undefined;
}

function normalizeHeatType(value: unknown): string | undefined {
  if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
  const heatType = (value as { heatType?: unknown }).heatType;
  return typeof heatType === 'string' && heatType.trim() ? heatType.trim() : undefined;
}

function formatFrequency(value: DeviceFrequency): string {
  if (value === 'all_the_time') return 'all the time';
  if (value === 'occasionally') return 'occasionally';
  return 'never';
}

function formatReach(value: DeviceReach): string {
  if (value === 'never') return 'don’t have it';
  if (value === 'only_extreme') return 'only in extreme';
  if (value === 'when_bit_warm') return 'when a bit warm/cold';
  if (value === 'basically_always') return 'basically always';
  return 'when hot/cold';
}

function formatHeatType(value: string): string {
  if (value === 'forced_air') return 'forced-air';
  if (value === 'woodstove_fireplace') return 'woodstove/fireplace';
  if (value === 'radiant') return 'radiant';
  return formatGardenValue(value).toLowerCase();
}

function hasWindow(directions: RoomProfile['windowDirections']): boolean {
  if (!Array.isArray(directions)) return false;
  return directions.some(direction => Boolean(direction && direction !== 'none' && direction !== 'unsure'));
}

export function formatAmbientArtificialLight(room: RoomProfile): string {
  if (room.usesAmbientArtificialLight === false) return 'No ambient artificial light';
  if (room.usesAmbientArtificialLight !== true) return 'Ambient artificial light not set';

  const types = Array.isArray(room.ambientArtificialLightTypes)
    ? room.ambientArtificialLightTypes.filter(Boolean)
    : [];
  const typeText = types.length ? types.map(formatGardenValue).join(', ') : 'Type not set';
  const hours = positiveFiniteNumber(room.ambientArtificialLightHoursPerDay);
  return `${typeText}${hours != null ? `, ${hours} hr/day` : ''}`;
}

/** Format a space's climate devices and window-opening context for display. */
export function formatClimateAir(room: RoomProfile): string {
  const devices = room.climateDevices;
  const active: string[] = [];

  const airConReach = normalizeReach(devices?.airCon);
  if (airConReach && airConReach !== 'never') {
    active.push(`Air con (${formatReach(airConReach)})`);
  }

  const heaterReach = normalizeReach(devices?.heater);
  if (heaterReach && heaterReach !== 'never') {
    const heaterDetails = [formatReach(heaterReach)];
    const heatType = normalizeHeatType(devices?.heater);
    if (heatType) heaterDetails.push(formatHeatType(heatType));
    active.push(`Heater (${heaterDetails.join(', ')})`);
  }

  const fanFrequency = normalizeFrequency(devices?.fan);
  if (fanFrequency && fanFrequency !== 'never') {
    active.push(`Fan (${formatFrequency(fanFrequency)})`);
  }

  const humidifierFrequency = normalizeFrequency(devices?.humidifier);
  if (humidifierFrequency && humidifierFrequency !== 'never') {
    active.push(`Humidifier (${formatFrequency(humidifierFrequency)})`);
  }

  const bits: string[] = [];
  if (active.length) bits.push(active.join(', '));

  if (hasWindow(room.windowDirections)) {
    const frequency = normalizeFrequency(room.windowOpenFrequency);
    if (frequency === 'all_the_time') bits.push('Window: open all the time');
    else if (frequency === 'occasionally') bits.push('Window: open occasionally');
    else if (frequency === 'never') bits.push('Window: seldom open');
    else bits.push('Window opening not set');
  }

  return bits.length ? bits.join(' · ') : 'Not set';
}
