// frontend/src/modals/devices/EditAttributesModal.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 EditAttributesModal({ open, onClose, onSaved, attr, id }) {
  const [bellGuardOn, setBellGuardOn] = useState(String(attr?.bellGuardOn ?? false))
  const [bellGuardSafetyOn, setBellGuardSafetyOn] = useState(String(attr?.bellGuardSafetyOn ?? false))
  const [warningsOn, setWarningsOn] = useState(String(attr?.warningsOn ?? false))
  const [hasBells, setHasBells] = useState(String(attr?.hasBells ?? false))
  const [hasClock, setHasClock] = useState(String(attr?.hasClock ?? false))
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  const handleSave = async () => {
    setSaving(true)
    setError('')
    try {
      await api.put(`/devices/${id}`, {
        device_attributes: {
          bellGuardOn: toBool(bellGuardOn),
          warningsOn: toBool(warningsOn),
          bellGuardSafetyOn: toBool(bellGuardSafetyOn),
          hasBells: toBool(hasBells),
          hasClock: toBool(hasClock),
        },
      })
      await onSaved()
      onClose()
    } catch (err) {
      setError(err.message || 'Failed to save.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Edit Basic Attributes"
      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)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
          <FormField
            label="Bell Guard"
            name="bellGuardOn"
            type="select"
            value={bellGuardOn}
            onChange={(e) => setBellGuardOn(e.target.value)}
          >
            <option value="true">Active</option>
            <option value="false">Disabled</option>
          </FormField>
          <FormField
            label="Bell Guard Safety"
            name="bellGuardSafetyOn"
            type="select"
            value={bellGuardSafetyOn}
            onChange={(e) => setBellGuardSafetyOn(e.target.value)}
          >
            <option value="true">Armed</option>
            <option value="false">Disarmed</option>
          </FormField>
        </div>
        <FormField
          label="Warnings"
          name="warningsOn"
          type="select"
          value={warningsOn}
          onChange={(e) => setWarningsOn(e.target.value)}
        >
          <option value="true">Active</option>
          <option value="false">Disabled</option>
        </FormField>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
          <FormField
            label="Bells Mechanism"
            name="hasBells"
            type="select"
            value={hasBells}
            onChange={(e) => setHasBells(e.target.value)}
          >
            <option value="true">Enabled</option>
            <option value="false">Disabled</option>
          </FormField>
          <FormField
            label="Clock Output"
            name="hasClock"
            type="select"
            value={hasClock}
            onChange={(e) => setHasClock(e.target.value)}
          >
            <option value="true">Enabled</option>
            <option value="false">Disabled</option>
          </FormField>
        </div>
        <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
          Connected bells: {Number.isFinite(attr?.totalBells) ? attr.totalBells : '—'} — managed via Bell Mechanisms tab.
        </p>
        {error && (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
        )}
      </div>
    </Modal>
  )
}
