// frontend/src/modals/bellcloud/devices/DeviceNoteModal.jsx
// Create or edit a simple device note (Firestore device notes — not the global /notes system).

import { useState, useEffect } from 'react'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import { useToast } from '@/components/ui/Toast'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'

export default function DeviceNoteModal({ open, deviceId, note, onClose, onSaved }) {
  const { user }  = useAuth()
  const { toast } = useToast()
  const isEdit    = !!note

  const [content, setContent] = useState('')
  const [saving,  setSaving]  = useState(false)
  const [error,   setError]   = useState('')

  useEffect(() => {
    if (!open) return
    setContent(note?.content || '')
    setError('')
  }, [open, note])

  const save = async () => {
    if (!content.trim()) { setError('Note content is required.'); return }
    setSaving(true)
    setError('')
    try {
      if (isEdit) {
        await api.put(`/devices/${deviceId}/notes/${note.id}`, { content: content.trim() })
        toast.success('Updated', 'Note updated.')
      } else {
        await api.post(`/devices/${deviceId}/notes`, {
          content:    content.trim(),
          created_by: user?.name || user?.email || '',
        })
        toast.success('Created', 'Note added.')
      }
      onSaved()
    } catch (err) {
      setError(err.message || 'Save failed.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={isEdit ? 'Edit Note' : 'Add Note'}
      size="sm"
      footer={
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
          <Button variant="secondary" size="md" onClick={onClose}>Cancel</Button>
          <Button variant="primary" size="md" onClick={save} loading={saving}>
            {isEdit ? 'Save Changes' : 'Add Note'}
          </Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        {error && (
          <div style={{
            padding: 'var(--space-2) var(--space-3)',
            backgroundColor: 'var(--color-danger-bg)',
            border: '1px solid var(--color-danger)',
            borderRadius: 'var(--radius-md)',
            color: 'var(--color-danger)',
            fontSize: 'var(--font-size-sm)',
          }}>
            {error}
          </div>
        )}
        <FormField
          label="Note"
          name="content"
          type="textarea"
          value={content}
          onChange={e => setContent(e.target.value)}
          placeholder="Record an observation, update, or reminder about this device…"
          rows={5}
        />
      </div>
    </Modal>
  )
}
