// frontend/src/modals/crm/SelectCustomerModal.jsx
// Pick a customer before creating a new 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'

export default function SelectCustomerModal({ onSelect, onClose }) {
  const [search, setSearch]         = useState('')
  const [allCustomers, setAll]      = useState([])
  const [loading, setLoading]       = useState(true)
  const [selected, setSelected]     = useState(null)

  useEffect(() => {
    api.get('/crm/customers')
      .then(res => setAll(Array.isArray(res) ? res : (res.customers || [])))
      .catch(() => setAll([]))
      .finally(() => setLoading(false))
  }, [])

  const filtered = search.trim()
    ? allCustomers.filter(c => {
        const s = search.toLowerCase()
        const name = [c.title, c.name, c.surname].filter(Boolean).join(' ').toLowerCase()
        const org  = (c.organization || '').toLowerCase()
        return name.includes(s) || org.includes(s)
      })
    : allCustomers

  function handleConfirm() {
    if (selected) onSelect(selected)
  }

  return (
    <Modal
      open
      onClose={onClose}
      title="Select Customer"
      size="md"
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}>
          <Button variant="secondary" size="md" onClick={onClose}>
            Cancel
          </Button>
          <Button variant="primary" size="md" onClick={handleConfirm} disabled={!selected}>
            Continue
          </Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
        <SearchBar
          value={search}
          onChange={setSearch}
          placeholder="Search by name or organisation…"
        />

        <div style={{
          overflowY: 'auto',
          maxHeight: 380,
          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 customers match your search' : 'No customers found'}
            </div>
          )}

          {!loading && filtered.map((c, i) => {
            const name     = [c.title, c.name, c.surname].filter(Boolean).join(' ')
            const isActive = selected?.id === c.id
            return (
              <div
                key={c.id}
                role="button"
                tabIndex={0}
                onClick={() => setSelected(c)}
                onKeyDown={e => e.key === 'Enter' && setSelected(c)}
                onDoubleClick={() => { setSelected(c); onSelect(c) }}
                style={{
                  padding: 'var(--space-3) var(--space-4)',
                  cursor: 'pointer',
                  borderBottom: i < filtered.length - 1 ? '1px solid var(--color-border)' : 'none',
                  backgroundColor: isActive ? 'var(--color-primary-subtle)' : 'transparent',
                  borderLeft: isActive ? '2px solid var(--color-primary)' : '2px solid transparent',
                  transition: 'background-color 0.1s',
                  display: 'flex',
                  flexDirection: 'column',
                  gap: 'var(--space-1)',
                }}
                onMouseEnter={e => { if (!isActive) e.currentTarget.style.backgroundColor = 'var(--color-bg-elevated)' }}
                onMouseLeave={e => { if (!isActive) e.currentTarget.style.backgroundColor = 'transparent' }}
              >
                <div style={{
                  fontSize: 'var(--font-size-base)',
                  fontWeight: 'var(--font-weight-medium)',
                  color: isActive ? 'var(--color-primary)' : 'var(--color-text-primary)',
                }}>
                  {c.organization || name || '—'}
                </div>
                {c.organization && name && (
                  <div style={{
                    fontSize: 'var(--font-size-xs)',
                    color: 'var(--color-text-muted)',
                  }}>
                    {name}
                  </div>
                )}
              </div>
            )
          })}
        </div>

        {selected && (
          <div style={{
            fontSize: 'var(--font-size-sm)',
            color: 'var(--color-text-muted)',
            paddingLeft: 'var(--space-1)',
          }}>
            Selected: <span style={{ color: 'var(--color-text-primary)', fontWeight: 'var(--font-weight-medium)' }}>
              {selected.organization || [selected.title, selected.name, selected.surname].filter(Boolean).join(' ')}
            </span>
          </div>
        )}
      </div>
    </Modal>
  )
}
