const AddChildModal = ({ open, onClose, onAdded }) => {
  const [name, setName] = React.useState('');
  const [age, setAge] = React.useState(9);
  const [login, setLogin] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState('');
  const [errorField, setErrorField] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    if (open) {
      setName(''); setAge(9); setLogin(''); setPassword('');
      setError(''); setErrorField(''); setLoading(false);
    }
  }, [open]);

  const submit = async (e) => {
    e?.preventDefault();
    setError(''); setErrorField('');
    if (name.trim().length < 1) { setError('Укажите имя'); setErrorField('name'); return; }
    if (!(age >= 1 && age <= 18)) { setError('Возраст: от 1 до 18'); setErrorField('age'); return; }
    if (login.trim().length < 2) { setError('Логин: минимум 2 символа'); setErrorField('login'); return; }
    if (password.length < 2) { setError('Пароль: минимум 2 символа'); setErrorField('password'); return; }

    setLoading(true);
    try {
      const { child } = await api.addChild(name.trim(), Number(age), login.trim(), password);
      onAdded?.(child);
      onClose?.();
    } catch (err) {
      setLoading(false);
      if (err.status === 409) { setError('Логин уже занят'); setErrorField('login'); }
      else if (err.status === 403) { setError('Только родители могут добавлять детей'); }
      else if (err.status === 400) { setError('Проверьте поля: ' + (err.field || '')); setErrorField(err.field || ''); }
      else setError('Ошибка: ' + (err.message || err.status));
    }
  };

  return (
    <Modal open={open} onClose={onClose} width={480}>
      <form onSubmit={submit} style={{ padding: 24 }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 4 }}>
          <div className="mono" style={{ fontSize: 11, color:'var(--fg-subtle)', letterSpacing:'.08em', textTransform:'uppercase' }}>ДОБАВИТЬ</div>
          <button type="button" onClick={onClose} style={{ background:'none', border:'none', color:'var(--fg-subtle)', cursor:'pointer' }}><IconClose size={18}/></button>
        </div>
        <h2 style={{ margin:'4px 0 16px', fontSize: 22, fontWeight: 600 }}>Новый ребёнок</h2>

        {error && (
          <div style={{ padding: 10, borderRadius: 10, background:'#FBE1DA', color:'#9A3218', fontSize: 13, marginBottom: 12 }}>{error}</div>
        )}

        <div style={{ display:'flex', flexDirection:'column', gap: 12 }}>
          <div>
            <Label>Имя</Label>
            <Input leading={<IconUser size={16}/>} placeholder="Артём" value={name} onChange={e=> setName(e.target.value)} error={errorField==='name'}/>
          </div>
          <div>
            <Label>Возраст (1–18)</Label>
            <Input leading={<IconSparkle size={16}/>} type="number" min="1" max="18" value={age} onChange={e=> setAge(Number(e.target.value))} error={errorField==='age'}/>
          </div>
          <div>
            <Label>Логин</Label>
            <Input leading={<IconMail size={16}/>} placeholder="artem2019" value={login} onChange={e=> setLogin(e.target.value)} error={errorField==='login'}/>
          </div>
          <div>
            <Label>Пароль (мин. 2 символа — можно простой, для ребёнка)</Label>
            <Input leading={<IconLock size={16}/>} type="password" placeholder="Придумайте простой пароль" value={password} onChange={e=> setPassword(e.target.value)} error={errorField==='password'}/>
          </div>
        </div>

        <div style={{ display:'flex', gap: 8, marginTop: 20 }}>
          <Button variant="ghost" full type="button" onClick={onClose}>Отмена</Button>
          <Button variant="primary" full type="submit" disabled={loading} leading={loading ? null : <IconCheck size={14}/>}>
            {loading ? 'Добавляем…' : 'Добавить'}
          </Button>
        </div>
      </form>
    </Modal>
  );
};

Object.assign(window, { AddChildModal });
