// frontend/src/modals/crm/customers/OrderStatusModal.jsx
// Update an order's status — archives current status as timeline event, sets new one

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 StatusBadge from '@/components/ui/StatusBadge'
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'              },
]

const STATUS_DEFAULT_NOTES = {
  negotiating:                    'Just started Negotiating with the customer on a possible new order',
  awaiting_quotation:             'We agreed on what the customer needs, and currently drafting a Quote for them',
  awaiting_customer_confirmation: 'The Quotation has been sent to the Customer. Awaiting their Confirmation',
  awaiting_fulfilment:            'Customer has accepted the Quotation, and no further action is needed from them. First Chance possible we are going to build their device',
  awaiting_payment:               'Customer has accepted the Quotation, but a payment/advance is due before we proceed',
  manufacturing:                  'We have begun manufacturing the Customer\'s Device',
  shipped:                        'The order has been Shipped ! Awaiting Customer Feedback',
  installed:                      'Customer has informed us that the device has been successfully Installed !',
  declined:                       'Customer sadly declined our offer',
  complete:                       'Customer has successfully installed, and operated their product. No further action needed ! The order is complete !',
}

const STATUS_TO_TIMELINE_TYPE = {
  negotiating:                    'negotiations_started',
  awaiting_quotation:             'quote_request',
  awaiting_customer_confirmation: 'quote_sent',
  awaiting_fulfilment:            'quote_accepted',
  awaiting_payment:               'invoice_sent',
  manufacturing:                  'mfg_started',
  shipped:                        'order_shipped',
  installed:                      'installed',
  declined:                       'note',
  complete:                       'payment_received',
}

const ORDER_STATUS_VARIANT = {
  negotiating: 'neutral', awaiting_quotation: 'warning',
  awaiting_customer_confirmation: 'info', awaiting_fulfilment: 'info',
  awaiting_payment: 'warning', manufacturing: 'warning',
  shipped: 'info', installed: 'success', declined: 'danger', complete: 'success',
}

export default function OrderStatusModal({ open, customerId, order, onClose, onSaved, user }) {
  const { toast } = useToast()
  const [form, setForm] = useState({ newStatus: 'negotiating', title: '', note: '', datetime: new Date().toISOString() })
  const [saving, setSaving] = useState(false)

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

  useEffect(() => {
    if (!open || !order) return
    const next = order.status || 'negotiating'
    setForm({
      newStatus: next,
      title: order.title || '',
      note: STATUS_DEFAULT_NOTES[next] || '',
      datetime: new Date().toISOString(),
    })
  }, [open, order])

  const handleStatusChange = (newStatus) => {
    setForm(f => ({ ...f, newStatus, note: STATUS_DEFAULT_NOTES[newStatus] || '' }))
  }

  const handleSave = async () => {
    setSaving(true)
    try {
      // Archive current status as timeline event (if not already archived)
      const existingMatch = (order.timeline || []).some(
        e => e.archived_status === order.status && e.date === (order.status_updated_date || order.created_at)
      )
      if (!existingMatch) {
        const tlType = STATUS_TO_TIMELINE_TYPE[order.status] || 'note'
        await api.post(`/crm/customers/${customerId}/orders/${order.id}/timeline`, {
          type: tlType,
          note: order.notes || '',
          date: order.status_updated_date || order.created_at || new Date().toISOString(),
          updated_by: order.status_updated_by || order.created_by || 'System',
          archived_status: order.status,
        })
      }

      await api.patch(`/crm/customers/${customerId}/orders/${order.id}`, {
        status: form.newStatus,
        title: form.title || order.title || null,
        status_updated_date: new Date(form.datetime).toISOString(),
        status_updated_by: user?.display_name || user?.name || 'Staff',
        notes: form.note,
      })

      toast.success('Status updated', `Order moved to "${ORDER_STATUS_OPTIONS.find(o => o.value === form.newStatus)?.label}".`)
      onSaved?.()
      onClose()
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to update status.')
    } finally {
      setSaving(false)
    }
  }

  if (!order) return null

  const currentVariant = ORDER_STATUS_VARIANT[order.status] || 'neutral'
  const nextVariant = ORDER_STATUS_VARIANT[form.newStatus] || 'neutral'

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Update Order Status"
      size="md"
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" loading={saving} onClick={handleSave}>Update Status</Button>
        </>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        {/* Current → New status indicator */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: 'var(--space-3)',
          padding: 'var(--space-3) var(--space-4)',
          backgroundColor: 'var(--color-bg-elevated)',
          borderRadius: 'var(--radius-lg)',
          border: '1px solid var(--color-border)',
        }}>
          <StatusBadge variant={currentVariant}>
            {ORDER_STATUS_OPTIONS.find(o => o.value === order.status)?.label || order.status}
          </StatusBadge>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ color: 'var(--color-text-muted)', flexShrink: 0 }}>
            <path d="M5 12h14M13 6l6 6-6 6" />
          </svg>
          <StatusBadge variant={nextVariant}>
            {ORDER_STATUS_OPTIONS.find(o => o.value === form.newStatus)?.label || form.newStatus}
          </StatusBadge>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
          <FormField label="New Status" name="newStatus" type="select" value={form.newStatus} onChange={e => handleStatusChange(e.target.value)}>
            {ORDER_STATUS_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </FormField>
          <DateTimePicker label="Date & Time" name="datetime" value={form.datetime} onChange={iso => set('datetime', iso)} />
          <div style={{ gridColumn: '1 / -1' }}>
            <FormField label="Order Title" name="title" type="text" value={form.title} onChange={e => set('title', e.target.value)} placeholder="Update title (optional)…" />
          </div>
          <div style={{ gridColumn: '1 / -1' }}>
            <FormField label="Status Note" name="note" type="textarea" value={form.note} onChange={e => set('note', e.target.value)} placeholder="Note about this status change…" />
          </div>
        </div>

        <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', margin: 0 }}>
          The current status will be archived as a timeline event before being replaced.
        </p>
      </div>
    </Modal>
  )
}
