// screen-add-device.jsx — "Add an appliance" form, wired to POST /household/devices
// (SaveHorAPI.addDevice). It mirrors SaveHor's other frontend one-for-one:
// device type (smart plug / aircon / whole-home CT clamp), appliance name,
// appliance type (from GET /appliance-types), and a Device ID whose label,
// placeholder and hint change per type — a Shelly MQTT prefix, a mitsubishi2mqtt
// name, or an Ampo UUID. Styled with the same Field/Btn primitives and back-arrow
// header as the other in-app screens. The whole-home clamp measures the entire
// home, not one appliance, so its appliance-type picker is hidden.
//
// onBack returns to Home without adding; onAdded(device) fires after a successful
// register so the caller can refresh Home's live device list.

// Native <select> dressed to match the Field primitive (same height, border and
// radius), with a chevron and a real focus ring. Kept local to this screen since
// it's the only place the app needs a dropdown.
function AddSelect({ label, value, onChange, children, c }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {label && <span style={{ fontSize: 13, fontWeight: 500, color: c.textMuted, letterSpacing: -0.05 }}>{label}</span>}
      <div style={{
        position: 'relative', display: 'flex', alignItems: 'center', height: 56,
        background: c.surface, border: `1.5px solid ${c.border}`, borderRadius: 14,
      }}>
        <select value={value} onChange={onChange} style={{
          flex: 1, height: '100%', border: 'none', outline: 'none', background: 'transparent',
          fontFamily: 'inherit', fontSize: 17, fontWeight: 500, color: c.text,
          padding: '0 40px 0 16px', appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none',
          cursor: 'pointer', width: '100%', borderRadius: 14,
        }}>
          {children}
        </select>
        <span style={{ position: 'absolute', right: 14, pointerEvents: 'none', display: 'flex' }}>
          <IcChevD size={18} color={c.textLight} />
        </span>
      </div>
    </label>
  );
}

function AddDeviceScreen({ c, onBack, onAdded }) {
  const { useState, useEffect } = React;
  const tr = useT();
  const [kind, setKind] = useState('smart_plug');   // 'smart_plug' | 'aircon' | 'ct_clamp'
  const [label, setLabel] = useState('');
  const [devId, setDevId] = useState('');
  const [typeId, setTypeId] = useState('');
  const [types, setTypes] = useState([]);
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState(false);

  const isClamp = kind === 'ct_clamp';

  // Load the appliance-type lookup once for the picker. Best-effort: if it fails
  // (endpoint down, offline), the type dropdown just stays empty and the device
  // still registers — appliance_type_id is optional on the backend.
  useEffect(() => {
    let alive = true;
    SaveHorAPI.getApplianceTypes()
      .then((rows) => {
        if (!alive || !Array.isArray(rows)) return;
        setTypes(rows);
        // Default the picker to the first type so a plug/aircon always sends one.
        if (rows.length) setTypeId(String(rows[0].id));
      })
      .catch(() => { /* leave the picker empty — type is optional */ });
    return () => { alive = false; };
  }, []);

  // Switching to "aircon" pre-selects the Air Conditioner type if the lookup has
  // one, exactly like SaveHor's other frontend.
  const onKindChange = (e) => {
    const next = e.target.value;
    setKind(next);
    setError('');
    if (next === 'aircon') {
      const ac = types.find((t) => t.name === 'Air Conditioner');
      if (ac) setTypeId(String(ac.id));
    }
  };

  // Per-type label / placeholder / hint for the Device ID field.
  const idCopy = isClamp
    ? { label: tr('addDevice.clampId'), placeholder: tr('addDevice.clampIdPlaceholder'), hint: tr('addDevice.clampIdHint') }
    : kind === 'aircon'
      ? { label: tr('addDevice.airconId'), placeholder: tr('addDevice.airconIdPlaceholder'), hint: tr('addDevice.airconIdHint') }
      : { label: tr('addDevice.plugId'), placeholder: tr('addDevice.plugIdPlaceholder'), hint: tr('addDevice.plugIdHint') };

  const clearErr = (setter) => (e) => { setter(e.target.value); setError(''); };

  const canSubmit = label.trim() && devId.trim() && !busy;

  const submit = async (e) => {
    if (e) e.preventDefault();
    if (!label.trim() || !devId.trim()) {
      setError(tr('addDevice.err.fill', { idName: idCopy.label }));
      return;
    }
    setBusy(true);
    setError('');
    try {
      const device = await SaveHorAPI.addDevice({
        mqtt_device_id: devId.trim(),
        label: label.trim(),
        // A whole-home clamp has no single appliance type — never send one.
        appliance_type_id: isClamp ? null : (parseInt(typeId, 10) || null),
        type: kind,
      });
      // Brief success beat, then hand control back so Home re-fetches its fleet.
      setDone(true);
      setTimeout(() => onAdded && onAdded(device), 650);
    } catch (err) {
      setError(err.message || tr('addDevice.err.generic'));
      setBusy(false);
    }
  };

  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0,
      overflowY: 'auto', background: c.bg,
    }}>
      {/* header — back arrow + title, matching the app's other in-app screens */}
      <div style={{ padding: '14px 20px 0', display: 'flex', alignItems: 'center', gap: 6 }}>
        <button onClick={onBack} aria-label={tr('addDevice.back')} style={{
          width: 36, height: 36, border: 'none', background: 'transparent', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0, flexShrink: 0,
        }}>
          <IcArrowL size={20} color={c.text} />
        </button>
        <div>
          <div style={{ fontSize: 20, fontWeight: 700, color: c.text, letterSpacing: -0.4 }}>{tr('addDevice.title')}</div>
          <div style={{ fontSize: 12.5, color: c.textMuted, marginTop: 1 }}>{tr('addDevice.sub')}</div>
        </div>
      </div>

      <div style={{ padding: '18px 24px 32px' }}>
        {done ? (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, padding: '40px 0' }}>
            <div style={{ width: 64, height: 64, borderRadius: 20, background: c.goodSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <IcCheck size={30} color={c.good} />
            </div>
            <div style={{ fontSize: 16, fontWeight: 700, color: c.text }}>{tr('addDevice.success')}</div>
          </div>
        ) : (
          <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <AddSelect label={tr('addDevice.kind')} value={kind} onChange={onKindChange} c={c}>
              <option value="smart_plug">{tr('addDevice.kindPlug')}</option>
              <option value="aircon">{tr('addDevice.kindAircon')}</option>
              <option value="ct_clamp">{tr('addDevice.kindClamp')}</option>
            </AddSelect>

            <Field
              label={tr('addDevice.name')} type="text" placeholder={tr('addDevice.namePlaceholder')}
              value={label} onChange={clearErr(setLabel)} c={c} />

            {/* The whole-home clamp has no per-appliance type, so hide the picker. */}
            {!isClamp && (
              <AddSelect label={tr('addDevice.type')} value={typeId} onChange={(e) => setTypeId(e.target.value)} c={c}>
                {types.length === 0
                  ? <option value="">{tr('addDevice.typeLoading')}</option>
                  : types.map((t) => <option key={t.id} value={String(t.id)}>{t.name}</option>)}
              </AddSelect>
            )}

            <Field
              label={idCopy.label} type="text" placeholder={idCopy.placeholder}
              helper={idCopy.hint}
              value={devId} onChange={clearErr(setDevId)} c={c} />

            {error && (
              <div style={{
                fontSize: 13, fontWeight: 500, color: c.danger,
                background: c.dangerSoft, borderRadius: 12, padding: '10px 14px', lineHeight: 1.4,
              }}>{error}</div>
            )}

            {/* Btn renders a typeless <button>, so inside the form it submits. */}
            <Btn kind="primary" size="lg" c={c} full disabled={!canSubmit} style={{ marginTop: 4 }}>
              {busy ? tr('addDevice.working') : tr('addDevice.submit')}
            </Btn>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AddDeviceScreen });
