// frontend/src/modals/crm/LogCommsEntryModal.jsx
// Log a new manual communication entry for a customer.

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

const TYPE_OPTIONS = [
  { value: 'whatsapp',  label: 'WhatsApp' },
  { value: 'call',      label: 'Phone call' },
  { value: 'sms',       label: 'SMS' },
  { value: 'note',      label: 'Note' },
  { value: 'in_person', label: 'In person' },
]

const DIRECTION_OPTIONS = [
  { value: 'inbound',  label: 'Inbound' },
  { value: 'outbound', label: 'Outbound' },
  { value: 'internal', label: 'Internal' },
]

const DEFAULT_FORM = (currentUserName = '') => ({
  type:        'note',
  direction:   'internal',
  occurred_at: new Date().toISOString(),
  subject:     '',
  body:        '',
  logged_by:   currentUserName,
})

export default function LogCommsEntryModal({ open, customerId, onClose, onSaved }) {
  const { toast }               = useToast()
  const { user }                = useAuth()
  const [form, setForm]         = useState(DEFAULT_FORM())
  const [saving, setSaving]     = useState(false)
  const [staffList, setStaffList]   = useState([])
  const [staffLoading, setStaffLoading] = useState(false)

  // Fetch staff list when modal opens
  useEffect(() => {
    if (!open) return
    const currentName = user?.name || ''
    setForm(DEFAULT_FORM(currentName))
    setStaffLoading(true)
    api.get('/staff')
      .then((data) => setStaffList(data.staff || []))
      .catch(() => setStaffList([]))
      .finally(() => setStaffLoading(false))
  }, [open])

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

  const handleSave = async () => {
    setSaving(true)
    try {
      await api.post('/crm/comms', {
        customer_id: customerId,
        type:        form.type,
        direction:   form.direction,
        subject:     form.subject   || null,
        body:        form.body      || null,
        logged_by:   form.logged_by || null,
        occurred_at: form.occurred_at || new Date().toISOString(),
      })
      toast.success('Entry logged', 'Communication entry saved.')
      onSaved?.()
      onClose()
    } catch (err) {
      toast.danger('Save failed', err.message || 'Could not log entry.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Log communication entry"
      size="md"
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-3)', justifyContent: 'flex-end' }}>
          <Button variant="secondary" size="md" onClick={onClose} disabled={saving}>Cancel</Button>
          <Button variant="primary"   size="md" onClick={handleSave} loading={saving}>Log entry</Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>

        {/* Row 1: type + direction */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
          <FormField label="Type" name="type" type="select" value={form.type} onChange={set('type')}>
            {TYPE_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
          </FormField>
          <FormField label="Direction" name="direction" type="select" value={form.direction} onChange={set('direction')}>
            {DIRECTION_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
          </FormField>
        </div>

        {/* Row 2: date/time + logged_by */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
          <DateTimePicker
            label="Date & time"
            name="occurred_at"
            value={form.occurred_at}
            onChange={setIso('occurred_at')}
          />
          {staffList.length > 0 ? (
            <FormField
              label="Logged by"
              name="logged_by"
              type="select"
              value={form.logged_by}
              onChange={set('logged_by')}
            >
              <option value="">— select staff —</option>
              {staffList.map((s) => (
                <option key={s.id} value={s.name}>{s.name}</option>
              ))}
            </FormField>
          ) : (
            <FormField
              label="Logged by"
              name="logged_by"
              type="text"
              value={form.logged_by}
              onChange={set('logged_by')}
              placeholder={staffLoading ? 'Loading…' : 'e.g. John Smith'}
              disabled={staffLoading}
            />
          )}
        </div>

        {/* Subject */}
        <FormField
          label="Subject / title"
          name="subject"
          type="text"
          value={form.subject}
          onChange={set('subject')}
          placeholder="Optional subject or title"
        />

        {/* Notes */}
        <FormField
          label="Notes"
          name="body"
          type="textarea"
          value={form.body}
          onChange={set('body')}
          rows={5}
          placeholder="Message content or notes…"
        />

      </div>
    </Modal>
  )
}
