// frontend/src/modals/crm/EditCommsEntryModal.jsx
// Edit a manually-logged comms entry (type, direction, date/time, subject, body, logged_by).
// System-logged entries (email, etc.) are rejected with a friendly error.

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'

const SYSTEM_LOGGED_TYPES = ['email']

const TYPE_OPTIONS = [
  { value: 'email',     label: 'Email' },
  { 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' },
]

export default function EditCommsEntryModal({ open, entry, onClose, onSaved }) {
  const { toast } = useToast()

  const [form, setForm]             = useState({})
  const [saving, setSaving]         = useState(false)
  const [staffList, setStaffList]   = useState([])
  const [staffLoading, setStaffLoading] = useState(false)
  const isSystemEntry = entry && SYSTEM_LOGGED_TYPES.includes(entry.type) && entry.logged_by?.toLowerCase() === 'system'

  useEffect(() => {
    if (entry) {
      setForm({
        type:        entry.type        || 'note',
        direction:   entry.direction   || 'inbound',
        occurred_at: entry.occurred_at || '',
        subject:     entry.subject     || '',
        body:        entry.body        || '',
        logged_by:   entry.logged_by   || '',
      })
    }
  }, [entry])

  // Fetch staff list when modal opens
  useEffect(() => {
    if (!open || isSystemEntry) return
    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 {
      const payload = {
        type:      form.type,
        direction: form.direction,
        subject:   form.subject   || null,
        body:      form.body      || null,
        logged_by: form.logged_by || null,
      }
      if (form.occurred_at) payload.occurred_at = form.occurred_at
      await api.put(`/crm/comms/${entry.id}`, payload)
      toast.success('Entry updated', 'The communication entry was saved successfully.')
      onSaved?.()
      onClose()
    } catch (err) {
      toast.danger('Save failed', err.message || 'Could not update entry.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Edit communication entry"
      size="md"
      footer={
        isSystemEntry ? (
          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button variant="secondary" size="md" onClick={onClose}>Close</Button>
          </div>
        ) : (
          <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}>Save changes</Button>
          </div>
        )
      }
    >
      {isSystemEntry ? (
        /* ── System-entry error state ── */
        <div style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          gap: 'var(--space-4)', padding: 'var(--space-6) 0',
          textAlign: 'center',
        }}>
          <div style={{
            width: 56, height: 56,
            borderRadius: 'var(--radius-full)',
            backgroundColor: 'var(--color-warning-bg)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="var(--color-warning)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
              <line x1="12" y1="9" x2="12" y2="13"/>
              <line x1="12" y1="17" x2="12.01" y2="17"/>
            </svg>
          </div>
          <div>
            <p style={{ margin: '0 0 var(--space-2)', fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
              System-logged entry
            </p>
            <p style={{ margin: 0, fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', maxWidth: 340 }}>
              This entry was logged automatically by the system and cannot be edited. Only manually-created entries can be modified.
            </p>
          </div>
        </div>
      ) : (
        /* ── Edit form ── */
        <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"
          />

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

        </div>
      )}
    </Modal>
  )
}
