// frontend/src/pages/crm/quotations/QuotationForm.jsx
// Create / Edit a quotation — full line-item builder with live totals

import { useState, useEffect, useMemo, useCallback } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import api from '@/lib/api'
import PageHeader from '@/components/ui/PageHeader'
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import FormField from '@/components/ui/FormField'
import StatusBadge from '@/components/ui/StatusBadge'
import Spinner from '@/components/ui/Spinner'
import Icon from '@/components/ui/Icon'
import ProductSearchModal from '@/modals/crm/ProductSearchModal'
import { fmtEuro } from '@/lib/formatters'

// ─── Constants ────────────────────────────────────────────────────────────────

const STATUS_OPTIONS    = ['draft', 'built', 'sent', 'accepted', 'declined']
const STATUS_BADGE_MAP  = { draft: 'neutral', built: 'warning', sent: 'info', accepted: 'success', declined: 'danger' }

const ORDER_TYPE_OPTIONS = [
  { value: '',                  label: '— Select —' },
  { value: 'Shipping',          label: 'Shipping' },
  { value: 'Pick-Up',           label: 'Pick-Up' },
  { value: 'Install On-Site',   label: 'Install On-Site' },
  { value: 'Other',             label: 'Other' },
]

const SHIPPING_METHOD_OPTIONS = [
  { value: '',                       label: '— Select —' },
  { value: 'Courier',                label: 'Courier' },
  { value: 'Transport',              label: 'Transport' },
  { value: 'Arranged with Client',   label: 'Arranged with Client' },
]

const UNIT_OPTIONS = [
  { value: 'pcs', label: 'pcs' },
  { value: 'kg',  label: 'kg' },
  { value: 'm',   label: 'm' },
]

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

function fmt(n) { return fmtEuro(n) }

const emptyItem = (sortOrder = 0) => ({
  product_id: null,
  description: '',
  description_en: '',
  description_gr: '',
  unit_type: 'pcs',
  unit_cost: 0,
  discount_percent: 0,
  quantity: 1,
  sort_order: sortOrder,
})

function calcLineTotal(item) {
  const cost = parseFloat(item.unit_cost) || 0
  const qty  = parseFloat(item.quantity)  || 0
  const disc = parseFloat(item.discount_percent) || 0
  return cost * qty * (1 - disc / 100)
}

function calcTotals(form) {
  const items      = form.items || []
  const itemsNet   = items.reduce((sum, it) => sum + calcLineTotal(it), 0)

  const shipNet    = (parseFloat(form.shipping_cost) || 0) * (1 - (parseFloat(form.shipping_cost_discount) || 0) / 100)
  const installNet = (parseFloat(form.install_cost)  || 0) * (1 - (parseFloat(form.install_cost_discount) || 0) / 100)
  const subtotal   = itemsNet + shipNet + installNet

  const globalDiscPct = parseFloat(form.global_discount_percent) || 0
  const globalDiscAmt = subtotal * (globalDiscPct / 100)
  const newSubtotal   = subtotal - globalDiscAmt

  // VAT applies to items only (not shipping/install), scaled by global discount
  const vatPct  = parseFloat(form.global_vat_percent) || 0
  const vatAmt  = subtotal > 0 && itemsNet > 0
    ? newSubtotal * (itemsNet / subtotal) * (vatPct / 100)
    : 0

  const extras     = parseFloat(form.extras_cost) || 0
  const finalTotal = newSubtotal + vatAmt + extras

  return { subtotal_before_discount: subtotal, global_discount_amount: globalDiscAmt, new_subtotal: newSubtotal, vat_amount: vatAmt, final_total: finalTotal }
}

// ─── Small reusable sub-components ────────────────────────────────────────────

// Raw input styled to match FormField's "cutout" treatment — used in the items table
// to keep dense columns without full FormField overhead
function CellInput({ value, onChange, type = 'text', placeholder, min, max, step, style, readOnly, className = '' }) {
  return (
    <input
      type={type}
      value={value ?? ''}
      onChange={e => onChange && onChange(type === 'number' ? (parseFloat(e.target.value) ?? 0) : e.target.value)}
      placeholder={placeholder}
      min={min}
      max={max}
      step={step}
      readOnly={readOnly}
      className={`input ${className}`}
      style={{
        padding: 'var(--space-2) var(--space-2)',
        fontSize: 'var(--font-size-sm)',
        MozAppearance: 'textfield',
        ...style,
      }}
    />
  )
}

function CellSelect({ value, onChange, options, style }) {
  return (
    <select
      value={value ?? ''}
      onChange={e => onChange(e.target.value)}
      className="input"
      style={{ padding: 'var(--space-2)', fontSize: 'var(--font-size-sm)', textAlign: 'center', ...style }}
    >
      {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
    </select>
  )
}

// ─── Main component ────────────────────────────────────────────────────────────

export default function QuotationForm() {
  const { id }            = useParams()
  const [searchParams]    = useSearchParams()
  const navigate          = useNavigate()
  const isEdit            = Boolean(id)
  const copyFromId        = !isEdit ? (searchParams.get('copy_from') || null) : null

  const [customer, setCustomer]               = useState(null)
  const [quotationNumber, setQuotationNumber] = useState('')
  const [saving, setSaving]                   = useState(false)
  const [loadingPage, setLoadingPage]         = useState(isEdit || Boolean(copyFromId))
  const [error, setError]                     = useState(null)
  const [showProductModal, setShowProductModal] = useState(false)
  const [showShipping, setShowShipping]       = useState(false)
  const [showInstall, setShowInstall]         = useState(false)
  const [clientPopulated, setClientPopulated] = useState(false)

  const [form, setForm] = useState({
    language: 'en',
    title: '',
    subtitle: '',
    customer_id: searchParams.get('customer_id') || '',
    order_type: '',
    shipping_method: '',
    estimated_shipping_date: '',
    global_discount_label: '',
    global_discount_percent: 0,
    global_vat_percent: 24,
    shipping_cost: 0,
    shipping_cost_discount: 0,
    install_cost: 0,
    install_cost_discount: 0,
    extras_label: '',
    extras_cost: 0,
    comments: [],
    items: [],
    status: 'draft',
    client_org: '',
    client_name: '',
    client_location: '',
    client_phone: '',
    client_email: '',
  })

  const [quickNotes, setQuickNotes] = useState({
    payment_advance: { enabled: false, percent: '30' },
    lead_time:       { enabled: false, days: '7' },
    backup_relays:   { enabled: false, count: '2' },
  })

  // ─── Load existing quotation ────────────────────────────────────────────
  useEffect(() => {
    if (isEdit) {
      setLoadingPage(true)
      api.get(`/crm/quotations/${id}`)
        .then(q => {
          setForm({
            language: q.language || 'en',
            title: q.title || '',
            subtitle: q.subtitle || '',
            customer_id: q.customer_id,
            order_type: q.order_type || '',
            shipping_method: q.shipping_method || '',
            estimated_shipping_date: q.estimated_shipping_date || '',
            global_discount_label: q.global_discount_label || '',
            global_discount_percent: q.global_discount_percent || 0,
            global_vat_percent: q.global_vat_percent ?? 24,
            shipping_cost: q.shipping_cost || 0,
            shipping_cost_discount: q.shipping_cost_discount || 0,
            install_cost: q.install_cost || 0,
            install_cost_discount: q.install_cost_discount || 0,
            extras_label: q.extras_label || '',
            extras_cost: q.extras_cost || 0,
            comments: q.comments || [],
            items: (q.items || []).map(it => ({
              product_id: it.product_id || null,
              description: it.description || '',
              description_en: it.description_en || '',
              description_gr: it.description_gr || '',
              unit_type: it.unit_type || 'pcs',
              unit_cost: it.unit_cost || 0,
              discount_percent: it.discount_percent || 0,
              quantity: it.quantity || 1,
              sort_order: it.sort_order || 0,
            })),
            status: q.status || 'draft',
            client_org: q.client_org || '',
            client_name: q.client_name || '',
            client_location: q.client_location || '',
            client_phone: q.client_phone || '',
            client_email: q.client_email || '',
          })
          if (q.quick_notes && typeof q.quick_notes === 'object') {
            setQuickNotes(prev => ({
              payment_advance: { ...prev.payment_advance, ...q.quick_notes.payment_advance },
              lead_time:       { ...prev.lead_time,       ...q.quick_notes.lead_time },
              backup_relays:   { ...prev.backup_relays,   ...q.quick_notes.backup_relays },
            }))
          }
          setQuotationNumber(q.quotation_number)
          if (q.shipping_cost > 0) setShowShipping(true)
          if (q.install_cost > 0)  setShowInstall(true)
          setClientPopulated(true)
        })
        .catch(() => setError('Failed to load quotation.'))
        .finally(() => setLoadingPage(false))
    } else if (copyFromId) {
      // Copy mode — load source quotation as a template, then get a fresh number
      setLoadingPage(true)
      Promise.all([
        api.get(`/crm/quotations/${copyFromId}`),
        api.get('/crm/quotations/next-number'),
      ])
        .then(([q, r]) => {
          setForm({
            language: q.language || 'en',
            title: q.title || '',
            subtitle: q.subtitle || '',
            customer_id: searchParams.get('customer_id') || q.customer_id,
            order_type: q.order_type || '',
            shipping_method: q.shipping_method || '',
            estimated_shipping_date: q.estimated_shipping_date || '',
            global_discount_label: q.global_discount_label || '',
            global_discount_percent: q.global_discount_percent || 0,
            global_vat_percent: q.global_vat_percent ?? 24,
            shipping_cost: q.shipping_cost || 0,
            shipping_cost_discount: q.shipping_cost_discount || 0,
            install_cost: q.install_cost || 0,
            install_cost_discount: q.install_cost_discount || 0,
            extras_label: q.extras_label || '',
            extras_cost: q.extras_cost || 0,
            comments: q.comments || [],
            items: (q.items || []).map(it => ({
              product_id: it.product_id || null,
              description: it.description || '',
              description_en: it.description_en || '',
              description_gr: it.description_gr || '',
              unit_type: it.unit_type || 'pcs',
              unit_cost: it.unit_cost || 0,
              discount_percent: it.discount_percent || 0,
              quantity: it.quantity || 1,
              sort_order: it.sort_order || 0,
            })),
            status: 'draft',
            client_org: q.client_org || '',
            client_name: q.client_name || '',
            client_location: q.client_location || '',
            client_phone: q.client_phone || '',
            client_email: q.client_email || '',
          })
          if (q.quick_notes && typeof q.quick_notes === 'object') {
            setQuickNotes(prev => ({
              payment_advance: { ...prev.payment_advance, ...q.quick_notes.payment_advance },
              lead_time:       { ...prev.lead_time,       ...q.quick_notes.lead_time },
              backup_relays:   { ...prev.backup_relays,   ...q.quick_notes.backup_relays },
            }))
          }
          setQuotationNumber(r.next_number)
          if (q.shipping_cost > 0) setShowShipping(true)
          if (q.install_cost > 0)  setShowInstall(true)
          setClientPopulated(true)
        })
        .catch(() => setError('Failed to load source quotation.'))
        .finally(() => setLoadingPage(false))
    } else {
      api.get('/crm/quotations/next-number').then(r => setQuotationNumber(r.next_number)).catch(() => {})
    }
  }, [id, isEdit, copyFromId])

  // ─── Load customer + auto-fill client fields ─────────────────────────────
  useEffect(() => {
    const cid = form.customer_id
    if (!cid) return
    api.get(`/crm/customers/${cid}`)
      .then(c => {
        setCustomer(c)
        if (!clientPopulated) {
          const name     = [c.title, c.name, c.surname].filter(Boolean).join(' ')
          const location = [c.location?.address, c.location?.city, c.location?.postal_code, c.location?.region, c.location?.country].filter(Boolean).join(', ')
          const phone    = (c.contacts || []).find(ct => ct.type === 'phone')?.value || ''
          const email    = (c.contacts || []).find(ct => ct.type === 'email')?.value || ''
          setForm(f => ({ ...f, client_org: c.organization || '', client_name: name, client_location: location, client_phone: phone, client_email: email }))
          setClientPopulated(true)
        }
      })
      .catch(() => setCustomer(null))
  }, [form.customer_id, clientPopulated])

  // ─── State helpers ───────────────────────────────────────────────────────
  const setField = useCallback((key, value) => setForm(f => ({ ...f, [key]: value })), [])

  const addBlankItem = useCallback(() => {
    setForm(f => ({ ...f, items: [...f.items, emptyItem(f.items.length)] }))
  }, [])

  const removeItem = useCallback(idx => {
    setForm(f => ({ ...f, items: f.items.filter((_, i) => i !== idx) }))
  }, [])

  const setItemField = useCallback((idx, key, value) => {
    setForm(f => ({ ...f, items: f.items.map((it, i) => i === idx ? { ...it, [key]: value } : it) }))
  }, [])

  const addProductFromCatalogue = useCallback(product => {
    setForm(f => {
      const lang   = f.language || 'en'
      const nameEn = product.name_en || product.name || ''
      const nameGr = product.name_gr || product.name || ''
      return {
        ...f,
        items: [...f.items, {
          product_id: product.id,
          description: lang === 'gr' ? nameGr : nameEn,
          description_en: nameEn,
          description_gr: nameGr,
          unit_type: 'pcs',
          unit_cost: product.price || 0,
          discount_percent: 0,
          quantity: 1,
          sort_order: f.items.length,
        }],
      }
    })
    setShowProductModal(false)
  }, [])

  const addComment    = useCallback(() => setForm(f => ({ ...f, comments: [...f.comments, ''] })), [])
  const setComment    = useCallback((idx, v) => setForm(f => ({ ...f, comments: f.comments.map((c, i) => i === idx ? v : c) })), [])
  const removeComment = useCallback(idx => setForm(f => ({ ...f, comments: f.comments.filter((_, i) => i !== idx) })), [])
  const setQuickNote  = useCallback((key, field, value) => setQuickNotes(prev => ({ ...prev, [key]: { ...prev[key], [field]: value } })), [])

  const totals = useMemo(() => calcTotals(form), [form])

  // ─── Save ────────────────────────────────────────────────────────────────
  async function handleSave(generatePdf = false) {
    setSaving(true)
    setError(null)
    try {
      const payload = {
        customer_id: form.customer_id,
        title: form.title || null,
        subtitle: form.subtitle || null,
        language: form.language,
        order_type: form.order_type || null,
        shipping_method: form.shipping_method || null,
        estimated_shipping_date: form.estimated_shipping_date || null,
        global_discount_label: form.global_discount_label || null,
        global_discount_percent: parseFloat(form.global_discount_percent) || 0,
        global_vat_percent: parseFloat(form.global_vat_percent) ?? 24,
        shipping_cost: showShipping ? (parseFloat(form.shipping_cost) || 0) : 0,
        shipping_cost_discount: showShipping ? (parseFloat(form.shipping_cost_discount) || 0) : 0,
        install_cost: showInstall ? (parseFloat(form.install_cost) || 0) : 0,
        install_cost_discount: showInstall ? (parseFloat(form.install_cost_discount) || 0) : 0,
        extras_label: form.extras_label || null,
        extras_cost: parseFloat(form.extras_cost) || 0,
        comments: form.comments.filter(c => c.trim()),
        quick_notes: quickNotes,
        items: form.items.map((it, i) => ({
          product_id: it.product_id || null,
          description: it.description || null,
          description_en: it.description_en || null,
          description_gr: it.description_gr || null,
          unit_type: it.unit_type || 'pcs',
          unit_cost: parseFloat(it.unit_cost) || 0,
          discount_percent: parseFloat(it.discount_percent) || 0,
          quantity: parseFloat(it.quantity) || 1,
          sort_order: i,
        })),
        client_org: form.client_org || null,
        client_name: form.client_name || null,
        client_location: form.client_location || null,
        client_phone: form.client_phone || null,
        client_email: form.client_email || null,
      }

      const pdfParam = generatePdf ? '?generate_pdf=true' : ''
      // Status rules: "Save Draft" always sets draft; "Generate & Save PDF" sets built (unless staff manually set accepted/declined)
      const saveStatus = generatePdf
        ? (form.status === 'accepted' || form.status === 'declined' ? form.status : 'built')
        : 'draft'
      let result
      if (isEdit) {
        result = await api.put(`/crm/quotations/${id}${pdfParam}`, { ...payload, status: saveStatus })
      } else {
        result = await api.post(`/crm/quotations${pdfParam}`, { ...payload, status: saveStatus })
      }

      navigate(`/crm/customers/${result.customer_id}`, { state: { tab: 'Quotations' } })
    } catch (e) {
      setError(e.message || 'Save failed')
    } finally {
      setSaving(false)
    }
  }

  // ─── Loading screen ──────────────────────────────────────────────────────
  if (loadingPage) {
    return (
      <div className="page-wrapper" style={{ alignItems: 'center', justifyContent: 'center', minHeight: '60vh' }}>
        <Spinner size="lg" />
      </div>
    )
  }

  if (error && !form.customer_id) {
    return (
      <div className="page-wrapper">
        <div style={{ color: 'var(--color-danger)', fontSize: 'var(--font-size-sm)' }}>{error}</div>
      </div>
    )
  }

  const customerLabel = customer
    ? (customer.organization || [customer.title, customer.name, customer.surname].filter(Boolean).join(' '))
    : null

  // ─── Render ──────────────────────────────────────────────────────────────
  return (
    <div className="page-wrapper page-wrapper--capped" style={{ paddingBottom: 'var(--space-16)' }}>

      <PageHeader
        title={isEdit ? 'Edit Quotation' : copyFromId ? 'Copy Quotation' : 'New Quotation'}
        subtitle={customerLabel ? `Customer: ${customerLabel}` : undefined}
      >
        {isEdit && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)', marginRight: 'var(--space-2)' }}>
            <span style={{
              fontFamily: 'var(--font-family-mono)',
              fontSize: 'var(--font-size-sm)',
              color: 'var(--color-text-muted)',
            }}>
              {quotationNumber}
            </span>
            <StatusBadge variant={STATUS_BADGE_MAP[form.status] || 'neutral'}>
              {form.status}
            </StatusBadge>
          </div>
        )}
        <Button variant="secondary" size="md" onClick={() => navigate(-1)} disabled={saving}>
          Cancel
        </Button>
        <Button variant="secondary" size="md" loading={saving} onClick={() => handleSave(false)}>
          Save Draft
        </Button>
        <Button
          variant="primary"
          size="md"
          loading={saving}
          icon={<Icon name="download" size={14} />}
          onClick={() => handleSave(true)}
        >
          Generate &amp; Save PDF
        </Button>
      </PageHeader>

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

      {/* ── Two-column layout ───────────────────────────────────────────── */}
      <div style={{ display: 'flex', gap: 'var(--space-5)', alignItems: 'flex-start' }}>

        {/* LEFT COLUMN — 38% */}
        <div style={{ flex: '0 0 38%', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>

          {/* ① Header card */}
          <Card title="Header">
            <div style={{ display: 'flex', gap: 'var(--space-3)', marginBottom: 'var(--space-4)', alignItems: 'flex-end' }}>
              {/* Language toggle */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
                <span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)' }}>Language</span>
                <div style={{ display: 'flex', gap: 'var(--space-1)' }}>
                  {['en', 'gr'].map(lang => (
                    <button
                      key={lang}
                      onClick={() => setField('language', lang)}
                      style={{
                        padding: 'var(--space-3) var(--space-4)',
                        fontSize: 'var(--font-size-base)',
                        fontWeight: 'var(--font-weight-semibold)',
                        lineHeight: 'var(--line-height-base)',
                        borderRadius: 'var(--radius-md)',
                        border: '1px solid var(--color-border)',
                        cursor: 'pointer',
                        backgroundColor: form.language === lang ? 'var(--color-primary-subtle)' : 'transparent',
                        color: form.language === lang ? 'var(--color-primary)' : 'var(--color-text-secondary)',
                        borderColor: form.language === lang ? 'var(--color-primary)' : 'var(--color-border)',
                        transition: 'all 0.15s',
                      }}
                    >
                      {lang === 'en' ? 'EN' : 'GR'}
                    </button>
                  ))}
                </div>
              </div>

              {/* Quotation # */}
              <div style={{ flex: 1 }}>
                <FormField
                  label="Quotation #"
                  name="quotation-number"
                  value={quotationNumber}
                  onChange={() => {}}
                  inputProps={{ readOnly: true, style: { fontFamily: 'var(--font-family-mono)', fontWeight: 600 } }}
                />
              </div>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
              <FormField
                label="Title"
                name="title"
                value={form.title}
                onChange={e => setField('title', e.target.value)}
                placeholder="Quotation title…"
              />
              <FormField
                label="Subtitle"
                name="subtitle"
                value={form.subtitle}
                onChange={e => setField('subtitle', e.target.value)}
                placeholder="Optional subtitle…"
              />
              <FormField
                label="Status"
                name="status"
                type="select"
                value={form.status}
                onChange={e => setField('status', e.target.value)}
              >
                {STATUS_OPTIONS.map(s => (
                  <option key={s} value={s}>{s.charAt(0).toUpperCase() + s.slice(1)}</option>
                ))}
              </FormField>
            </div>
          </Card>

          {/* ② Client Info */}
          <Card
            title="Client Info"
            subtitle="Editable for this quotation only — customer record is not affected."
          >
            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
                <FormField label="Organization" name="client-org" value={form.client_org} onChange={e => setField('client_org', e.target.value)} placeholder="Company…" />
                <FormField label="Phone" name="client-phone" type="tel" value={form.client_phone} onChange={e => setField('client_phone', e.target.value)} placeholder="+30…" />
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
                <FormField label="Name" name="client-name" value={form.client_name} onChange={e => setField('client_name', e.target.value)} placeholder="Full name…" />
                <FormField label="Email" name="client-email" type="email" value={form.client_email} onChange={e => setField('client_email', e.target.value)} placeholder="email@…" />
              </div>
              <FormField label="Location" name="client-location" value={form.client_location} onChange={e => setField('client_location', e.target.value)} placeholder="City, region, country…" />
            </div>
          </Card>

          {/* ③ Order Details */}
          <Card title="Order Details">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
                <FormField label="Order Type" name="order-type" type="select" value={form.order_type} onChange={e => setField('order_type', e.target.value)}>
                  {ORDER_TYPE_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                </FormField>
                <FormField label="Shipping Method" name="shipping-method" type="select" value={form.shipping_method} onChange={e => setField('shipping_method', e.target.value)}>
                  {SHIPPING_METHOD_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                </FormField>
              </div>
              <FormField
                label="Estimated Delivery Date"
                name="delivery-date"
                value={form.estimated_shipping_date}
                onChange={e => setField('estimated_shipping_date', e.target.value)}
                inputProps={{ type: 'date' }}
              />
            </div>
          </Card>

        </div>{/* end LEFT */}

        {/* RIGHT COLUMN */}
        <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>

          {/* ④ Items */}
          <Card title="Line Items">
              {/* Items table */}
              {(form.items.length > 0 || showShipping || showInstall) && (
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: '3fr 86px 60px 60px 60px 88px 30px',
                  gap: 'var(--space-2)',
                  marginBottom: 'var(--space-2)',
                  padding: '0 2px',
                }}>
                  {['Description', 'Unit Cost €', 'Disc %', 'Qty', 'Unit', 'Line Total', ''].map((h, i) => (
                    <div key={i} style={{
                      fontSize: 'var(--font-size-xs)',
                      fontWeight: 'var(--font-weight-semibold)',
                      color: 'var(--color-text-muted)',
                      textTransform: 'uppercase',
                      letterSpacing: 'var(--tracking-wide)',
                      textAlign: i === 5 ? 'right' : i >= 1 && i <= 4 ? 'center' : 'left',
                    }}>
                      {h}
                    </div>
                  ))}
                </div>
              )}

              {/* Item rows */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
                {form.items.map((item, idx) => (
                  <div
                    key={idx}
                    style={{
                      display: 'grid',
                      gridTemplateColumns: '3fr 86px 60px 60px 60px 88px 30px',
                      gap: 'var(--space-2)',
                      alignItems: 'center',
                    }}
                  >
                    <CellInput
                      value={item.description}
                      onChange={v => setItemField(idx, 'description', v)}
                      placeholder="Description…"
                    />
                    <CellInput
                      type="number"
                      value={item.unit_cost}
                      onChange={v => setItemField(idx, 'unit_cost', v)}
                      min={0} step="0.01"
                      style={{ textAlign: 'center' }}
                    />
                    <CellInput
                      type="number"
                      value={item.discount_percent}
                      onChange={v => setItemField(idx, 'discount_percent', v)}
                      min={0} max={100} step="0.5"
                      style={{ textAlign: 'center' }}
                    />
                    <CellInput
                      type="number"
                      value={item.quantity}
                      onChange={v => setItemField(idx, 'quantity', v)}
                      min={0} step="1"
                      style={{ textAlign: 'center' }}
                    />
                    <CellSelect
                      value={item.unit_type}
                      onChange={v => setItemField(idx, 'unit_type', v)}
                      options={UNIT_OPTIONS}
                      style={{ textAlign: 'center' }}
                    />
                    <div style={{
                      fontSize: 'var(--font-size-sm)',
                      fontWeight: 'var(--font-weight-semibold)',
                      color: 'var(--color-text-primary)',
                      textAlign: 'right',
                      padding: '0 var(--space-1)',
                    }}>
                      {fmt(calcLineTotal(item))}
                    </div>
                    <button
                      onClick={() => removeItem(idx)}
                      style={{
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        width: 28, height: 28,
                        borderRadius: 'var(--radius-md)',
                        border: '1px solid var(--color-border)',
                        backgroundColor: 'transparent',
                        cursor: 'pointer',
                        color: 'var(--color-text-muted)',
                        transition: 'color 0.15s, border-color 0.15s, background-color 0.15s',
                      }}
                      onMouseEnter={e => {
                        e.currentTarget.style.color = 'var(--color-danger)'
                        e.currentTarget.style.borderColor = 'rgba(255,92,92,0.4)'
                        e.currentTarget.style.backgroundColor = 'var(--color-danger-bg)'
                      }}
                      onMouseLeave={e => {
                        e.currentTarget.style.color = 'var(--color-text-muted)'
                        e.currentTarget.style.borderColor = 'var(--color-border)'
                        e.currentTarget.style.backgroundColor = 'transparent'
                      }}
                    >
                      <Icon name="close" size={12} />
                    </button>
                  </div>
                ))}
              </div>

              {/* Empty state */}
              {form.items.length === 0 && !showShipping && !showInstall && (
                <div style={{
                  padding: 'var(--space-6)',
                  textAlign: 'center',
                  color: 'var(--color-text-muted)',
                  fontSize: 'var(--font-size-sm)',
                  borderRadius: 'var(--radius-md)',
                  border: '1px dashed var(--color-border)',
                  backgroundColor: 'var(--color-bg-abyss)',
                }}>
                  No items yet — add from catalogue or add a blank row
                </div>
              )}

              {/* Shipping row */}
              {showShipping && (
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: '3fr 86px 60px 30px',
                  gap: 'var(--space-2)',
                  alignItems: 'center',
                  backgroundColor: 'var(--color-bg-elevated)',
                  borderRadius: 'var(--radius-md)',
                  padding: 'var(--space-2) var(--space-2)',
                  marginTop: 'var(--space-2)',
                }}>
                  <div style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)', paddingLeft: 'var(--space-2)' }}>
                    Shipping
                  </div>
                  <CellInput
                    type="number"
                    value={form.shipping_cost}
                    onChange={v => setField('shipping_cost', v)}
                    min={0} step="0.01"
                    style={{ textAlign: 'right' }}
                  />
                  <div style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)', textAlign: 'right', padding: '0 var(--space-1)' }}>
                    {fmt(parseFloat(form.shipping_cost) || 0)}
                  </div>
                  <button onClick={() => { setShowShipping(false); setField('shipping_cost', 0); setField('shipping_cost_discount', 0) }} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 28, height: 28, borderRadius: 'var(--radius-md)', border: '1px solid var(--color-border)', backgroundColor: 'transparent', cursor: 'pointer', color: 'var(--color-text-muted)' }}>
                    <Icon name="close" size={12} />
                  </button>
                </div>
              )}

              {/* Install row */}
              {showInstall && (
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: '3fr 86px 60px 30px',
                  gap: 'var(--space-2)',
                  alignItems: 'center',
                  backgroundColor: 'var(--color-bg-elevated)',
                  borderRadius: 'var(--radius-md)',
                  padding: 'var(--space-2) var(--space-2)',
                  marginTop: 'var(--space-2)',
                }}>
                  <div style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)', paddingLeft: 'var(--space-2)' }}>
                    Installation
                  </div>
                  <CellInput
                    type="number"
                    value={form.install_cost}
                    onChange={v => setField('install_cost', v)}
                    min={0} step="0.01"
                    style={{ textAlign: 'right' }}
                  />
                  <div style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)', textAlign: 'right', padding: '0 var(--space-1)' }}>
                    {fmt(parseFloat(form.install_cost) || 0)}
                  </div>
                  <button onClick={() => { setShowInstall(false); setField('install_cost', 0); setField('install_cost_discount', 0) }} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 28, height: 28, borderRadius: 'var(--radius-md)', border: '1px solid var(--color-border)', backgroundColor: 'transparent', cursor: 'pointer', color: 'var(--color-text-muted)' }}>
                    <Icon name="close" size={12} />
                  </button>
                </div>
              )}

              {/* Add rows / shipping / install — shipping/install left, catalogue/blank right */}
              <div style={{ display: 'flex', gap: 'var(--space-2)', marginTop: 'var(--space-3)', flexWrap: 'wrap' }}>
                <div style={{ display: 'flex', gap: 'var(--space-2)' }}>
                  {!showShipping && (
                    <Button variant="ghost" size="sm" onClick={() => setShowShipping(true)}>
                      + Shipping Cost
                    </Button>
                  )}
                  {!showInstall && (
                    <Button variant="ghost" size="sm" onClick={() => setShowInstall(true)}>
                      + Installation Cost
                    </Button>
                  )}
                </div>
                <div style={{ display: 'flex', gap: 'var(--space-2)', marginLeft: 'auto' }}>
                  <Button variant="ghost" size="sm" onClick={() => setShowProductModal(true)}>
                    + From Catalogue
                  </Button>
                  <Button variant="ghost" size="sm" onClick={addBlankItem}>
                    + Blank Row
                  </Button>
                </div>
              </div>
          </Card>

          {/* ⑤ Totals */}
          <Card title="Totals">

              {/* Discount + VAT rows side by side */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-2)', marginBottom: 'var(--space-2)' }}>
                {/* Discount row */}
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: '70px 1fr 80px 20px',
                  alignItems: 'center',
                  gap: 'var(--space-2)',
                  padding: 'var(--space-2) var(--space-3)',
                  borderRadius: 'var(--radius-md)',
                  border: '1px solid var(--color-border)',
                  backgroundColor: 'var(--color-bg-abyss)',
                }}>
                  <div style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)' }}>Discount</div>
                  <CellInput
                    value={form.global_discount_label}
                    onChange={v => setField('global_discount_label', v)}
                    placeholder="Discount label…"
                    style={{ fontSize: 'var(--font-size-xs)' }}
                  />
                  <CellInput
                    type="number"
                    value={form.global_discount_percent}
                    onChange={v => setField('global_discount_percent', v)}
                    min={0} max={100} step="0.5"
                    style={{ textAlign: 'right', fontSize: 'var(--font-size-xs)' }}
                  />
                  <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', textAlign: 'center' }}>%</span>
                </div>

                {/* VAT row */}
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: '40px 1fr 80px 20px',
                  alignItems: 'center',
                  gap: 'var(--space-2)',
                  padding: 'var(--space-2) var(--space-3)',
                  borderRadius: 'var(--radius-md)',
                  border: '1px solid var(--color-border)',
                  backgroundColor: 'var(--color-bg-abyss)',
                }}>
                  <div style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)' }}>VAT</div>
                  <div style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>Items only — excl. shipping &amp; install</div>
                  <CellInput
                    type="number"
                    value={form.global_vat_percent}
                    onChange={v => setField('global_vat_percent', v)}
                    min={0} max={100} step="1"
                    style={{ textAlign: 'right', fontSize: 'var(--font-size-xs)' }}
                  />
                  <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', textAlign: 'center' }}>%</span>
                </div>
              </div>

              {/* Extras row */}
              <div style={{
                display: 'grid',
                gridTemplateColumns: '80px 1fr 96px 20px',
                alignItems: 'center',
                gap: 'var(--space-2)',
                marginBottom: 'var(--space-4)',
                padding: 'var(--space-2) var(--space-3)',
                borderRadius: 'var(--radius-md)',
                border: '1px solid var(--color-border)',
                backgroundColor: 'var(--color-bg-abyss)',
              }}>
                <div style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)' }}>Other</div>
                <CellInput
                  value={form.extras_label}
                  onChange={v => setField('extras_label', v)}
                  placeholder="Other costs…"
                  style={{ fontSize: 'var(--font-size-xs)' }}
                />
                <CellInput
                  type="number"
                  value={form.extras_cost}
                  onChange={v => setField('extras_cost', v)}
                  min={0} step="0.01"
                  style={{ textAlign: 'right', fontSize: 'var(--font-size-xs)' }}
                />
                <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', textAlign: 'center' }}>€</span>
              </div>

              {/* Summary boxes */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 'var(--space-3)' }}>
                {[
                  { label: 'Subtotal excl. VAT', value: fmt(totals.subtotal_before_discount), accent: false, due: false },
                  { label: 'After Discount',      value: fmt(totals.new_subtotal),             accent: false, due: false },
                  { label: `VAT ${parseFloat(form.global_vat_percent) || 0}%`, value: fmt(totals.vat_amount), accent: false, due: false },
                  { label: 'Total Due',            value: fmt(totals.final_total),              accent: true,  due: true  },
                ].map(({ label, value, accent, due }) => (
                  <div
                    key={label}
                    style={{
                      padding: 'var(--space-3) var(--space-3)',
                      borderRadius: 'var(--radius-md)',
                      border: `1px solid ${due ? 'var(--color-success)' : accent ? 'var(--color-primary)' : 'var(--color-border)'}`,
                      backgroundColor: due ? 'var(--color-success-bg)' : accent ? 'var(--color-primary-subtle)' : 'var(--color-bg-abyss)',
                      textAlign: 'center',
                    }}
                  >
                    <div style={{
                      fontSize: 'var(--font-size-xs)',
                      fontWeight: 'var(--font-weight-semibold)',
                      color: 'var(--color-text-muted)',
                      textTransform: 'uppercase',
                      letterSpacing: 'var(--tracking-wide)',
                      marginBottom: 'var(--space-2)',
                    }}>
                      {label}
                    </div>
                    <div style={{
                      fontSize: due ? 'var(--font-size-lg)' : 'var(--font-size-md)',
                      fontWeight: 'var(--font-weight-bold)',
                      color: due ? 'var(--color-success)' : 'var(--color-text-primary)',
                    }}>
                      {value}
                    </div>
                  </div>
                ))}
              </div>
          </Card>

          {/* ⑥ Notes & Quick Notes */}
          <Card title="Notes / Comments">

              {/* Quick notes */}
              <div style={{ marginBottom: 'var(--space-4)' }}>
                <div style={{
                  fontSize: 'var(--font-size-xs)',
                  fontWeight: 'var(--font-weight-semibold)',
                  color: 'var(--color-text-muted)',
                  textTransform: 'uppercase',
                  letterSpacing: 'var(--tracking-wide)',
                  marginBottom: 'var(--space-2)',
                }}>
                  Quick Notes
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
                  {[
                    { key: 'payment_advance', label: 'Payment Advance', fieldKey: 'percent', suffix: '%' },
                    { key: 'lead_time',       label: 'Lead Time',       fieldKey: 'days',    suffix: 'days' },
                    { key: 'backup_relays',   label: 'Backup Relays',   fieldKey: 'count',   suffix: `relay${parseInt(quickNotes.backup_relays.count) === 1 ? '' : 's'}` },
                  ].map(({ key, label, fieldKey, suffix }) => (
                    <div
                      key={key}
                      style={{
                        display: 'grid',
                        gridTemplateColumns: '20px 1fr 80px 44px',
                        alignItems: 'center',
                        gap: 'var(--space-3)',
                        padding: 'var(--space-2) var(--space-3)',
                        borderRadius: 'var(--radius-md)',
                        border: '1px solid var(--color-border)',
                        backgroundColor: quickNotes[key].enabled ? 'var(--color-primary-subtle)' : 'transparent',
                        borderColor: quickNotes[key].enabled ? 'var(--color-primary)' : 'var(--color-border)',
                        transition: 'background-color 0.15s, border-color 0.15s',
                      }}
                    >
                      <input
                        type="checkbox"
                        checked={quickNotes[key].enabled}
                        onChange={e => setQuickNote(key, 'enabled', e.target.checked)}
                        style={{ cursor: 'pointer', accentColor: 'var(--color-primary)' }}
                      />
                      <span style={{
                        fontSize: 'var(--font-size-sm)',
                        color: quickNotes[key].enabled ? 'var(--color-text-primary)' : 'var(--color-text-muted)',
                      }}>
                        {label}
                      </span>
                      <CellInput
                        type="number"
                        value={quickNotes[key][fieldKey]}
                        onChange={v => setQuickNote(key, fieldKey, v)}
                        min={1} step={1}
                        style={{ textAlign: 'right', opacity: quickNotes[key].enabled ? 1 : 0.4 }}
                      />
                      <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', whiteSpace: 'nowrap' }}>{suffix}</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Dynamic comments */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
                {form.comments.map((comment, idx) => (
                  <div key={idx} style={{ display: 'flex', gap: 'var(--space-2)', alignItems: 'flex-start' }}>
                    <textarea
                      value={comment}
                      onChange={e => setComment(idx, e.target.value)}
                      rows={2}
                      placeholder="Note text…"
                      className="input textarea"
                      style={{ flex: 1, resize: 'vertical', fontSize: 'var(--font-size-sm)' }}
                    />
                    <button
                      onClick={() => removeComment(idx)}
                      style={{
                        marginTop: 2,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        width: 28, height: 28,
                        borderRadius: 'var(--radius-md)',
                        border: '1px solid var(--color-border)',
                        backgroundColor: 'transparent',
                        cursor: 'pointer',
                        color: 'var(--color-text-muted)',
                        flexShrink: 0,
                      }}
                      onMouseEnter={e => {
                        e.currentTarget.style.color = 'var(--color-danger)'
                        e.currentTarget.style.borderColor = 'rgba(255,92,92,0.4)'
                        e.currentTarget.style.backgroundColor = 'var(--color-danger-bg)'
                      }}
                      onMouseLeave={e => {
                        e.currentTarget.style.color = 'var(--color-text-muted)'
                        e.currentTarget.style.borderColor = 'var(--color-border)'
                        e.currentTarget.style.backgroundColor = 'transparent'
                      }}
                    >
                      <Icon name="close" size={12} />
                    </button>
                  </div>
                ))}
              </div>

              {/* Empty state + Add Note — on same line */}
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'var(--space-3)' }}>
                {form.comments.length === 0 && (
                  <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
                    No notes. Click &quot;+ Add Note&quot; to add one.
                  </span>
                )}
                <div style={{ marginLeft: 'auto' }}>
                  <Button variant="ghost" size="sm" onClick={addComment}>+ Add Note</Button>
                </div>
              </div>
          </Card>

        </div>{/* end RIGHT */}
      </div>

      {/* ── Modals ──────────────────────────────────────────────────────── */}
      {showProductModal && (
        <ProductSearchModal
          onSelect={addProductFromCatalogue}
          onClose={() => setShowProductModal(false)}
        />
      )}
    </div>
  )
}
