// frontend/src/pages/crm/customers/tabs/OrdersTab.jsx
// List of orders for a customer, each expandable with a timeline

import { useState } from 'react'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import Card from '@/components/ui/Card'
import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
import ConfirmDialog from '@/components/ui/ConfirmDialog'
import { useToast } from '@/components/ui/Toast'
import OrderModal from '@/modals/crm/customers/OrderModal'
import OrderStatusModal from '@/modals/crm/customers/OrderStatusModal'
import TimelineEventModal from '@/modals/crm/customers/TimelineEventModal'
import { InitNegotiationsModal } from '@/modals/crm/QuickEntryModals'
import { fmtDateLong, fmtDateTime as fmtDateTimeCentral } 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: 'neutral', awaiting_quotation: 'warning',
  awaiting_customer_confirmation: 'info', awaiting_fulfilment: 'info',
  awaiting_payment: 'warning', manufacturing: 'warning',
  shipped: 'info', 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',
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

function fmtDate(iso) { return fmtDateLong(iso) }
function fmtDateTime(iso) { return fmtDateTimeCentral(iso) }

// ─── Timeline Event Row ───────────────────────────────────────────────────────

function TimelineRow({ event, index, canEdit, onEdit, onDelete }) {
  const [hovered, setHovered] = useState(false)

  return (
    <div
      style={{ display: 'flex', gap: 'var(--space-3)', position: 'relative', paddingBottom: 'var(--space-3)' }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      {/* Dot + line */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0, paddingTop: 2 }}>
        <div style={{
          width: 8, height: 8, borderRadius: '50%',
          backgroundColor: 'var(--color-primary)',
          boxShadow: '0 0 0 3px var(--color-primary-subtle)',
          flexShrink: 0,
        }} />
        <div style={{ flex: 1, width: 1, backgroundColor: 'var(--color-border)', marginTop: 4 }} />
      </div>

      {/* Content */}
      <div style={{ flex: 1, minWidth: 0, paddingBottom: 'var(--space-1)' }}>
        <div style={{
          fontSize: 'var(--font-size-sm)',
          fontWeight: 'var(--font-weight-semibold)',
          color: 'var(--color-text-primary)',
        }}>
          {TIMELINE_TYPE_LABELS[event.type] || event.type}
        </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="table-actions" size="sm" onClick={() => onEdit(index, event)}>Edit</Button>
          <Button variant="danger" size="sm" onClick={() => onDelete(index)}>Delete</Button>
        </div>
      )}
    </div>
  )
}

// ─── Order Card ───────────────────────────────────────────────────────────────

function OrderCard({ order, customerId, canEdit, user, onReload, initialExpanded = false }) {
  const { toast } = useToast()
  const [expanded, setExpanded] = useState(initialExpanded)

  // Edit order modal
  const [showEdit, setShowEdit] = useState(false)
  // Update status modal
  const [showStatus, setShowStatus] = useState(false)
  // Timeline event modal
  const [timelineModal, setTimelineModal] = useState(null) // null | { editIndex, initialData }
  // Delete timeline
  const [deleteTlIndex, setDeleteTlIndex] = useState(null)
  const [deletingTl, setDeletingTl] = useState(false)
  // Delete order
  const [showDeleteOrder, setShowDeleteOrder] = useState(false)
  const [deletingOrder, setDeletingOrder] = useState(false)

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

  const handleDeleteTimeline = async () => {
    setDeletingTl(true)
    try {
      // Find original index in unsorted timeline
      const sorted = [...(order.timeline || [])].sort((a, b) => (b.date || '').localeCompare(a.date || ''))
      const origIdx = (order.timeline || []).findIndex(e =>
        e.date === sorted[deleteTlIndex].date &&
        e.note === sorted[deleteTlIndex].note &&
        e.type === sorted[deleteTlIndex].type
      )
      await api.delete(`/crm/customers/${customerId}/orders/${order.id}/timeline/${origIdx}`)
      toast.success('Deleted', 'Timeline event removed.')
      setDeleteTlIndex(null)
      onReload()
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to delete event.')
    } finally {
      setDeletingTl(false)
    }
  }

  const handleDeleteOrder = async () => {
    setDeletingOrder(true)
    try {
      await api.delete(`/crm/customers/${customerId}/orders/${order.id}`)
      toast.success('Deleted', 'Order removed.')
      setShowDeleteOrder(false)
      onReload()
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to delete order.')
    } finally {
      setDeletingOrder(false)
    }
  }

  const startEditTimeline = (_sortedIndex, event) => {
    // Resolve original index
    const origIdx = (order.timeline || []).findIndex(e =>
      e.date === event.date && e.note === event.note && e.type === event.type
    )
    setTimelineModal({ editIndex: origIdx, initialData: event })
  }

  const variant = ORDER_STATUS_VARIANT[order.status] || 'neutral'

  return (
    <div style={{
      backgroundColor: 'var(--color-bg-surface)',
      border: '1px solid var(--color-border)',
      borderRadius: 'var(--radius-xl)',
      overflow: 'hidden',
      boxShadow: 'var(--shadow-card)',
    }}>
      {/* ── Order Header ─────────────────────────────────────────────────── */}
      <div
        style={{
          padding: 'var(--space-5)',
          cursor: 'pointer',
          display: 'flex',
          alignItems: 'flex-start',
          gap: 'var(--space-4)',
          flexWrap: 'wrap',
        }}
        onClick={e => {
          if (e.target.closest('button')) return
          setExpanded(v => !v)
        }}
      >
        {/* Info block */}
        <div style={{ flex: 1, minWidth: 200, display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', flexWrap: 'wrap' }}>
            {order.order_number && (
              <span style={{
                fontFamily: 'var(--font-family-mono)',
                fontSize: 'var(--font-size-sm)',
                color: 'var(--color-text-muted)',
              }}>
                {order.order_number}
              </span>
            )}
            <StatusBadge variant={variant}>
              {ORDER_STATUS_LABELS[order.status] || order.status}
            </StatusBadge>
          </div>

          <div style={{
            fontSize: 'var(--font-size-md)',
            fontWeight: 'var(--font-weight-semibold)',
            color: 'var(--color-text-primary)',
          }}>
            {order.title || (
              <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic', fontWeight: 'var(--font-weight-normal)' }}>
                Untitled order
              </span>
            )}
          </div>

          {order.notes && (
            <div style={{
              fontSize: 'var(--font-size-sm)',
              color: 'var(--color-text-secondary)',
              lineHeight: 1.5,
              whiteSpace: 'pre-wrap',
            }}>
              {order.notes}
            </div>
          )}

          <div style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
            Created {fmtDate(order.created_at)}
            {order.created_by ? ` by ${order.created_by}` : ''}
            {order.status_updated_date && order.status_updated_by && (
              <> · Status updated {fmtDate(order.status_updated_date)} by {order.status_updated_by}</>
            )}
          </div>
        </div>

        {/* Action buttons */}
        <div style={{ display: 'flex', gap: 'var(--space-2)', flexShrink: 0, flexWrap: 'wrap' }}>
          {canEdit && (
            <Button
              variant="secondary"
              size="sm"
              onClick={e => { e.stopPropagation(); setShowStatus(true) }}
            >
              Update Status
            </Button>
          )}
          <Button
            variant="ghost"
            size="sm"
            onClick={e => { e.stopPropagation(); setExpanded(v => !v) }}
          >
            {expanded ? 'Hide Timeline' : `Timeline (${timeline.length})`}
          </Button>
          {canEdit && (
            <Button
              variant="ghost"
              size="sm"
              onClick={e => { e.stopPropagation(); setShowEdit(true) }}
            >
              Edit
            </Button>
          )}
          {canEdit && (
            <Button
              variant="danger"
              size="sm"
              onClick={e => { e.stopPropagation(); setShowDeleteOrder(true) }}
              aria-label="Delete order"
            >
              <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor">
                <path d="M5.755 20.283L4 8h16l-1.755 12.283A2 2 0 0116.265 22H7.735a2 2 0 01-1.98-1.717zM21 4h-5V3a1 1 0 00-1-1H9a1 1 0 00-1 1v1H3a1 1 0 000 2h18a1 1 0 000-2z" />
              </svg>
            </Button>
          )}
        </div>
      </div>

      {/* ── Timeline (expanded) ───────────────────────────────────────────── */}
      {expanded && (
        <div style={{
          borderTop: '1px solid var(--color-border)',
          padding: 'var(--space-5)',
          backgroundColor: 'var(--color-bg-base)',
        }}>
          {timeline.length === 0 ? (
            <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic', margin: 0 }}>
              No timeline events yet.
            </p>
          ) : (
            <div style={{ maxHeight: timeline.length > 6 ? 360 : 'none', overflowY: 'auto', paddingRight: 'var(--space-2)' }}>
              {timeline.map((ev, i) => (
                <TimelineRow
                  key={i}
                  event={ev}
                  index={i}
                  canEdit={canEdit}
                  onEdit={startEditTimeline}
                  onDelete={idx => setDeleteTlIndex(idx)}
                />
              ))}
            </div>
          )}

          {canEdit && (
            <div style={{ marginTop: 'var(--space-3)' }}>
              <Button
                variant="secondary"
                size="sm"
                onClick={() => setTimelineModal({ editIndex: null, initialData: null })}
              >
                + Add Event
              </Button>
            </div>
          )}
        </div>
      )}

      {/* ── Modals ───────────────────────────────────────────────────────── */}
      <OrderModal
        open={showEdit}
        customerId={customerId}
        order={order}
        user={user}
        onClose={() => setShowEdit(false)}
        onSaved={onReload}
      />

      <OrderStatusModal
        open={showStatus}
        customerId={customerId}
        order={order}
        user={user}
        onClose={() => setShowStatus(false)}
        onSaved={onReload}
      />

      {timelineModal && (
        <TimelineEventModal
          open={true}
          customerId={customerId}
          orderId={order.id}
          editIndex={timelineModal.editIndex}
          initialData={timelineModal.initialData}
          user={user}
          onClose={() => setTimelineModal(null)}
          onSaved={onReload}
        />
      )}

      <ConfirmDialog
        open={deleteTlIndex !== null}
        variant="danger"
        title="Delete Timeline Event"
        message="Remove this timeline event permanently?"
        confirmLabel={deletingTl ? 'Deleting…' : 'Delete'}
        loading={deletingTl}
        onConfirm={handleDeleteTimeline}
        onCancel={() => setDeleteTlIndex(null)}
        onClose={() => setDeleteTlIndex(null)}
      />

      <ConfirmDialog
        open={showDeleteOrder}
        variant="danger"
        title="Delete Order"
        message={`Delete order "${order.order_number || order.title || 'this order'}"? This cannot be undone.`}
        confirmLabel={deletingOrder ? 'Deleting…' : 'Delete Order'}
        loading={deletingOrder}
        onConfirm={handleDeleteOrder}
        onCancel={() => setShowDeleteOrder(false)}
        onClose={() => setShowDeleteOrder(false)}
      />
    </div>
  )
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function OrdersTab({ customer, orders, canEdit, onReloadOrders }) {
  const { user } = useAuth()
  const [showInitNeg, setShowInitNeg] = useState(false)

  if (!orders) {
    return (
      <div style={{ padding: 'var(--space-10)', textAlign: 'center', color: 'var(--color-text-muted)' }}>
        Loading orders…
      </div>
    )
  }

  if (orders.length === 0) {
    return (
      <Card>
        <div style={{
          padding: 'var(--space-12)',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          gap: 'var(--space-3)',
          color: 'var(--color-text-muted)',
        }}>
          <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2" />
            <rect x="9" y="3" width="6" height="4" rx="1" />
            <path d="M9 12h6M9 16h4" />
          </svg>
          <p style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-secondary)', margin: 0 }}>
            No orders yet
          </p>
          <p style={{ fontSize: 'var(--font-size-sm)', margin: 0 }}>
            Use "Init Negotiations" from the action menu to create the first order.
          </p>
        </div>
      </Card>
    )
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
      {/* Summary row */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 'var(--space-3)',
        flexWrap: 'wrap',
      }}>
        <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
          {orders.length} order{orders.length !== 1 ? 's' : ''}
        </span>
        {/* Status summary pills */}
        {Object.entries(
          orders.reduce((acc, o) => { acc[o.status] = (acc[o.status] || 0) + 1; return acc }, {})
        ).map(([status, count]) => (
          <StatusBadge key={status} variant={ORDER_STATUS_VARIANT[status] || 'neutral'}>
            {count} {ORDER_STATUS_LABELS[status] || status}
          </StatusBadge>
        ))}
        {/* Add Order button — far right */}
        {canEdit && (
          <div style={{ marginLeft: 'auto' }}>
            <Button variant="primary" size="md" onClick={() => setShowInitNeg(true)}>
              + Add Order
            </Button>
          </div>
        )}
      </div>

      {/* Order cards */}
      {orders.map((order, idx) => (
        <OrderCard
          key={order.id}
          order={order}
          customerId={customer.id}
          canEdit={canEdit}
          user={user}
          onReload={onReloadOrders}
          initialExpanded={idx === 0}
        />
      ))}

      <InitNegotiationsModal
        open={showInitNeg}
        customerId={customer.id}
        onClose={() => setShowInitNeg(false)}
        onSuccess={() => { setShowInitNeg(false); onReloadOrders?.() }}
      />
    </div>
  )
}
