import { useState, useEffect, useRef } from 'react';
import { Modal } from '../../components/Modal';
import { useLexwareContactSearch } from '../hooks';
import type { LexwareContact } from '../types';
import styles from './LexwareSection.module.css';

interface LexwareSearchModalProps {
  isOpen: boolean;
  onClose: () => void;
  onLink: (lexwareContactId: string) => void;
  isLinking: boolean;
}

/**
 * Extracts a display name from a LexwareContact.
 */
function lexwareDisplayName(c: LexwareContact): string {
  const companyName = c.company?.name;
  const personName = [c.person?.firstName, c.person?.lastName]
    .filter(Boolean)
    .join(' ');
  if (companyName && personName) return `${companyName} (${personName})`;
  return companyName || personName || 'Unbenannt';
}

/**
 * Extracts the primary email from a LexwareContact.
 */
function lexwareEmail(c: LexwareContact): string | null {
  const emails = c.emailAddresses;
  if (!emails) return null;
  return (
    emails.business?.[0] ??
    emails.office?.[0] ??
    emails.private?.[0] ??
    emails.other?.[0] ??
    null
  );
}

/**
 * Extracts the primary address as a single-line string.
 */
function lexwareAddress(c: LexwareContact): string | null {
  const addr = c.addresses?.billing?.[0] ?? c.addresses?.shipping?.[0];
  if (!addr) return null;
  const parts = [addr.street, [addr.zip, addr.city].filter(Boolean).join(' ')];
  return parts.filter(Boolean).join(', ') || null;
}

export function LexwareSearchModal({
  isOpen,
  onClose,
  onLink,
  isLinking,
}: LexwareSearchModalProps) {
  const [searchTerm, setSearchTerm] = useState('');
  const [debouncedTerm, setDebouncedTerm] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);

  // Reset search when modal opens
  useEffect(() => {
    if (isOpen) {
      setSearchTerm('');
      setDebouncedTerm('');
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  }, [isOpen]);

  // Debounce search input
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedTerm(searchTerm.trim());
    }, 400);
    return () => clearTimeout(timer);
  }, [searchTerm]);

  const { data, isLoading } = useLexwareContactSearch(
    { name: debouncedTerm },
    isOpen && debouncedTerm.length >= 2,
  );

  const results: LexwareContact[] = data?.data ?? [];

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="Lexware Kontakt suchen & verknüpfen"
      maxWidth="560px"
    >
      <input
        ref={inputRef}
        type="text"
        className={styles.searchInput}
        placeholder="Name oder Firma eingeben..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />

      <div className={styles.searchResults}>
        {debouncedTerm.length < 2 && (
          <p className={styles.loadingText}>
            Mindestens 2 Zeichen eingeben...
          </p>
        )}

        {debouncedTerm.length >= 2 && isLoading && (
          <p className={styles.loadingText}>Suche in Lexware...</p>
        )}

        {debouncedTerm.length >= 2 && !isLoading && results.length === 0 && (
          <p className={styles.loadingText}>
            Keine Ergebnisse gefunden
          </p>
        )}

        {results.map((contact) => {
          const email = lexwareEmail(contact);
          const address = lexwareAddress(contact);
          return (
            <div key={contact.id} className={styles.searchResultItem}>
              <div className={styles.searchResultInfo}>
                <div className={styles.searchResultName}>
                  {lexwareDisplayName(contact)}
                </div>
                <div className={styles.searchResultMeta}>
                  {email && <span>{email}</span>}
                  {email && address && <span> &middot; </span>}
                  {address && <span>{address}</span>}
                  {!email && !address && <span>Keine Details</span>}
                </div>
              </div>
              <button
                className={styles.searchResultBtn}
                disabled={isLinking}
                onClick={() => onLink(contact.id)}
              >
                {isLinking ? '...' : 'Verknüpfen'}
              </button>
            </div>
          );
        })}
      </div>
    </Modal>
  );
}
