import { useState } from 'react'
import Modal from '../../../components/Modal.jsx'
import { api } from '../../../api/client.js'

export default function UserEditor({ user, onClose, onSaved }) {
  const isEdit = Boolean(user)
  const [form, setForm] = useState({
    username: user?.username || '',
    password: '',
    role: user?.role || 'admin',
    status: user?.status || 'active',
    email: user?.email || '',
  })
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState('')

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }))

  async function save() {
    if (!form.username.trim()) return setError('Username is required.')
    if (!isEdit && form.password.length < 8) return setError('Password must be at least 8 characters.')
    if (isEdit && form.password && form.password.length < 8) return setError('Password must be at least 8 characters.')
    setBusy(true)
    setError('')
    try {
      const email = form.email.trim() || null
      if (isEdit) {
        const payload = { username: form.username.trim(), role: form.role, status: form.status, email }
        if (form.password) payload.password = form.password
        await api.admin.updateUser(user.id, payload)
      } else {
        await api.admin.createUser({
          username: form.username.trim(),
          password: form.password,
          role: form.role,
          status: form.status,
          email,
        })
      }
      onSaved()
    } catch (err) {
      setError(err.message || 'Could not save the user.')
      setBusy(false)
    }
  }

  async function remove() {
    if (!confirm(`Delete user "${user.username}"?`)) return
    setBusy(true)
    try {
      await api.admin.deleteUser(user.id)
      onSaved()
    } catch (err) {
      setError(err.message || 'Could not delete this user.')
      setBusy(false)
    }
  }

  return (
    <Modal
      title={isEdit ? `Edit ${user.username}` : 'Add user'}
      onClose={onClose}
      width={460}
      footer={
        <>
          {isEdit && (
            <button onClick={remove} disabled={busy} className="sans" style={delStyle}>
              Delete
            </button>
          )}
          <button onClick={onClose} disabled={busy} className="pill">
            Cancel
          </button>
          <button onClick={save} disabled={busy} className="btn btn-primary btn-sq">
            {busy ? 'Saving…' : 'Save'}
          </button>
        </>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {error && <p className="sans" style={{ margin: 0, color: '#d98b84', fontSize: '0.85rem' }}>{error}</p>}
        <label>
          <span className="field-label">Username</span>
          <input type="text" value={form.username} onChange={set('username')} className="input" autoComplete="off" />
        </label>
        <label>
          <span className="field-label">
            {isEdit ? 'Reset password (leave blank to keep)' : 'Password'}
          </span>
          <input type="password" value={form.password} onChange={set('password')} className="input" autoComplete="new-password" />
          {isEdit && (
            <span className="sans dim" style={{ display: 'block', marginTop: 6, fontSize: '0.76rem' }}>
              Setting a new password here is the supported reset for a player who is locked out. It logs
              their other sessions out.
            </span>
          )}
        </label>
        <label>
          <span className="field-label">Email (optional)</span>
          <input type="email" value={form.email} onChange={set('email')} className="input" autoComplete="off" placeholder="player@example.com" />
        </label>
        <div style={{ display: 'flex', gap: 12 }}>
          <label style={{ flex: 1 }}>
            <span className="field-label">Role</span>
            <select value={form.role} onChange={set('role')} className="select">
              <option value="admin">admin</option>
              <option value="editor">editor</option>
              <option value="moderator">moderator</option>
              <option value="player">player</option>
            </select>
          </label>
          <label style={{ flex: 1 }}>
            <span className="field-label">Status</span>
            <select value={form.status} onChange={set('status')} className="select">
              <option value="active">active</option>
              <option value="disabled">disabled</option>
              <option value="banned">banned</option>
              <option value="pending">pending</option>
            </select>
          </label>
        </div>
      </div>
    </Modal>
  )
}

const delStyle = {
  border: '1px solid #6e3b38',
  borderRadius: 999,
  padding: '7px 16px',
  background: 'rgba(110,59,56,0.18)',
  color: '#d98b84',
  fontSize: '0.86rem',
  cursor: 'pointer',
  marginRight: 'auto',
}
