// frontend/src/modals/crm/customers/OrderModal.jsx
// Edit an existing order's basic details (number, title, status, notes)

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 api from '@/lib/api'

const ORDER_STATUS_OPTIONS = [
  { value: 'negotiating',                    label: 'Negotiating'               },
  { value: 'awaiting_quotation',             label: 'Awaiting Quotation'        },
  { value: 'awaiting_customer_confirmation', label: 'Awaiting Confirmation'     },
  { value: 'awaiting_fulfilment',            label: 'Accepted - Waiting'        },
  { value: 'awaiting_payment',               label: 'Awaiting Payment'          },
  { value: 'manufacturing',                  label: 'Manufacturing'             },
  { value: 'shipped',                        label: 'Shipped'                   },
  { value: 'installed',                      label: 'Installed'                 },
  { value: 'declined',                       label: 'Declined'                  },
  { value: 'complete',                       label: 'Complete'                  },
]

export default function OrderModal({ open, customerId, order, onClose, onSaved, user }) {
  const { toast } = useToast()
  const [form, setForm] = useState({ order_number: '', title: '', status: 'negotiating', notes: '' })
  const [saving, setSaving] = useState(false)

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

  useEffect(() => {
    if (!open || !order) return
    setForm({
      order_number: order.order_number || '',
      title: order.title || '',
      status: order.status || 'negotiating',
      notes: order.notes || '',
    })
  }, [open, order])

  const handleSave = async () => {
    setSaving(true)
    try {
      await api.patch(`/crm/customers/${customerId}/orders/${order.id}`, {
        order_number: form.order_number || null,
        title: form.title || null,
        status: form.status,
        status_updated_date: new Date().toISOString(),
        status_updated_by: user?.display_name || user?.name || 'Staff',
        notes: form.notes || null,
      })
      toast.success('Saved', 'Order updated successfully.')
      onSaved?.()
      onClose()
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to save order.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Edit Order"
      size="md"
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" loading={saving} onClick={handleSave}>Save Changes</Button>
        </>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
          <FormField label="Order Number" name="order_number" type="text" value={form.order_number} onChange={e => set('order_number', e.target.value)} placeholder="e.g. ORD-2026-001" />
          <FormField label="Title" name="title" type="text" value={form.title} onChange={e => set('title', e.target.value)} placeholder="Order title…" />
          <div style={{ gridColumn: '1 / -1' }}>
            <FormField label="Status" name="status" type="select" value={form.status} onChange={e => set('status', e.target.value)}>
              {ORDER_STATUS_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            </FormField>
          </div>
          <div style={{ gridColumn: '1 / -1' }}>
            <FormField label="Notes" name="notes" type="textarea" value={form.notes} onChange={e => set('notes', e.target.value)} placeholder="Internal notes…" />
          </div>
        </div>
      </div>
    </Modal>
  )
}
