// frontend/src/modals/crm/ProductSearchModal.jsx
// Search & select a product from the catalogue to add to a quotation

import { useState, useEffect } from 'react'
import api from '@/lib/api'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import SearchBar from '@/components/ui/SearchBar'
import Spinner from '@/components/ui/Spinner'
import { fmtEuro } from '@/lib/formatters'

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

export default function ProductSearchModal({ onSelect, onClose }) {
  const [search, setSearch] = useState('')
  const [allProducts, setAllProducts] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    api.get('/crm/products')
      .then(res => setAllProducts(res.products || []))
      .catch(() => setAllProducts([]))
      .finally(() => setLoading(false))
  }, [])

  const filtered = search.trim()
    ? allProducts.filter(p =>
        (p.name_en || p.name || '').toLowerCase().includes(search.toLowerCase()) ||
        (p.name_gr || '').toLowerCase().includes(search.toLowerCase()) ||
        (p.sku || '').toLowerCase().includes(search.toLowerCase()),
      )
    : allProducts

  return (
    <Modal
      open
      onClose={onClose}
      title="Add from Catalogue"
      size="md"
      footer={
        <Button variant="secondary" size="md" onClick={onClose}>
          Cancel
        </Button>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
        <SearchBar
          value={search}
          onChange={setSearch}
          placeholder="Search products by name or SKU…"
        />

        <div style={{
          overflowY: 'auto',
          maxHeight: 340,
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border)',
          backgroundColor: 'var(--color-bg-abyss)',
        }}>
          {loading && (
            <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-6)' }}>
              <Spinner size="md" />
            </div>
          )}

          {!loading && filtered.length === 0 && (
            <div style={{
              padding: 'var(--space-6)',
              textAlign: 'center',
              color: 'var(--color-text-muted)',
              fontSize: 'var(--font-size-sm)',
            }}>
              {search.trim() ? 'No products match your search' : 'No products in catalogue'}
            </div>
          )}

          {filtered.map((p, i) => (
            <div
              key={p.id}
              role="button"
              tabIndex={0}
              onClick={() => onSelect(p)}
              onKeyDown={e => e.key === 'Enter' && onSelect(p)}
              style={{
                padding: 'var(--space-3) var(--space-4)',
                cursor: 'pointer',
                borderBottom: i < filtered.length - 1 ? '1px solid var(--color-border)' : 'none',
                transition: 'background-color 0.1s',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                gap: 'var(--space-3)',
              }}
              onMouseEnter={e => e.currentTarget.style.backgroundColor = 'var(--color-bg-elevated)'}
              onMouseLeave={e => e.currentTarget.style.backgroundColor = ''}
            >
              <div style={{ minWidth: 0 }}>
                <div style={{
                  fontSize: 'var(--font-size-base)',
                  fontWeight: 'var(--font-weight-medium)',
                  color: 'var(--color-text-primary)',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                }}>
                  {p.name_en || p.name}
                  {p.name_gr && p.name_gr !== (p.name_en || p.name) && (
                    <span style={{ color: 'var(--color-text-muted)', fontWeight: 400, marginLeft: 'var(--space-2)' }}>
                      / {p.name_gr}
                    </span>
                  )}
                </div>
                {p.sku && (
                  <div style={{
                    fontSize: 'var(--font-size-xs)',
                    fontFamily: 'var(--font-family-mono)',
                    color: 'var(--color-text-muted)',
                    marginTop: 2,
                  }}>
                    {p.sku}
                  </div>
                )}
              </div>
              <span style={{
                fontSize: 'var(--font-size-sm)',
                fontWeight: 'var(--font-weight-semibold)',
                color: 'var(--color-primary)',
                flexShrink: 0,
              }}>
                {fmt(p.price)}
              </span>
            </div>
          ))}
        </div>
      </div>
    </Modal>
  )
}
