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

import { useState, useEffect, useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import PageHeader from '@/components/ui/PageHeader'
import SearchBar from '@/components/ui/SearchBar'
import DataTable from '@/components/ui/DataTable'
import StatusBadge from '@/components/ui/StatusBadge'
import Spinner from '@/components/ui/Spinner'
import Select from '@/components/ui/Select'
import { fmtDateMedium } 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',
}

// Map order status → StatusBadge variant
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',
}

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

// ---------------------------------------------------------------------------
// Columns
// ---------------------------------------------------------------------------
const COLUMNS = [
  {
    key: 'order_number',
    label: 'Order #',
    sortable: true,
    render: (row) => row.order_number
      ? <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', fontWeight: 'var(--font-weight-medium)' }}>{row.order_number}</span>
      : <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>—</span>,
  },
  {
    key: 'customer_name',
    label: 'Customer',
    sortable: true,
    render: (row) => row.customer_name || <span style={{ color: 'var(--color-text-muted)' }}>—</span>,
  },
  {
    key: 'title',
    label: 'Title',
    sortable: true,
    render: (row) => row.title
      ? <span style={{ color: 'var(--color-text-secondary)' }}>{row.title}</span>
      : <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>Untitled</span>,
  },
  {
    key: 'status',
    label: 'Status',
    sortable: true,
    render: (row) => (
      <StatusBadge variant={ORDER_STATUS_VARIANT[row.status] || 'neutral'}>
        {ORDER_STATUS_LABELS[row.status] || row.status || '—'}
      </StatusBadge>
    ),
  },
  {
    key: 'created_at',
    label: 'Created',
    sortable: true,
    render: (row) => <span style={{ color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)' }}>{fmtDate(row.created_at)}</span>,
  },
]

// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------
export default function OrderList() {
  const [orders, setOrders] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [statusFilter, setStatusFilter] = useState('')
  const [searchQuery, setSearchQuery] = useState('')
  const [sortKey, setSortKey] = useState('created_at')
  const [sortDir, setSortDir] = useState('desc')
  const navigate = useNavigate()

  useEffect(() => {
    const load = async () => {
      setLoading(true)
      setError('')
      try {
        const params = new URLSearchParams()
        if (statusFilter) params.set('status', statusFilter)
        const qs = params.toString()
        const data = await api.get(`/crm/orders${qs ? `?${qs}` : ''}`)
        setOrders(data.orders || [])
      } catch (err) {
        setError(err.message)
      } finally {
        setLoading(false)
      }
    }
    load()
  }, [statusFilter])

  const handleSort = (key) => {
    if (sortKey === key) setSortDir(d => d === 'asc' ? 'desc' : 'asc')
    else { setSortKey(key); setSortDir('asc') }
  }

  const filteredOrders = useMemo(() => {
    let rows = orders
    if (searchQuery) {
      const q = searchQuery.toLowerCase()
      rows = rows.filter(o =>
        (o.order_number || '').toLowerCase().includes(q) ||
        (o.customer_name || '').toLowerCase().includes(q) ||
        (o.title || '').toLowerCase().includes(q)
      )
    }
    return [...rows].sort((a, b) => {
      const va = a[sortKey] ?? ''
      const vb = b[sortKey] ?? ''
      const cmp = va < vb ? -1 : va > vb ? 1 : 0
      return sortDir === 'asc' ? cmp : -cmp
    })
  }, [orders, searchQuery, sortKey, sortDir])

  const statusOptions = [
    { value: '', label: 'All Statuses' },
    ...Object.entries(ORDER_STATUS_LABELS).map(([v, l]) => ({ value: v, label: l })),
  ]

  // Status counts for the summary strip
  const statusCounts = useMemo(() => {
    const counts = {}
    orders.forEach(o => { counts[o.status] = (counts[o.status] || 0) + 1 })
    return counts
  }, [orders])

  const activeStatuses = Object.entries(statusCounts)
    .filter(([, c]) => c > 0)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 5)

  return (
    <div className="page-wrapper">
      <PageHeader
        title="Orders"
        subtitle="All customer orders across the pipeline"
      />

      {/* Summary chips */}
      {!loading && !error && activeStatuses.length > 0 && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-2)' }}>
          <button
            type="button"
            onClick={() => setStatusFilter('')}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 'var(--space-2)',
              padding: 'var(--space-1) var(--space-3)',
              borderRadius: 'var(--radius-full)',
              fontSize: 'var(--font-size-sm)',
              cursor: 'pointer',
              border: '1px solid',
              borderColor: !statusFilter ? 'var(--color-primary)' : 'var(--color-border-strong)',
              backgroundColor: !statusFilter ? 'var(--color-primary-subtle)' : 'transparent',
              color: !statusFilter ? 'var(--color-primary)' : 'var(--color-text-muted)',
              transition: 'all 0.15s ease',
              fontFamily: 'var(--font-family-base)',
            }}
          >
            All
            <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-xs)', opacity: 0.7 }}>
              {orders.length}
            </span>
          </button>
          {activeStatuses.map(([status, count]) => (
            <button
              key={status}
              type="button"
              onClick={() => setStatusFilter(s => s === status ? '' : status)}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 'var(--space-2)',
                padding: 'var(--space-1) var(--space-3)',
                borderRadius: 'var(--radius-full)',
                fontSize: 'var(--font-size-sm)',
                cursor: 'pointer',
                border: '1px solid',
                borderColor: statusFilter === status ? 'var(--color-primary)' : 'var(--color-border-strong)',
                backgroundColor: statusFilter === status ? 'var(--color-primary-subtle)' : 'transparent',
                color: statusFilter === status ? 'var(--color-primary)' : 'var(--color-text-muted)',
                transition: 'all 0.15s ease',
                fontFamily: 'var(--font-family-base)',
              }}
            >
              <StatusBadge variant={ORDER_STATUS_VARIANT[status] || 'neutral'}>
                {ORDER_STATUS_LABELS[status] || status}
              </StatusBadge>
              <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-xs)', opacity: 0.7 }}>
                {count}
              </span>
            </button>
          ))}
        </div>
      )}

      {/* Filters row */}
      <div style={{ display: 'flex', gap: 'var(--space-3)', flexWrap: 'wrap', alignItems: 'center' }}>
        <div style={{ flex: '1 1 240px', maxWidth: '360px' }}>
          <SearchBar
            value={searchQuery}
            onChange={setSearchQuery}
            placeholder="Search orders, customers…"
          />
        </div>
        <div style={{ minWidth: '200px' }}>
          <Select
            value={statusFilter}
            onChange={setStatusFilter}
            options={statusOptions}
            placeholder="All Statuses"
          />
        </div>
      </div>

      {/* Error */}
      {error && (
        <div style={{
          padding: 'var(--space-3) var(--space-4)',
          borderRadius: 'var(--radius-md)',
          backgroundColor: 'var(--color-danger-bg)',
          border: '1px solid var(--color-danger)',
          fontSize: 'var(--font-size-sm)',
          color: 'var(--color-danger)',
        }}>
          {error}
        </div>
      )}

      {/* Loading */}
      {loading ? (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'var(--space-16)' }}>
          <Spinner size="md" />
        </div>
      ) : (
        <DataTable
          columns={COLUMNS}
          data={filteredOrders}
          sortKey={sortKey}
          sortDir={sortDir}
          onSort={handleSort}
          onRowClick={(row) => navigate(`/crm/orders/${row.id}`)}
          emptyMessage={searchQuery || statusFilter ? 'No orders match your filters.' : 'No orders yet.'}
          keyField="id"
        />
      )}
    </div>
  )
}
