// frontend/src/modals/devices/EditMiscModal.jsx
import { useState } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
import api from '@/lib/api'

const toBool = (v) => v === 'true' || v === true

export default function EditMiscModal({ open, onClose, onSaved, device, attr, id }) {
  const [eventsOn, setEventsOn] = useState(String(device?.events_on ?? false))
  const [locale, setLocale] = useState(attr?.deviceLocale || 'all')
  const [wsUrl, setWsUrl] = useState(device?.websocket_url || '')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  const handleSave = async () => {
    setSaving(true)
    setError('')
    try {
      await api.put(`/devices/${id}`, {
        events_on: toBool(eventsOn),
        device_attributes: { deviceLocale: locale },
        websocket_url: wsUrl,
      })
      await onSaved()
      onClose()
    } catch (err) {
      setError(err.message || 'Failed to save.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Edit Misc Settings"
      size="sm"
      footer={
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" loading={saving} onClick={handleSave}>Save</Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <FormField
          label="Automated Events"
          name="eventsOn"
          type="select"
          value={eventsOn}
          onChange={(e) => setEventsOn(e.target.value)}
        >
          <option value="true">Enabled</option>
          <option value="false">Disabled</option>
        </FormField>
        <FormField
          label="Church Type"
          name="locale"
          type="select"
          value={locale}
          onChange={(e) => setLocale(e.target.value)}
        >
          <option value="all">All (Global)</option>
          <option value="orthodox">Orthodox</option>
          <option value="catholic">Catholic</option>
        </FormField>
        <FormField
          label="WebSocket URL"
          name="wsUrl"
          type="url"
          value={wsUrl}
          onChange={(e) => setWsUrl(e.target.value)}
          placeholder="ws://..."
        />
        {error && (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
        )}
      </div>
    </Modal>
  )
}
