// frontend/src/modals/crm/customers/TimelineEventModal.jsx
// Add or edit a timeline event on an order

import { useState, useEffect } from 'react'
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 api from '@/lib/api'

const TIMELINE_TYPE_OPTIONS = [
  { value: 'negotiations_started', label: 'Started Negotiations'   },
  { value: 'quote_request',        label: 'Quote Requested'        },
  { value: 'quote_sent',           label: 'Quote Sent'             },
  { value: 'quote_accepted',       label: 'Quote Accepted'         },
  { value: 'quote_declined',       label: 'Quote Declined'         },
  { value: 'mfg_started',          label: 'Manufacturing Started'  },
  { value: 'mfg_complete',         label: 'Manufacturing Complete' },
  { value: 'order_shipped',        label: 'Order Shipped'          },
  { value: 'installed',            label: 'Installed'              },
  { value: 'payment_received',     label: 'Payment Received'       },
  { value: 'invoice_sent',         label: 'Invoice Sent'           },
  { value: 'note',                 label: 'Note'                   },
]

export default function TimelineEventModal({ open, customerId, orderId, editIndex, initialData, onClose, onSaved, user }) {
  const { toast } = useToast()
  const [form, setForm] = useState({ type: 'note', note: '', date: new Date().toISOString() })
  const [saving, setSaving] = useState(false)

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }))

  useEffect(() => {
    if (!open) return
    if (initialData) {
      setForm({
        type: initialData.type || 'note',
        note: initialData.note || '',
        date: initialData.date || new Date().toISOString(),
      })
    } else {
      setForm({ type: 'note', note: '', date: new Date().toISOString() })
    }
  }, [open, initialData])

  const handleSave = async () => {
    if (!form.type) { toast.warning('Required', 'Event type is required.'); return }
    setSaving(true)
    try {
      const payload = {
        type: form.type,
        note: form.note,
        date: form.date ? new Date(form.date).toISOString() : new Date().toISOString(),
        updated_by: user?.display_name || user?.name || 'Staff',
      }
      if (editIndex !== undefined && editIndex !== null) {
        await api.patch(`/crm/customers/${customerId}/orders/${orderId}/timeline/${editIndex}`, payload)
        toast.success('Updated', 'Timeline event updated.')
      } else {
        await api.post(`/crm/customers/${customerId}/orders/${orderId}/timeline`, payload)
        toast.success('Added', 'Timeline event recorded.')
      }
      onSaved?.()
      onClose()
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to save event.')
    } finally {
      setSaving(false)
    }
  }

  const isEditing = editIndex != null

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={isEditing ? 'Edit Timeline Event' : 'Add Timeline Event'}
      size="sm"
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" loading={saving} onClick={handleSave}>
            {isEditing ? 'Update Event' : 'Add Event'}
          </Button>
        </>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <FormField label="Event Type" name="type" type="select" value={form.type} onChange={e => set('type', e.target.value)}>
          {TIMELINE_TYPE_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
        </FormField>
        <DateTimePicker label="Date & Time" name="date" value={form.date} onChange={iso => set('date', iso)} />
        <FormField label="Note" name="note" type="textarea" value={form.note} onChange={e => set('note', e.target.value)} placeholder="Describe what happened…" />
      </div>
    </Modal>
  )
}
