// frontend/src/modals/devices/AssignCustomerModal.jsx
import { useState, useEffect, useCallback, useRef } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import Spinner from '@/components/ui/Spinner'
import api from '@/lib/api'

export default function AssignCustomerModal({ open, onClose, onSelect, deviceId }) {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState([])
  const [searching, setSearching] = useState(false)
  const inputRef = useRef(null)

  useEffect(() => {
    if (open) {
      setQuery('')
      setResults([])
      setTimeout(() => inputRef.current?.focus(), 80)
    }
  }, [open])

  const search = useCallback(
    async (q) => {
      setSearching(true)
      try {
        const data = await api.get(`/devices/${deviceId}/customer-search?q=${encodeURIComponent(q)}`)
        setResults(data.results || [])
      } catch {
        setResults([])
      } finally {
        setSearching(false)
      }
    },
    [deviceId]
  )

  useEffect(() => {
    if (!open) return
    const t = setTimeout(() => search(query), 250)
    return () => clearTimeout(t)
  }, [query, search, open])

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Assign to Customer"
      size="sm"
      footer={
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
        <div style={{ position: 'relative' }}>
          <input
            ref={inputRef}
            type="text"
            className="input"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search by name, email, phone, org, tags…"
          />
          {searching && (
            <span
              style={{
                position: 'absolute',
                right: 'var(--space-3)',
                top: '50%',
                transform: 'translateY(-50%)',
              }}
            >
              <Spinner size="sm" />
            </span>
          )}
        </div>

        <div
          style={{
            border: '1px solid var(--color-border)',
            borderRadius: 'var(--radius-md)',
            minHeight: '64px',
            maxHeight: '260px',
            overflowY: 'auto',
          }}
        >
          {results.length === 0 ? (
            <p
              style={{
                padding: 'var(--space-3)',
                fontSize: 'var(--font-size-sm)',
                color: 'var(--color-text-muted)',
              }}
            >
              {searching ? 'Searching…' : query ? 'No customers found.' : 'Type to search customers…'}
            </p>
          ) : (
            results.map((c) => (
              <button
                key={c.id}
                type="button"
                onClick={() => onSelect(c)}
                style={{
                  display: 'block',
                  width: '100%',
                  textAlign: 'left',
                  padding: 'var(--space-3)',
                  background: 'none',
                  border: 'none',
                  borderBottom: '1px solid var(--color-border)',
                  cursor: 'pointer',
                }}
                onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = 'var(--color-bg-island)' }}
                onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent' }}
              >
                <span
                  style={{
                    display: 'block',
                    fontSize: 'var(--font-size-sm)',
                    fontWeight: 'var(--font-weight-medium)',
                    color: 'var(--color-text-primary)',
                  }}
                >
                  {[c.name, c.surname].filter(Boolean).join(' ')}
                  {c.city && (
                    <span
                      style={{
                        color: 'var(--color-text-muted)',
                        fontWeight: 'var(--font-weight-normal)',
                        marginLeft: 'var(--space-2)',
                      }}
                    >
                      {c.city}
                    </span>
                  )}
                </span>
                {c.organization && (
                  <span
                    style={{
                      display: 'block',
                      fontSize: 'var(--font-size-sm)',
                      color: 'var(--color-text-muted)',
                    }}
                  >
                    {c.organization}
                  </span>
                )}
              </button>
            ))
          )}
        </div>
      </div>
    </Modal>
  )
}
