import { useState } from 'react';
import { useOffice365Contacts, useIntegrations, useCreateContact } from '../crm/hooks';
import type { M365Contact, CreateContactPayload } from '../crm/types';
import styles from './DashboardContactsTab.module.css';

// ── Hilfsfunktionen ────────────────────────────────────────────────────────────

function getInitials(name: string): string {
  const parts = name.trim().split(/\s+/);
  if (parts.length >= 2) {
    return (
      (parts[0][0] ?? '') + (parts[parts.length - 1][0] ?? '')
    ).toUpperCase();
  }
  return name.substring(0, 2).toUpperCase();
}

const AVATAR_COLORS = [
  '#6366f1', '#8b5cf6', '#ec4899', '#f43f5e',
  '#f97316', '#eab308', '#22c55e', '#14b8a6',
  '#3b82f6', '#0ea5e9',
];

function getAvatarColor(name: string): string {
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }
  return AVATAR_COLORS[Math.abs(hash) % AVATAR_COLORS.length];
}

// ── Kontakt-Kachel ─────────────────────────────────────────────────────────────

function ContactCard({
  contact,
  onClick,
}: {
  contact: M365Contact;
  onClick: () => void;
}) {
  const initials = getInitials(contact.displayName);
  const color    = getAvatarColor(contact.displayName);
  const email    = contact.emailAddresses[0]?.address ?? null;
  const phone    = contact.mobilePhone ?? contact.businessPhones[0] ?? null;

  return (
    <div
      className={styles.card}
      onClick={onClick}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') onClick();
      }}
    >
      <div className={styles.cardAvatar} style={{ background: color }}>
        {initials}
      </div>
      <div className={styles.cardName}>{contact.displayName}</div>
      {contact.jobTitle   && <div className={styles.cardJobTitle}>{contact.jobTitle}</div>}
      {contact.companyName && <div className={styles.cardCompany}>{contact.companyName}</div>}
      {email && <div className={styles.cardEmail}>{email}</div>}
      {phone && <div className={styles.cardPhone}>{phone}</div>}
    </div>
  );
}

// ── Kontakt-Zeile ──────────────────────────────────────────────────────────────

function ContactRow({
  contact,
  onClick,
}: {
  contact: M365Contact;
  onClick: () => void;
}) {
  const initials = getInitials(contact.displayName);
  const color    = getAvatarColor(contact.displayName);
  const email    = contact.emailAddresses[0]?.address ?? null;
  const phone    = contact.mobilePhone ?? contact.businessPhones[0] ?? null;

  return (
    <div
      className={styles.row}
      onClick={onClick}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') onClick();
      }}
    >
      <div className={styles.rowAvatar} style={{ background: color }}>
        {initials}
      </div>
      <div className={styles.rowName}>{contact.displayName}</div>
      <div className={styles.rowMeta}>{contact.companyName ?? '—'}</div>
      <div className={styles.rowMeta}>{contact.jobTitle ?? '—'}</div>
      <div className={styles.rowMeta}>{email ?? '—'}</div>
      <div className={styles.rowMeta}>{phone ?? '—'}</div>
    </div>
  );
}

// ── Detail-Modal ───────────────────────────────────────────────────────────────

type ImportStatus = 'idle' | 'loading' | 'success' | 'error';

function ContactModal({
  contact,
  onClose,
}: {
  contact: M365Contact;
  onClose: () => void;
}) {
  const createContact = useCreateContact();
  const [importStatus, setImportStatus] = useState<ImportStatus>('idle');

  const initials = getInitials(contact.displayName);
  const color    = getAvatarColor(contact.displayName);
  const email    = contact.emailAddresses[0]?.address ?? null;

  const handleImport = async () => {
    if (importStatus === 'loading' || importStatus === 'success') return;
    if (importStatus === 'error') {
      setImportStatus('idle');
      return;
    }

    setImportStatus('loading');

    const parts     = contact.displayName.trim().split(/\s+/);
    const firstName = parts[0] ?? '';
    const lastName  = parts.length > 1 ? parts.slice(1).join(' ') : undefined;

    const payload: CreateContactPayload = {
      type:        'PERSON',
      firstName,
      lastName,
      email:       email ?? undefined,
      mobile:      contact.mobilePhone ?? undefined,
      phone:       contact.businessPhones[0] ?? undefined,
      position:    contact.jobTitle ?? undefined,
      companyName: contact.companyName ?? undefined,
    };

    try {
      await createContact.mutateAsync(payload);
      setImportStatus('success');
    } catch {
      setImportStatus('error');
    }
  };

  const importLabel =
    importStatus === 'loading' ? 'Importiere…'
    : importStatus === 'success' ? '✓ Importiert'
    : importStatus === 'error'   ? '✕ Fehler — Erneut versuchen'
    : 'CRM Import';

  return (
    <div
      className={styles.backdrop}
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className={styles.modal}>
        {/* Schliessen */}
        <button className={styles.modalClose} onClick={onClose} title="Schließen">
          <svg
            width="12"
            height="12"
            viewBox="0 0 12 12"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
          >
            <path d="M1 1l10 10M11 1L1 11" />
          </svg>
        </button>

        {/* Kopfzeile */}
        <div className={styles.modalHeader}>
          <div className={styles.modalAvatar} style={{ background: color }}>
            {initials}
          </div>
          <div>
            <h2 className={styles.modalName}>{contact.displayName}</h2>
            {contact.jobTitle    && <div className={styles.modalJobTitle}>{contact.jobTitle}</div>}
            {contact.companyName && <div className={styles.modalCompany}>{contact.companyName}</div>}
          </div>
        </div>

        {/* Kontaktdetails */}
        <div className={styles.modalDetails}>
          {contact.emailAddresses.map((ea, i) =>
            ea.address ? (
              <div key={i} className={styles.detailRow}>
                <span className={styles.detailLabel}>
                  {i === 0 ? 'E-Mail' : `E-Mail ${i + 1}`}
                </span>
                <a href={`mailto:${ea.address}`} className={styles.detailValue}>
                  {ea.address}
                </a>
              </div>
            ) : null,
          )}
          {contact.mobilePhone && (
            <div className={styles.detailRow}>
              <span className={styles.detailLabel}>Mobil</span>
              <a href={`tel:${contact.mobilePhone}`} className={styles.detailValue}>
                {contact.mobilePhone}
              </a>
            </div>
          )}
          {contact.businessPhones.map((p, i) => (
            <div key={i} className={styles.detailRow}>
              <span className={styles.detailLabel}>
                {contact.businessPhones.length > 1 ? `Telefon ${i + 1}` : 'Telefon'}
              </span>
              <a href={`tel:${p}`} className={styles.detailValue}>
                {p}
              </a>
            </div>
          ))}
          {/* Kein Kontaktdetail vorhanden */}
          {!email &&
            !contact.mobilePhone &&
            contact.businessPhones.length === 0 && (
              <p className={styles.detailEmpty}>Keine Kontaktdaten hinterlegt.</p>
            )}
        </div>

        {/* Footer: CRM Import */}
        <div className={styles.modalFooter}>
          <button
            className={`${styles.importBtn}
              ${importStatus === 'success' ? styles.importBtnSuccess : ''}
              ${importStatus === 'error'   ? styles.importBtnError   : ''}`}
            onClick={handleImport}
            disabled={importStatus === 'loading' || importStatus === 'success'}
          >
            {importLabel}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Hauptkomponente ────────────────────────────────────────────────────────────

export function DashboardContactsTab() {
  const { data: integrationsData } = useIntegrations();
  const { data, isLoading, isError } = useOffice365Contacts();
  const [search,   setSearch]   = useState('');
  const [viewMode, setViewMode] = useState<'cards' | 'list'>('cards');
  const [selected, setSelected] = useState<M365Contact | null>(null);

  const isConnected =
    integrationsData?.data?.some(
      (i) => i.provider === 'MICROSOFT_365' && i.connected,
    ) ?? false;

  /* ── Nicht verbunden ── */
  if (!isConnected) {
    return (
      <div className={styles.state}>
        <div className={styles.stateIcon}>📇</div>
        <p className={styles.stateTitle}>Microsoft 365 nicht verbunden</p>
        <p className={styles.stateSub}>
          Verbinde dein Microsoft-365-Konto im Profil, um deine Kontakte zu sehen.
        </p>
      </div>
    );
  }

  /* ── Laden ── */
  if (isLoading) {
    return <div className={styles.stateCenter}>Kontakte werden geladen…</div>;
  }

  /* ── Fehler ── */
  if (isError || !data) {
    return (
      <div className={styles.stateCenter} style={{ color: 'var(--color-error, #ef4444)' }}>
        Kontakte konnten nicht geladen werden.
      </div>
    );
  }

  const contacts = data.data ?? [];
  const q        = search.trim().toLowerCase();
  const filtered = q
    ? contacts.filter(
        (c) =>
          c.displayName.toLowerCase().includes(q) ||
          (c.companyName ?? '').toLowerCase().includes(q) ||
          c.emailAddresses.some((ea) => (ea.address ?? '').toLowerCase().includes(q)),
      )
    : contacts;

  return (
    <div className={styles.root}>
      {/* Toolbar */}
      <div className={styles.toolbar}>
        {/* Suche */}
        <div className={styles.searchWrap}>
          <svg
            className={styles.searchIcon}
            width="14"
            height="14"
            viewBox="0 0 14 14"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
          >
            <circle cx="6" cy="6" r="4" />
            <path d="M9 9l3 3" />
          </svg>
          <input
            type="text"
            className={styles.searchInput}
            placeholder="Name, E-Mail oder Firma suchen…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
          {search && (
            <button
              className={styles.searchClear}
              onClick={() => setSearch('')}
              title="Suche leeren"
            >
              ×
            </button>
          )}
        </div>

        {/* Ansicht-Toggle */}
        <div className={styles.viewToggle}>
          <button
            className={`${styles.viewBtn} ${viewMode === 'cards' ? styles.viewBtnActive : ''}`}
            onClick={() => setViewMode('cards')}
            title="Kachelansicht"
          >
            <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor">
              <rect x="0" y="0" width="6" height="6" rx="1" />
              <rect x="8" y="0" width="6" height="6" rx="1" />
              <rect x="0" y="8" width="6" height="6" rx="1" />
              <rect x="8" y="8" width="6" height="6" rx="1" />
            </svg>
          </button>
          <button
            className={`${styles.viewBtn} ${viewMode === 'list' ? styles.viewBtnActive : ''}`}
            onClick={() => setViewMode('list')}
            title="Listenansicht"
          >
            <svg
              width="14"
              height="14"
              viewBox="0 0 14 14"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
            >
              <path d="M1 3h12M1 7h12M1 11h12" />
            </svg>
          </button>
        </div>

        <span className={styles.count}>{filtered.length} Kontakte</span>
      </div>

      {/* Listenansicht-Header */}
      {viewMode === 'list' && (
        <div className={styles.listHeader}>
          <div /> {/* Avatar-Platz */}
          <div className={styles.listHeaderCell}>Name</div>
          <div className={styles.listHeaderCell}>Firma</div>
          <div className={styles.listHeaderCell}>Jobtitel</div>
          <div className={styles.listHeaderCell}>E-Mail</div>
          <div className={styles.listHeaderCell}>Telefon</div>
        </div>
      )}

      {/* Kacheln oder Liste */}
      <div className={viewMode === 'cards' ? styles.grid : styles.list}>
        {filtered.map((c) =>
          viewMode === 'cards' ? (
            <ContactCard key={c.id} contact={c} onClick={() => setSelected(c)} />
          ) : (
            <ContactRow key={c.id} contact={c} onClick={() => setSelected(c)} />
          ),
        )}
      </div>

      {/* Keine Ergebnisse */}
      {filtered.length === 0 && (
        <div className={styles.empty}>Keine Kontakte gefunden.</div>
      )}

      {/* Detail-Modal */}
      {selected && (
        <ContactModal contact={selected} onClose={() => setSelected(null)} />
      )}
    </div>
  );
}
