import { useState, useMemo } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import {
  useCompany,
  useDeleteCompany,
  useUpdateCompany,
  useCompanyVouchers,
  useRefreshCompanyVouchers,
  useLinkLexwareCompany,
  useUnlinkLexwareCompany,
  useSyncFromLexware,
  usePushToLexware,
  useEnrichCompany,
} from '../hooks';
import { useCrmSettings } from '../settings/CrmSettingsContext';
import { CompanyFormModal } from './CompanyFormModal';
import { ActivityFeed } from './ActivityFeed';
import { CompanyRelationshipsCard } from './CompanyRelationshipsCard';
import { ContractsCard } from './ContractsCard';
import { LexwareSearchModal } from '../lexware/LexwareSearchModal';
import { CustomFieldsDisplay } from '../CustomFieldsDisplay';
import { Modal } from '../../components/Modal';
import type { DealStatus, LexwareVoucher, Deal, EnrichmentSuggestion } from '../types';
import { VOUCHER_TYPE_LABELS } from '../types';
import styles from './CompanyDetailPage.module.css';

// ============================================================
//  Types
// ============================================================

type DetailTab = 'company' | 'activities' | 'deals' | 'contracts';
type SourceFilter = 'ALL' | 'CRM' | 'LEXWARE';

interface UnifiedItem {
  id: string;
  source: 'CRM' | 'LEXWARE';
  title: string;
  type: string;
  date: string | null;
  status: string;
  statusColor?: { bg: string; color: string };
  amount: number | null;
  currency: string;
  link: string;
  openExternal?: boolean;
  stageColor?: string;
}

// ============================================================
//  Constants & Helpers
// ============================================================

const TAB_LABELS: Record<DetailTab, string> = {
  company: 'Unternehmen',
  activities: 'Aktivitäten',
  deals: 'Vorgänge',
  contracts: 'Verträge',
};

const STATUS_COLORS: Record<DealStatus, { bg: string; color: string }> = {
  OPEN: { bg: '#dbeafe', color: '#1e40af' },
  WON: { bg: '#d1fae5', color: '#065f46' },
  LOST: { bg: '#fee2e2', color: '#991b1b' },
};

const STATUS_LABELS: Record<DealStatus, string> = {
  OPEN: 'Offen',
  WON: 'Gewonnen',
  LOST: 'Verloren',
};

const currencyFormatter = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',
});

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  });
}

// ============================================================
//  Page Component
// ============================================================

export function CompanyDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { isModuleEnabled } = useCrmSettings();
  const lexwareEnabled = isModuleEnabled('lexware');

  // ---- Core data ----
  const { data, isLoading, error } = useCompany(id!);
  const deleteMutation = useDeleteCompany();

  // ---- UI State ----
  const [activeTab, setActiveTab] = useState<DetailTab>('company');
  const [isEditOpen, setEditOpen] = useState(false);
  const [isDeleteOpen, setDeleteOpen] = useState(false);
  const [isLexwareSearchOpen, setLexwareSearchOpen] = useState(false);
  const [isEnrichOpen, setEnrichOpen] = useState(false);
  const [enrichSuggestions, setEnrichSuggestions] = useState<EnrichmentSuggestion[]>([]);
  const [sourceFilter, setSourceFilter] = useState<SourceFilter>('ALL');
  const [typeFilter, setTypeFilter] = useState('');

  // ---- Lexware Mutations (must be called before conditional returns) ----
  const linkCompany = useLinkLexwareCompany();
  const unlinkCompany = useUnlinkLexwareCompany();
  const syncFromLexware = useSyncFromLexware();
  const pushToLexware = usePushToLexware();
  const refreshVouchers = useRefreshCompanyVouchers();
  const enrichCompany = useEnrichCompany();
  const updateCompany = useUpdateCompany();

  // ---- Lexware Vouchers ----
  const companyData = data?.data;
  const isLinked = !!companyData?.lexwareContactId;

  const vouchersQuery = useCompanyVouchers(
    id!,
    isLinked && lexwareEnabled ? { pageSize: 100 } : undefined,
  );

  // ---- Loading / Error ----
  if (isLoading) return <p>Laden...</p>;
  if (error || !data)
    return (
      <p style={{ color: 'var(--color-error)' }}>
        Unternehmen konnte nicht geladen werden
      </p>
    );

  const company = data.data;
  const contacts = company.contacts ?? [];
  const deals = company.deals ?? [];
  const vouchers: LexwareVoucher[] = vouchersQuery.data?.data ?? [];

  // Industry badge
  const industryColor = company.industryRef?.color ?? '#6366f1';
  const industryName = company.industryRef?.name ?? company.industry;

  // Lexware mutation state
  const isAnyLexwareMutating =
    linkCompany.isPending ||
    unlinkCompany.isPending ||
    syncFromLexware.isPending ||
    pushToLexware.isPending ||
    refreshVouchers.isPending;

  return (
    <div>
      {/* Zurück */}
      <Link to="/crm/companies" className={styles.backLink}>
        <svg
          width="14"
          height="14"
          viewBox="0 0 14 14"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
        >
          <path d="M9 2L4 7l5 5" />
        </svg>
        Zurück zu Unternehmen
      </Link>

      {/* Header */}
      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.name}>{company.name}</h1>
          {industryName && (
            <span
              className={styles.industryBadge}
              style={{ backgroundColor: industryColor }}
            >
              {industryName}
            </span>
          )}
          <span
            style={{
              display: 'inline-block',
              width: 8,
              height: 8,
              borderRadius: '50%',
              background: company.isActive
                ? 'var(--color-success)'
                : 'var(--color-error)',
            }}
            title={company.isActive ? 'Aktiv' : 'Inaktiv'}
          />
        </div>
        <div style={{ display: 'flex', gap: '0.5rem' }}>
          <button
            onClick={() => {
              enrichCompany.mutate(company.id, {
                onSuccess: (res) => {
                  // Backend gibt suggestions als Record<field, {current, suggested, source}> zurück
                  const suggestions = Object.entries(res.data.suggestions).map(
                    ([field, s]) => ({ field, ...s }),
                  );
                  setEnrichSuggestions(suggestions);
                  setEnrichOpen(true);
                },
              });
            }}
            disabled={enrichCompany.isPending}
            style={{
              padding: '0.375rem 0.75rem',
              fontSize: '0.8125rem',
              background: 'transparent',
              border: '1px solid #a5b4fc',
              borderRadius: 'var(--radius-sm)',
              cursor: enrichCompany.isPending ? 'wait' : 'pointer',
              color: '#4f46e5',
              opacity: enrichCompany.isPending ? 0.6 : 1,
            }}
          >
            {enrichCompany.isPending ? 'Anreichern...' : 'Anreichern'}
          </button>
          <button
            onClick={() => setEditOpen(true)}
            style={{
              padding: '0.375rem 0.75rem',
              fontSize: '0.8125rem',
              background: 'transparent',
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-sm)',
              cursor: 'pointer',
              color: 'var(--color-text-secondary)',
            }}
          >
            Bearbeiten
          </button>
          <button
            onClick={() => setDeleteOpen(true)}
            style={{
              padding: '0.375rem 0.75rem',
              fontSize: '0.8125rem',
              background: 'transparent',
              border: '1px solid #fecaca',
              borderRadius: 'var(--radius-sm)',
              cursor: 'pointer',
              color: 'var(--color-error)',
            }}
          >
            Löschen
          </button>
        </div>
      </div>

      {/* ======== Tab Bar ======== */}
      <div className={styles.tabBar}>
        {(Object.keys(TAB_LABELS) as DetailTab[]).map((tab) => (
          <button
            key={tab}
            className={`${styles.tab} ${activeTab === tab ? styles.tabActive : ''}`}
            onClick={() => setActiveTab(tab)}
          >
            {TAB_LABELS[tab]}
          </button>
        ))}
      </div>

      {/* ======== Tab Content ======== */}
      <div className={styles.tabContent}>
        {/* ---- Tab 1: Unternehmensdaten ---- */}
        {activeTab === 'company' && (
          <div className={styles.overviewGrid}>
            {/* Left: Stammdaten */}
            <div>
              <div className={styles.card}>
                <h2 className={styles.cardTitle}>Unternehmensdaten</h2>
                <div className={styles.infoGrid}>
                  {company.accountType && (
                    <>
                      <span className={styles.infoLabel}>Kontotyp</span>
                      <span className={styles.infoValue}>{company.accountType.name}</span>
                    </>
                  )}
                  {company.ownerName && (
                    <>
                      <span className={styles.infoLabel}>Zuständig</span>
                      <span className={styles.infoValue}>{company.ownerName}</span>
                    </>
                  )}
                  {company.email && (
                    <>
                      <span className={styles.infoLabel}>E-Mail</span>
                      <span className={styles.infoValue}>
                        <a
                          href={`mailto:${company.email}`}
                          style={{ color: 'var(--color-primary)' }}
                        >
                          {company.email}
                        </a>
                      </span>
                    </>
                  )}
                  {company.phone && (
                    <>
                      <span className={styles.infoLabel}>Telefon</span>
                      <span className={styles.infoValue}>{company.phone}</span>
                    </>
                  )}
                  {company.website && (
                    <>
                      <span className={styles.infoLabel}>Website</span>
                      <span className={styles.infoValue}>
                        <a
                          href={company.website}
                          target="_blank"
                          rel="noopener noreferrer"
                          style={{ color: 'var(--color-primary)' }}
                        >
                          {company.website}
                        </a>
                      </span>
                    </>
                  )}
                  {(company.street || company.zip || company.city) && (
                    <>
                      <span className={styles.infoLabel}>Adresse</span>
                      <span className={styles.infoValue}>
                        {company.street && <>{company.street}<br /></>}
                        {company.zip} {company.city}
                        {company.country && company.country !== 'DE' && (
                          <>, {company.country}</>
                        )}
                      </span>
                    </>
                  )}
                  {(company.deliveryStreet || company.deliveryZip || company.deliveryCity) && (
                    <>
                      <span className={styles.infoLabel}>Lieferadresse</span>
                      <span className={styles.infoValue}>
                        {company.deliveryStreet && <>{company.deliveryStreet}<br /></>}
                        {company.deliveryZip} {company.deliveryCity}
                        {company.deliveryCountry && company.deliveryCountry !== 'DE' && (
                          <>, {company.deliveryCountry}</>
                        )}
                      </span>
                    </>
                  )}
                  {company.vatId && (
                    <>
                      <span className={styles.infoLabel}>USt-IdNr.</span>
                      <span className={styles.infoValue}>{company.vatId}</span>
                    </>
                  )}
                  {company.taxId && (
                    <>
                      <span className={styles.infoLabel}>Steuernummer</span>
                      <span className={styles.infoValue}>{company.taxId}</span>
                    </>
                  )}
                  {company.tradeRegisterNumber && (
                    <>
                      <span className={styles.infoLabel}>Handelsregister</span>
                      <span className={styles.infoValue}>
                        {company.tradeRegisterNumber}
                        {company.registerCourt && (
                          <span style={{ color: 'var(--color-text-muted)' }}> ({company.registerCourt})</span>
                        )}
                      </span>
                    </>
                  )}
                  {company.companySize && (
                    <>
                      <span className={styles.infoLabel}>Groesse</span>
                      <span className={styles.infoValue}>
                        {{'SIZE_1_10': '1–10', 'SIZE_11_50': '11–50', 'SIZE_51_200': '51–200', 'SIZE_201_500': '201–500', 'SIZE_500_PLUS': '500+'}[company.companySize] ?? company.companySize} Mitarbeiter
                      </span>
                    </>
                  )}
                  {company.dataEnrichedAt && (
                    <>
                      <span className={styles.infoLabel}>Datenanreicherung</span>
                      <span className={styles.infoValue} style={{ fontSize: '0.8125rem', color: 'var(--color-text-muted)' }}>
                        {new Date(company.dataEnrichedAt).toLocaleDateString('de-DE')}
                        {company.dataEnrichedSource && ` (${company.dataEnrichedSource})`}
                      </span>
                    </>
                  )}
                  <span className={styles.infoLabel}>Erstellt</span>
                  <span className={styles.infoValue}>
                    {formatDate(company.createdAt)}
                  </span>
                </div>

                {/* Tags */}
                {company.tags && company.tags.length > 0 && (
                  <div style={{ marginTop: '1rem' }}>
                    <span
                      className={styles.infoLabel}
                      style={{ display: 'block', marginBottom: '0.375rem' }}
                    >
                      Tags
                    </span>
                    <div className={styles.tags}>
                      {company.tags.map((tag) => (
                        <span key={tag} className={styles.tag}>
                          {tag}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

                {/* Notizen */}
                {company.notes && (
                  <div className={styles.notesSection}>
                    <span
                      className={styles.infoLabel}
                      style={{ display: 'block', marginBottom: '0.375rem' }}
                    >
                      Notizen
                    </span>
                    <p className={styles.notesText}>{company.notes}</p>
                  </div>
                )}

                {/* Custom Fields */}
                {company.customFields && company.customFields.length > 0 && (
                  <CustomFieldsDisplay fields={company.customFields} />
                )}

                {/* Lexware Verknüpfung */}
                {lexwareEnabled && (
                  <div className={styles.lexwareInfo}>
                    <div className={styles.lexwareStatusRow}>
                      <span
                        className={`${styles.lexwareBadge} ${
                          isLinked ? styles.lexwareBadgeLinked : styles.lexwareBadgeNotLinked
                        }`}
                      >
                        <span
                          style={{
                            width: 6,
                            height: 6,
                            borderRadius: '50%',
                            background: isLinked ? '#059669' : 'var(--color-text-muted)',
                            display: 'inline-block',
                          }}
                        />
                        LX {isLinked ? 'Verknüpft' : 'Nicht verknüpft'}
                      </span>
                      {isLinked && company.lexwareSyncedAt && (
                        <span style={{ fontSize: '0.6875rem', color: 'var(--color-text-muted)' }}>
                          Sync: {formatDate(company.lexwareSyncedAt)}
                        </span>
                      )}
                    </div>
                    <div className={styles.lexwareActions}>
                      {!isLinked ? (
                        <button
                          className={styles.lexwareActionBtnPrimary}
                          onClick={() => setLexwareSearchOpen(true)}
                          disabled={isAnyLexwareMutating}
                        >
                          Lexware Kontakt suchen
                        </button>
                      ) : (
                        <>
                          <button
                            className={styles.lexwareActionBtn}
                            onClick={() => syncFromLexware.mutate({ entityType: 'company', entityId: company.id })}
                            disabled={isAnyLexwareMutating}
                          >
                            {syncFromLexware.isPending ? 'Sync...' : 'Sync'}
                          </button>
                          <button
                            className={styles.lexwareActionBtn}
                            onClick={() => pushToLexware.mutate({ entityType: 'company', entityId: company.id })}
                            disabled={isAnyLexwareMutating}
                          >
                            {pushToLexware.isPending ? 'Push...' : 'Push'}
                          </button>
                          <button
                            className={styles.lexwareActionBtnDanger}
                            onClick={() => unlinkCompany.mutate(company.id)}
                            disabled={isAnyLexwareMutating}
                          >
                            {unlinkCompany.isPending ? 'Trennen...' : 'Trennen'}
                          </button>
                        </>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Right: Kontakte + Beziehungen */}
            <div className={styles.rightStack}>
              {/* Kontakte */}
              <div className={styles.card}>
                <div className={styles.cardTitleRow}>
                  <h2 className={styles.cardTitle} style={{ marginBottom: 0 }}>
                    Kontakte ({company._count?.contacts ?? contacts.length})
                  </h2>
                </div>
                {contacts.length === 0 ? (
                  <p style={{ color: 'var(--color-text-muted)', fontSize: '0.8125rem' }}>
                    Keine Kontakte vorhanden
                  </p>
                ) : (
                  <table className={styles.compactTable}>
                    <thead>
                      <tr>
                        <th>Name</th>
                        <th>Position</th>
                      </tr>
                    </thead>
                    <tbody>
                      {contacts.map((c) => {
                        const cName = [c.firstName, c.lastName]
                          .filter(Boolean)
                          .join(' ') || '—';
                        return (
                          <tr
                            key={c.id}
                            data-clickable="true"
                            onClick={() => navigate(`/crm/contacts/${c.id}`)}
                          >
                            <td style={{ fontWeight: 500 }}>{cName}</td>
                            <td style={{ color: 'var(--color-text-secondary)' }}>
                              {c.position ?? '—'}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                )}
              </div>

              {/* Beziehungen */}
              <CompanyRelationshipsCard companyId={company.id} />
            </div>
          </div>
        )}

        {/* ---- Tab 2: Aktivitäten ---- */}
        {activeTab === 'activities' && (
          <div style={{ maxWidth: 800 }}>
            <ActivityFeed companyId={company.id} />
          </div>
        )}

        {/* ---- Tab 3: Vorgänge ---- */}
        {activeTab === 'deals' && (
          <VorgaengeTab
            deals={deals}
            vouchers={vouchers}
            isLoadingVouchers={vouchersQuery.isLoading}
            isLinked={isLinked}
            lexwareEnabled={lexwareEnabled}
            companyId={company.id}
            refreshVouchers={refreshVouchers}
            sourceFilter={sourceFilter}
            setSourceFilter={setSourceFilter}
            typeFilter={typeFilter}
            setTypeFilter={setTypeFilter}
            navigate={navigate}
          />
        )}

        {/* ---- Tab 4: Verträge ---- */}
        {activeTab === 'contracts' && (
          <ContractsCard companyId={company.id} />
        )}
      </div>

      {/* ======== Modals ======== */}
      <CompanyFormModal
        isOpen={isEditOpen}
        onClose={() => setEditOpen(false)}
        company={company}
        onSuccess={() => setEditOpen(false)}
      />

      <LexwareSearchModal
        isOpen={isLexwareSearchOpen}
        onClose={() => setLexwareSearchOpen(false)}
        onLink={(lexwareId) => {
          linkCompany.mutate(
            { lexwareContactId: lexwareId, companyId: company.id },
            { onSuccess: () => setLexwareSearchOpen(false) },
          );
        }}
        isLinking={linkCompany.isPending}
      />

      {/* Enrichment Suggestions Modal */}
      <Modal
        isOpen={isEnrichOpen}
        onClose={() => setEnrichOpen(false)}
        title="Datenanreicherung — Vorschläge"
        maxWidth="600px"
      >
        {enrichSuggestions.length === 0 ? (
          <p style={{ color: 'var(--color-text-muted)', fontSize: '0.875rem' }}>
            Keine neuen Vorschläge vorhanden.
          </p>
        ) : (
          <div>
            <p style={{ fontSize: '0.8125rem', color: 'var(--color-text-muted)', marginBottom: '1rem' }}>
              Folgende Daten wurden gefunden. Klicke auf &quot;Übernehmen&quot;, um einzelne Vorschläge zu übernehmen.
            </p>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.8125rem' }}>
              <thead>
                <tr style={{ borderBottom: '1px solid var(--color-border)' }}>
                  <th style={{ padding: '0.5rem', textAlign: 'left', fontWeight: 600 }}>Feld</th>
                  <th style={{ padding: '0.5rem', textAlign: 'left', fontWeight: 600 }}>Aktuell</th>
                  <th style={{ padding: '0.5rem', textAlign: 'left', fontWeight: 600 }}>Vorschlag</th>
                  <th style={{ padding: '0.5rem', textAlign: 'left', fontWeight: 600 }}>Quelle</th>
                  <th style={{ padding: '0.5rem', width: '80px' }}></th>
                </tr>
              </thead>
              <tbody>
                {enrichSuggestions.map((s, i) => (
                  <tr key={i} style={{ borderBottom: '1px solid var(--color-border)' }}>
                    <td style={{ padding: '0.5rem', fontWeight: 500 }}>{s.field}</td>
                    <td style={{ padding: '0.5rem', color: 'var(--color-text-muted)' }}>
                      {s.current ?? '—'}
                    </td>
                    <td style={{ padding: '0.5rem', color: '#4f46e5', fontWeight: 500 }}>
                      {s.suggested ?? '—'}
                    </td>
                    <td style={{ padding: '0.5rem', fontSize: '0.75rem', color: 'var(--color-text-muted)' }}>
                      {s.source}
                    </td>
                    <td style={{ padding: '0.5rem' }}>
                      {s.suggested && (
                        <button
                          onClick={() => {
                            updateCompany.mutate(
                              { id: company.id, data: { [s.field]: s.suggested } },
                              {
                                onSuccess: () => {
                                  setEnrichSuggestions((prev) =>
                                    prev.filter((_, idx) => idx !== i),
                                  );
                                },
                              },
                            );
                          }}
                          disabled={updateCompany.isPending}
                          style={{
                            padding: '0.25rem 0.5rem',
                            fontSize: '0.75rem',
                            background: '#4f46e5',
                            color: 'white',
                            border: 'none',
                            borderRadius: 'var(--radius-sm)',
                            cursor: 'pointer',
                            whiteSpace: 'nowrap',
                          }}
                        >
                          Übernehmen
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '1rem' }}>
          <button
            onClick={() => setEnrichOpen(false)}
            style={{
              padding: '0.5rem 1rem',
              background: 'transparent',
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              cursor: 'pointer',
              color: 'var(--color-text-secondary)',
            }}
          >
            Schließen
          </button>
        </div>
      </Modal>

      <Modal
        isOpen={isDeleteOpen}
        onClose={() => setDeleteOpen(false)}
        title="Unternehmen löschen"
        maxWidth="420px"
      >
        <p
          style={{
            fontSize: '0.9375rem',
            color: 'var(--color-text)',
            marginBottom: '0.5rem',
          }}
        >
          Soll das Unternehmen <strong>{company.name}</strong> wirklich gelöscht
          werden?
        </p>
        <p
          style={{
            fontSize: '0.8125rem',
            color: 'var(--color-error)',
            marginBottom: '1.5rem',
          }}
        >
          Verknüpfte Kontakte und Vorgänge verlieren die Zuordnung.
        </p>
        <div
          style={{
            display: 'flex',
            justifyContent: 'flex-end',
            gap: '0.75rem',
          }}
        >
          <button
            onClick={() => setDeleteOpen(false)}
            disabled={deleteMutation.isPending}
            style={{
              padding: '0.5rem 1rem',
              background: 'transparent',
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              cursor: 'pointer',
              color: 'var(--color-text-secondary)',
            }}
          >
            Abbrechen
          </button>
          <button
            onClick={() =>
              deleteMutation.mutate(company.id, {
                onSuccess: () => navigate('/crm/companies'),
              })
            }
            disabled={deleteMutation.isPending}
            style={{
              padding: '0.5rem 1rem',
              background: 'var(--color-error)',
              color: 'white',
              border: 'none',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              fontWeight: 600,
              cursor: deleteMutation.isPending ? 'wait' : 'pointer',
              opacity: deleteMutation.isPending ? 0.7 : 1,
            }}
          >
            {deleteMutation.isPending ? 'Löschen...' : 'Endgültig löschen'}
          </button>
        </div>
      </Modal>
    </div>
  );
}

// ============================================================
//  VorgaengeTab — CRM Deals + Lexware Belege kombiniert
// ============================================================

function VorgaengeTab({
  deals,
  vouchers,
  isLoadingVouchers,
  isLinked,
  lexwareEnabled,
  companyId,
  refreshVouchers,
  sourceFilter,
  setSourceFilter,
  typeFilter,
  setTypeFilter,
  navigate,
}: {
  deals: Deal[];
  vouchers: LexwareVoucher[];
  isLoadingVouchers: boolean;
  isLinked: boolean;
  lexwareEnabled: boolean;
  companyId: string;
  refreshVouchers: ReturnType<typeof useRefreshCompanyVouchers>;
  sourceFilter: SourceFilter;
  setSourceFilter: (v: SourceFilter) => void;
  typeFilter: string;
  setTypeFilter: (v: string) => void;
  navigate: ReturnType<typeof useNavigate>;
}) {
  // Map CRM deals to unified format
  const crmItems: UnifiedItem[] = useMemo(
    () =>
      deals.map((deal) => ({
        id: `crm-${deal.id}`,
        source: 'CRM' as const,
        title: deal.title,
        type: deal.stage?.name ?? deal.pipeline?.name ?? '—',
        date: deal.createdAt,
        status: STATUS_LABELS[deal.status] ?? deal.status,
        statusColor: STATUS_COLORS[deal.status],
        amount: deal.value ? parseFloat(deal.value) : null,
        currency: deal.currency ?? 'EUR',
        link: `/crm/deals/${deal.id}`,
        stageColor: deal.stage?.color,
      })),
    [deals],
  );

  // Map Lexware vouchers to unified format
  const lexwareItems: UnifiedItem[] = useMemo(
    () =>
      vouchers.map((v) => ({
        id: `lx-${v.id}`,
        source: 'LEXWARE' as const,
        title: v.title || v.voucherNumber || '—',
        type: VOUCHER_TYPE_LABELS[v.voucherType] ?? v.voucherType,
        date: v.voucherDate,
        status: v.voucherStatus ?? '—',
        amount: v.totalGrossAmount ? parseFloat(v.totalGrossAmount) : null,
        currency: v.currency ?? 'EUR',
        link: v.lexwareDeepLink ?? '#',
        openExternal: true,
      })),
    [vouchers],
  );

  // Merge + sort by date descending
  const allItems = useMemo(() => {
    let items = [...crmItems, ...lexwareItems];

    // Source filter
    if (sourceFilter === 'CRM') items = items.filter((i) => i.source === 'CRM');
    if (sourceFilter === 'LEXWARE') items = items.filter((i) => i.source === 'LEXWARE');

    // Type filter
    if (typeFilter) items = items.filter((i) => i.type === typeFilter);

    // Sort by date (newest first)
    items.sort((a, b) => {
      if (!a.date && !b.date) return 0;
      if (!a.date) return 1;
      if (!b.date) return -1;
      return new Date(b.date).getTime() - new Date(a.date).getTime();
    });

    return items;
  }, [crmItems, lexwareItems, sourceFilter, typeFilter]);

  // Collect all unique types for filter dropdown
  const allTypes = useMemo(() => {
    const types = new Set<string>();
    [...crmItems, ...lexwareItems].forEach((i) => {
      if (i.type && i.type !== '—') types.add(i.type);
    });
    return Array.from(types).sort();
  }, [crmItems, lexwareItems]);

  return (
    <div>
      {/* Filter + Actions */}
      <div className={styles.vorgaengeHeader}>
        <div className={styles.filterRow}>
          <select
            className={styles.filterSelect}
            value={sourceFilter}
            onChange={(e) => setSourceFilter(e.target.value as SourceFilter)}
          >
            <option value="ALL">Alle Quellen</option>
            <option value="CRM">Nur CRM</option>
            <option value="LEXWARE">Nur Lexware</option>
          </select>
          <select
            className={styles.filterSelect}
            value={typeFilter}
            onChange={(e) => setTypeFilter(e.target.value)}
          >
            <option value="">Alle Typen</option>
            {allTypes.map((t) => (
              <option key={t} value={t}>
                {t}
              </option>
            ))}
          </select>
        </div>
        {isLinked && lexwareEnabled && (
          <button
            className={styles.refreshBtn}
            onClick={() => refreshVouchers.mutate(companyId)}
            disabled={refreshVouchers.isPending}
          >
            <svg
              width="14"
              height="14"
              viewBox="0 0 16 16"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path d="M1 1v5h5M15 15v-5h-5" />
              <path d="M13.5 6A6 6 0 003.3 3.3L1 6M2.5 10a6 6 0 0010.2 2.7L15 10" />
            </svg>
            {refreshVouchers.isPending ? 'Aktualisieren...' : 'Belege aktualisieren'}
          </button>
        )}
      </div>

      {/* Loading */}
      {isLoadingVouchers && isLinked && (
        <p style={{ color: 'var(--color-text-muted)', fontSize: '0.8125rem', marginBottom: '1rem' }}>
          Lexware Belege werden geladen...
        </p>
      )}

      {/* Tabelle */}
      <div className={styles.vorgaengeTableCard}>
        <table className={styles.vorgaengeTable}>
          <thead>
            <tr>
              <th style={{ width: 60 }}>Quelle</th>
              <th>Bezeichnung</th>
              <th>Typ</th>
              <th>Datum</th>
              <th>Status</th>
              <th style={{ textAlign: 'right' }}>Betrag</th>
            </tr>
          </thead>
          <tbody>
            {allItems.length === 0 && (
              <tr>
                <td colSpan={6} className={styles.emptyRow}>
                  Keine Vorgänge oder Belege vorhanden
                </td>
              </tr>
            )}
            {allItems.map((item) => (
              <tr
                key={item.id}
                className={item.source === 'LEXWARE' ? styles.lexwareRow : undefined}
                onClick={() => {
                  if (item.openExternal) {
                    window.open(item.link, '_blank', 'noopener,noreferrer');
                  } else {
                    navigate(item.link);
                  }
                }}
              >
                {/* Quelle */}
                <td>
                  <span
                    className={`${styles.sourceBadge} ${
                      item.source === 'LEXWARE'
                        ? styles.sourceBadgeLexware
                        : styles.sourceBadgeCrm
                    }`}
                  >
                    {item.source === 'LEXWARE' ? 'LX' : 'CRM'}
                  </span>
                </td>
                {/* Bezeichnung */}
                <td style={{ fontWeight: 500, color: 'var(--color-text)' }}>
                  {item.title}
                </td>
                {/* Typ */}
                <td>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.25rem' }}>
                    {item.stageColor && (
                      <span
                        style={{
                          width: 6,
                          height: 6,
                          borderRadius: '50%',
                          background: item.stageColor,
                          display: 'inline-block',
                        }}
                      />
                    )}
                    {item.type}
                  </span>
                </td>
                {/* Datum */}
                <td>{item.date ? formatDate(item.date) : '—'}</td>
                {/* Status */}
                <td>
                  {item.statusColor ? (
                    <span
                      style={{
                        display: 'inline-block',
                        padding: '0 0.375rem',
                        borderRadius: '9999px',
                        fontSize: '0.6875rem',
                        fontWeight: 500,
                        background: item.statusColor.bg,
                        color: item.statusColor.color,
                      }}
                    >
                      {item.status}
                    </span>
                  ) : (
                    <span style={{ fontSize: '0.8125rem' }}>{item.status}</span>
                  )}
                </td>
                {/* Betrag */}
                <td style={{ textAlign: 'right', fontWeight: 500, whiteSpace: 'nowrap' }}>
                  {item.amount != null
                    ? currencyFormatter.format(item.amount)
                    : '—'}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
