// frontend/src/pages/crm/orders/OrderDetail.jsx

import { useState, useEffect, useCallback } from 'react'
import { useParams, useNavigate, Link } from 'react-router-dom'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import PageHeader from '@/components/ui/PageHeader'
import Card from '@/components/ui/Card'
import StatusBadge from '@/components/ui/StatusBadge'
import Button from '@/components/ui/Button'
import Spinner from '@/components/ui/Spinner'
import Breadcrumbs from '@/components/ui/Breadcrumbs'
import FormField from '@/components/ui/FormField'
import Modal from '@/components/ui/Modal'
import ConfirmDialog from '@/components/ui/ConfirmDialog'
import { useToast } from '@/components/ui/Toast'
import { fmtDateMedium, fmtDateTime as fmtDateTimeFmt, toDatetimeLocal, nowLocal } from '@/lib/formatters'

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

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

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

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

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 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',
  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. The order is complete!',
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function fmtDate(iso) { return fmtDateMedium(iso) }
function fmtDateTime(iso) { return fmtDateTimeFmt(iso) }

// ---------------------------------------------------------------------------
// Timeline event row
// ---------------------------------------------------------------------------
function TimelineEvent({ event, canEdit, onEdit, onDelete }) {
  const [hovered, setHovered] = useState(false)
  const typeLabel = TIMELINE_TYPE_LABELS[event.type] || event.type

  // Choose icon color based on type
  const dotColor = {
    negotiations_started: 'var(--color-info)',
    quote_sent: 'var(--color-warning)',
    quote_accepted: 'var(--color-success)',
    quote_declined: 'var(--color-danger)',
    payment_received: 'var(--color-success)',
    order_shipped: 'var(--color-primary)',
    installed: 'var(--color-success)',
    mfg_started: 'var(--color-primary)',
    mfg_complete: 'var(--color-success)',
  }[event.type] || 'var(--color-text-muted)'

  return (
    <div
      style={{ display: 'flex', gap: 'var(--space-3)', paddingBottom: 'var(--space-3)', position: 'relative' }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      {/* Timeline spine */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0, width: '16px' }}>
        <div style={{
          width: '8px', height: '8px',
          borderRadius: 'var(--radius-full)',
          backgroundColor: dotColor,
          marginTop: '4px',
          flexShrink: 0,
          boxShadow: `0 0 6px ${dotColor}`,
        }} />
        <div style={{ flex: 1, width: '1px', backgroundColor: 'var(--color-border)', marginTop: '4px' }} />
      </div>

      {/* Content */}
      <div style={{ flex: 1, paddingBottom: 'var(--space-1)' }}>
        <div style={{
          fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)',
          color: 'var(--color-text-primary)',
        }}>
          {typeLabel}
        </div>
        {event.note && (
          <div style={{
            fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)',
            marginTop: 'var(--space-1)', whiteSpace: 'pre-wrap', lineHeight: '1.5',
          }}>
            {event.note}
          </div>
        )}
        <div style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginTop: 'var(--space-1)' }}>
          {fmtDateTime(event.date)}
          {event.updated_by && <span style={{ opacity: 0.6 }}> · {event.updated_by}</span>}
        </div>
      </div>

      {/* Hover actions */}
      {canEdit && hovered && (
        <div style={{ display: 'flex', gap: 'var(--space-2)', flexShrink: 0, alignSelf: 'flex-start' }}>
          <Button variant="ghost" size="sm" onClick={() => onEdit(event)}>Edit</Button>
          <Button variant="danger" size="sm" onClick={() => onDelete(event)}>Delete</Button>
        </div>
      )}
    </div>
  )
}

// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------
export default function OrderDetail() {
  const { id } = useParams()
  const navigate = useNavigate()
  const { user, hasPermission } = useAuth()
  const { toast } = useToast()

  const [order, setOrder] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  // Modal state
  const [showEditModal, setShowEditModal] = useState(false)
  const [showStatusModal, setShowStatusModal] = useState(false)
  const [showTimelineModal, setShowTimelineModal] = useState(false)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [editingEvent, setEditingEvent] = useState(null)
  const [deletingEvent, setDeletingEvent] = useState(null)

  // Edit form
  const [editForm, setEditForm] = useState({ order_number: '', title: '', status: 'negotiating', notes: '' })
  const [savingEdit, setSavingEdit] = useState(false)

  // Status update form
  const [statusForm, setStatusForm] = useState({ newStatus: 'negotiating', title: '', note: '', datetime: nowLocal() })
  const [savingStatus, setSavingStatus] = useState(false)

  // Timeline form
  const [timelineForm, setTimelineForm] = useState({ type: 'note', note: '', date: nowLocal() })
  const [savingTimeline, setSavingTimeline] = useState(false)

  // Delete order
  const [deletingOrder, setDeletingOrder] = useState(false)

  // Delete timeline event
  const [deletingTlEvent, setDeletingTlEvent] = useState(false)

  const canEdit = hasPermission('crm_orders', 'edit')

  const load = useCallback(async () => {
    setLoading(true)
    setError('')
    try {
      const data = await api.get(`/crm/orders/${id}`)
      setOrder(data)
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }, [id])

  useEffect(() => { load() }, [load])

  // Sync edit form when order loads
  useEffect(() => {
    if (order) {
      setEditForm({
        order_number: order.order_number || '',
        title: order.title || '',
        status: order.status || 'negotiating',
        notes: order.notes || '',
      })
      setStatusForm(f => ({ ...f, newStatus: order.status || 'negotiating', title: order.title || '' }))
    }
  }, [order])

  // ---------------------------------------------------------------------------
  // Handlers
  // ---------------------------------------------------------------------------
  const handleSaveEdit = async () => {
    setSavingEdit(true)
    try {
      await api.patch(`/crm/customers/${order.customer_id}/orders/${id}`, {
        order_number: editForm.order_number || null,
        title: editForm.title || null,
        status: editForm.status,
        notes: editForm.notes || null,
      })
      toast.success('Saved', 'Order updated.')
      setShowEditModal(false)
      load()
    } catch (err) {
      toast.danger('Error', err.message)
    } finally {
      setSavingEdit(false)
    }
  }

  const handleUpdateStatus = async () => {
    setSavingStatus(true)
    try {
      // Archive current status as timeline event if not already there
      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/${order.customer_id}/orders/${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/${order.customer_id}/orders/${id}`, {
        status: statusForm.newStatus,
        title: statusForm.title || order.title || null,
        status_updated_date: new Date(statusForm.datetime).toISOString(),
        status_updated_by: user?.name || 'Staff',
        notes: statusForm.note,
      })
      toast.success('Status updated', `Order moved to ${ORDER_STATUS_LABELS[statusForm.newStatus]}.`)
      setShowStatusModal(false)
      load()
    } catch (err) {
      toast.danger('Error', err.message)
    } finally {
      setSavingStatus(false)
    }
  }

  const handleAddTimeline = async () => {
    if (!timelineForm.type) return
    setSavingTimeline(true)
    try {
      const payload = {
        ...timelineForm,
        date: timelineForm.date ? new Date(timelineForm.date).toISOString() : new Date().toISOString(),
        updated_by: user?.name || 'Staff',
      }
      if (editingEvent) {
        // Find index in original timeline
        const origIdx = (order.timeline || []).findIndex(
          e => e.date === editingEvent.date && e.note === editingEvent.note && e.type === editingEvent.type
        )
        await api.patch(`/crm/customers/${order.customer_id}/orders/${id}/timeline/${origIdx}`, {
          type: timelineForm.type,
          note: timelineForm.note,
          date: new Date(timelineForm.date).toISOString(),
        })
        toast.success('Updated', 'Timeline event updated.')
      } else {
        await api.post(`/crm/customers/${order.customer_id}/orders/${id}/timeline`, payload)
        toast.success('Added', 'Timeline event added.')
      }
      setTimelineForm({ type: 'note', note: '', date: nowLocal() })
      setEditingEvent(null)
      setShowTimelineModal(false)
      load()
    } catch (err) {
      toast.danger('Error', err.message)
    } finally {
      setSavingTimeline(false)
    }
  }

  const handleDeleteTimelineEvent = async () => {
    if (!deletingEvent) return
    setDeletingTlEvent(true)
    try {
      const origIdx = (order.timeline || []).findIndex(
        e => e.date === deletingEvent.date && e.note === deletingEvent.note && e.type === deletingEvent.type
      )
      await api.delete(`/crm/customers/${order.customer_id}/orders/${id}/timeline/${origIdx}`)
      toast.success('Deleted', 'Timeline event removed.')
      setDeletingEvent(null)
      load()
    } catch (err) {
      toast.danger('Error', err.message)
    } finally {
      setDeletingTlEvent(false)
    }
  }

  const handleDeleteOrder = async () => {
    setDeletingOrder(true)
    try {
      await api.delete(`/crm/customers/${order.customer_id}/orders/${id}`)
      toast.success('Deleted', 'Order deleted.')
      navigate('/crm/orders')
    } catch (err) {
      toast.danger('Error', err.message)
      setDeletingOrder(false)
    }
  }

  const openEditTimeline = (event) => {
    setEditingEvent(event)
    setTimelineForm({
      type: event.type || 'note',
      note: event.note || '',
      date: event.date ? toDatetimeLocal(event.date) : nowLocal(),
    })
    setShowTimelineModal(true)
  }

  const openDeleteTimeline = (event) => {
    setDeletingEvent(event)
  }

  // ---------------------------------------------------------------------------
  // Render states
  // ---------------------------------------------------------------------------
  if (loading) {
    return (
      <div className="page-wrapper">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'var(--space-16)' }}>
          <Spinner size="md" />
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="page-wrapper">
        <PageHeader title="Order" />
        <div style={{ padding: 'var(--space-4)', borderRadius: 'var(--radius-md)', backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)', color: 'var(--color-danger)', fontSize: 'var(--font-size-sm)' }}>
          {error}
        </div>
      </div>
    )
  }

  if (!order) return null

  const timeline = [...(order.timeline || [])].sort((a, b) => (b.date || '').localeCompare(a.date || ''))

  const statusVariant = ORDER_STATUS_VARIANT[order.status] || 'neutral'
  const statusLabel = ORDER_STATUS_LABELS[order.status] || order.status || '—'

  return (
    <>
      <div className="page-wrapper">
        <Breadcrumbs items={[
          { label: 'Orders', href: '/crm/orders' },
          { label: order.order_number || order.title || `Order ${id}` },
        ]} />

        <PageHeader
          title={order.order_number ? `Order ${order.order_number}` : (order.title || 'Order Detail')}
          subtitle={order.customer_name || undefined}
        >
          {canEdit && (
            <div style={{ display: 'flex', gap: 'var(--space-2)' }}>
              <Button variant="secondary" onClick={() => setShowStatusModal(true)}>Update Status</Button>
              <Button variant="ghost" onClick={() => setShowEditModal(true)}>Edit</Button>
              <Button variant="danger" onClick={() => setShowDeleteConfirm(true)}>Delete</Button>
            </div>
          )}
        </PageHeader>

        {/* Main two-column layout */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 'var(--space-6)', alignItems: 'start' }} className="order-detail-grid">

          {/* Left: timeline */}
          <Card title="Timeline" subtitle="Order history and status changes" padding={false}>
            <div style={{ padding: 'var(--space-4)' }}>
              {/* Add event button */}
              {canEdit && (
                <div style={{ marginBottom: 'var(--space-4)' }}>
                  <Button
                    variant="secondary"
                    size="sm"
                    onClick={() => {
                      setEditingEvent(null)
                      setTimelineForm({ type: 'note', note: '', date: nowLocal() })
                      setShowTimelineModal(true)
                    }}
                  >
                    + Add Event
                  </Button>
                </div>
              )}

              {timeline.length === 0 ? (
                <div style={{ textAlign: 'center', padding: 'var(--space-8)', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)', fontStyle: 'italic' }}>
                  No timeline events yet.
                </div>
              ) : (
                <div>
                  {timeline.map((ev, i) => (
                    <TimelineEvent
                      key={`${ev.date}-${ev.type}-${i}`}
                      event={ev}
                      canEdit={canEdit}
                      onEdit={openEditTimeline}
                      onDelete={openDeleteTimeline}
                    />
                  ))}
                </div>
              )}
            </div>
          </Card>

          {/* Right: details */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
            {/* Status card */}
            <Card>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
                <div>
                  <div style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-1)' }}>Status</div>
                  <StatusBadge variant={statusVariant}>{statusLabel}</StatusBadge>
                </div>
                {order.status_updated_date && (
                  <div>
                    <div style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-1)' }}>Updated</div>
                    <div style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
                      {fmtDate(order.status_updated_date)}
                      {order.status_updated_by && <span style={{ color: 'var(--color-text-muted)' }}> by {order.status_updated_by}</span>}
                    </div>
                  </div>
                )}
              </div>
            </Card>

            {/* Info card */}
            <Card title="Order Info">
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
                {[
                  { label: 'Order Number', value: order.order_number, mono: true },
                  { label: 'Title', value: order.title },
                  { label: 'Customer', value: order.customer_name ? (
                    <Link
                      to={`/crm/customers/${order.customer_id}`}
                      style={{ color: 'var(--color-text-accent)', textDecoration: 'none' }}
                    >
                      {order.customer_name}
                    </Link>
                  ) : null },
                  { label: 'Created', value: fmtDate(order.created_at) },
                  { label: 'Created by', value: order.created_by },
                ].map(row => (
                  <div key={row.label}>
                    <div style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: '2px' }}>
                      {row.label}
                    </div>
                    <div style={{
                      fontSize: 'var(--font-size-sm)',
                      color: 'var(--color-text-secondary)',
                      fontFamily: row.mono ? 'var(--font-family-mono)' : 'inherit',
                    }}>
                      {row.value || <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>—</span>}
                    </div>
                  </div>
                ))}

                {order.notes && (
                  <div>
                    <div style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: '2px' }}>Notes</div>
                    <div style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)', whiteSpace: 'pre-wrap', lineHeight: '1.5' }}>
                      {order.notes}
                    </div>
                  </div>
                )}
              </div>
            </Card>

            {/* Timeline count */}
            <div style={{ padding: 'var(--space-3) var(--space-4)', borderRadius: 'var(--radius-lg)', backgroundColor: 'var(--color-bg-surface)', border: '1px solid var(--color-border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>Timeline events</span>
              <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-primary)', fontWeight: 'var(--font-weight-semibold)' }}>
                {timeline.length}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Edit Order Modal */}
      <Modal
        open={showEditModal}
        onClose={() => setShowEditModal(false)}
        title="Edit Order"
        size="md"
        footer={
          <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}>
            <Button variant="ghost" onClick={() => setShowEditModal(false)}>Cancel</Button>
            <Button variant="primary" onClick={handleSaveEdit} loading={savingEdit}>Save Changes</Button>
          </div>
        }
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
          <FormField
            label="Order Number"
            name="order_number"
            type="text"
            value={editForm.order_number}
            onChange={e => setEditForm(f => ({ ...f, order_number: e.target.value }))}
            placeholder="e.g. ORD-2025-001"
          />
          <FormField
            label="Title"
            name="title"
            type="text"
            value={editForm.title}
            onChange={e => setEditForm(f => ({ ...f, title: e.target.value }))}
            placeholder="Short description of the order"
          />
          <FormField
            label="Status"
            name="status"
            type="select"
            value={editForm.status}
            onChange={e => setEditForm(f => ({ ...f, status: e.target.value }))}
          >
            {Object.entries(ORDER_STATUS_LABELS).map(([v, l]) => (
              <option key={v} value={v}>{l}</option>
            ))}
          </FormField>
          <FormField
            label="Notes"
            name="notes"
            type="textarea"
            value={editForm.notes}
            onChange={e => setEditForm(f => ({ ...f, notes: e.target.value }))}
            placeholder="Internal notes about this order…"
            rows={3}
          />
        </div>
      </Modal>

      {/* Update Status Modal */}
      <Modal
        open={showStatusModal}
        onClose={() => setShowStatusModal(false)}
        title="Update Order Status"
        size="md"
        footer={
          <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}>
            <Button variant="ghost" onClick={() => setShowStatusModal(false)}>Cancel</Button>
            <Button variant="primary" onClick={handleUpdateStatus} loading={savingStatus}>Update Status</Button>
          </div>
        }
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
          {/* Info banner */}
          <div style={{ padding: 'var(--space-3)', borderRadius: 'var(--radius-md)', backgroundColor: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
            Current status <strong style={{ color: 'var(--color-text-secondary)' }}>{ORDER_STATUS_LABELS[order?.status] || order?.status}</strong> will be archived as a timeline event.
          </div>
          <FormField
            label="New Status"
            name="newStatus"
            type="select"
            value={statusForm.newStatus}
            onChange={e => setStatusForm(f => ({ ...f, newStatus: e.target.value, note: STATUS_DEFAULT_NOTES[e.target.value] || '' }))}
          >
            {Object.entries(ORDER_STATUS_LABELS).map(([v, l]) => (
              <option key={v} value={v}>{l}</option>
            ))}
          </FormField>
          <FormField
            label="Order Title (optional)"
            name="statusTitle"
            type="text"
            value={statusForm.title}
            onChange={e => setStatusForm(f => ({ ...f, title: e.target.value }))}
          />
          <FormField
            label="Date & Time"
            name="datetime"
            type="text"
            value={statusForm.datetime}
            onChange={e => setStatusForm(f => ({ ...f, datetime: e.target.value }))}
            hint="Format: YYYY-MM-DDTHH:MM"
          />
          <FormField
            label="Note"
            name="statusNote"
            type="textarea"
            value={statusForm.note}
            onChange={e => setStatusForm(f => ({ ...f, note: e.target.value }))}
            placeholder="Optional note about this status change…"
            rows={3}
          />
        </div>
      </Modal>

      {/* Timeline Event Modal */}
      <Modal
        open={showTimelineModal}
        onClose={() => { setShowTimelineModal(false); setEditingEvent(null) }}
        title={editingEvent ? 'Edit Timeline Event' : 'Add Timeline Event'}
        size="md"
        footer={
          <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}>
            <Button variant="ghost" onClick={() => { setShowTimelineModal(false); setEditingEvent(null) }}>Cancel</Button>
            <Button variant="primary" onClick={handleAddTimeline} loading={savingTimeline}>
              {editingEvent ? 'Save Changes' : 'Add Event'}
            </Button>
          </div>
        }
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
          <FormField
            label="Type"
            name="type"
            type="select"
            value={timelineForm.type}
            onChange={e => setTimelineForm(f => ({ ...f, type: e.target.value }))}
          >
            {Object.entries(TIMELINE_TYPE_LABELS).map(([v, l]) => (
              <option key={v} value={v}>{l}</option>
            ))}
          </FormField>
          <FormField
            label="Date & Time"
            name="date"
            type="text"
            value={timelineForm.date}
            onChange={e => setTimelineForm(f => ({ ...f, date: e.target.value }))}
            hint="Format: YYYY-MM-DDTHH:MM"
          />
          <FormField
            label="Note"
            name="note"
            type="textarea"
            value={timelineForm.note}
            onChange={e => setTimelineForm(f => ({ ...f, note: e.target.value }))}
            placeholder="Description or notes for this event…"
            rows={3}
          />
        </div>
      </Modal>

      {/* Confirm delete timeline event */}
      {deletingEvent && (
        <ConfirmDialog
          open={!!deletingEvent}
          onClose={() => setDeletingEvent(null)}
          onConfirm={handleDeleteTimelineEvent}
          loading={deletingTlEvent}
          variant="danger"
          title="Delete Timeline Event"
          message={`Delete the "${TIMELINE_TYPE_LABELS[deletingEvent.type] || deletingEvent.type}" event? This cannot be undone.`}
        />
      )}

      {/* Confirm delete order */}
      <ConfirmDialog
        open={showDeleteConfirm}
        onClose={() => setShowDeleteConfirm(false)}
        onConfirm={handleDeleteOrder}
        loading={deletingOrder}
        variant="danger"
        title="Delete Order"
        message="Are you sure you want to delete this order? All timeline events will be lost. This cannot be undone."
      />

      <style>{`
        @media (max-width: 900px) {
          .order-detail-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </>
  )
}
