// frontend/src/modals/crm/customers/NoteModal.jsx
// Add or edit a staff note on a customer record

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

// onClose()        — cancel / close without saving
// onSaved(updated) — save succeeded, pass the updated customer object
export default function NoteModal({ open, customer, editIndex, initialData, onClose, onSaved }) {
  const toast      = useToast()
  const { user }   = useAuth()
  const [text, setText]     = useState('')
  const [saving, setSaving] = useState(false)

  const isEdit = editIndex != null

  useEffect(() => {
    if (!open) return
    setText(isEdit ? (initialData?.text || initialData?.content || initialData?.body || '') : '')
  }, [open, isEdit, initialData])

  const handleSave = async () => {
    if (!text.trim()) return
    setSaving(true)
    try {
      const existingNotes = customer.notes || []
      const by = user?.display_name || user?.name || 'Staff'
      const now = new Date().toISOString()

      let updatedNotes
      if (isEdit) {
        updatedNotes = existingNotes.map((n, i) =>
          i === editIndex ? { ...n, text: text.trim(), by, at: now } : n
        )
      } else {
        updatedNotes = [...existingNotes, { text: text.trim(), by, at: now }]
      }

      const updated = await api.put(`/crm/customers/${customer.id}`, { notes: updatedNotes })
      toast.success(isEdit ? 'Note updated' : 'Note added', '')
      onSaved(updated)
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to save note.')
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={isEdit ? 'Edit Note' : 'Add Note'}
      footer={
        <>
          <Button variant="ghost" size="md" onClick={() => onClose(null)} disabled={saving}>
            Cancel
          </Button>
          <Button variant="primary" size="md" onClick={handleSave} disabled={saving || !text.trim()}>
            {saving ? 'Saving…' : isEdit ? 'Save Changes' : 'Add Note'}
          </Button>
        </>
      }
    >
      <FormField
        label="Note"
        type="textarea"
        value={text}
        onChange={e => setText(e.target.value)}
        placeholder="Write your note here… (newlines are preserved)"
        rows={6}
        autoFocus
      />
    </Modal>
  )
}
