import { useState, useEffect } from 'react';
import { Link, Navigate } from 'react-router-dom';
import { useAuth } from '../../auth/AuthContext';
import { useCrmSettings } from '../settings/CrmSettingsContext';
import {
  useLexwareContacts,
  useImportLexwareAsCompany,
  useImportLexwareAsContact,
  useCreateContact,
  useCompanies,
  useContacts,
  usePushToLexware,
} from '../hooks';
import type {
  LexwareContact,
  LexwareContactPersonEntry,
  LexwareContactSearchParams,
  Company,
  Contact,
} from '../types';
import styles from './LexwareSyncPage.module.css';

// ============================================================
//  Helpers
// ============================================================

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';
}

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
  );
}

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;
}

function lexwareRoles(c: LexwareContact): string {
  const roles: string[] = [];
  if (c.roles?.customer) roles.push('Kunde');
  if (c.roles?.vendor) roles.push('Lieferant');
  return roles.join(', ') || '—';
}

// ============================================================
//  Import Tab — Lexware → CRM
// ============================================================

function ImportTab() {
  const [searchTerm, setSearchTerm] = useState('');
  const [debouncedTerm, setDebouncedTerm] = useState('');
  const [currentPage, setCurrentPage] = useState(0);
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
  const [successMessage, setSuccessMessage] = useState('');

  const importAsCompany = useImportLexwareAsCompany();
  const importAsContact = useImportLexwareAsContact();
  const createContact = useCreateContact();

  // Load CRM entities to detect already-imported Lexware contacts
  // pageSize max 100 (backend DTO validation @Max(100))
  const companiesQuery = useCompanies({ page: 1, pageSize: 100, sort: 'name', order: 'asc' });
  const contactsQuery = useContacts({ page: 1, pageSize: 100, sort: 'lastName', order: 'asc' });

  // Build lookup: lexwareContactId → { type, name, id }
  const linkedMap = new Map<string, { type: 'company' | 'contact'; name: string; id: string }>();
  for (const c of companiesQuery.data?.data ?? []) {
    if (c.lexwareContactId) {
      linkedMap.set(c.lexwareContactId, { type: 'company', name: c.name, id: c.id });
    }
  }
  for (const c of contactsQuery.data?.data ?? []) {
    if (c.lexwareContactId) {
      const name = [c.firstName, c.lastName].filter(Boolean).join(' ') || c.companyName || '—';
      linkedMap.set(c.lexwareContactId, { type: 'contact', name, id: c.id });
    }
  }

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

  // Build params: name only when >= 3 chars (backend MinLength(3))
  const searchParams: LexwareContactSearchParams = {
    page: currentPage,
    size: 25,
    ...(debouncedTerm.length >= 3 ? { name: debouncedTerm } : {}),
  };

  const { data, isLoading } = useLexwareContacts(searchParams);
  const results: LexwareContact[] = data?.data ?? [];
  const pagination = data?.pagination;
  const totalPages = pagination?.totalPages ?? 1;

  const isImporting =
    importAsCompany.isPending ||
    importAsContact.isPending ||
    createContact.isPending;

  const handleImportAsCompany = (lexwareContactId: string, name: string) => {
    importAsCompany.mutate(
      { lexwareContactId },
      {
        onSuccess: () => {
          setSuccessMessage(`"${name}" als Unternehmen importiert`);
          setTimeout(() => setSuccessMessage(''), 4000);
        },
      },
    );
  };

  const handleImportAsContact = (lexwareContactId: string, name: string) => {
    importAsContact.mutate(
      { lexwareContactId },
      {
        onSuccess: () => {
          setSuccessMessage(`"${name}" als Kontakt importiert`);
          setTimeout(() => setSuccessMessage(''), 4000);
        },
      },
    );
  };

  const handleImportContactPerson = (
    person: LexwareContactPersonEntry,
    companyName: string,
    companyId?: string,
  ) => {
    const cpName =
      [person.firstName, person.lastName].filter(Boolean).join(' ') ||
      'Ansprechpartner';
    createContact.mutate(
      {
        firstName: person.firstName || undefined,
        lastName: person.lastName || undefined,
        email: person.emailAddress || undefined,
        phone: person.phoneNumber || undefined,
        companyId: companyId || undefined,
        companyName: companyName || undefined,
        type: 'PERSON',
      },
      {
        onSuccess: () => {
          setSuccessMessage(
            `Ansprechpartner "${cpName}" als Kontakt importiert`,
          );
          setTimeout(() => setSuccessMessage(''), 4000);
        },
      },
    );
  };

  const toggleExpanded = (id: string) => {
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  return (
    <div>
      <p className={styles.tabDesc}>
        Alle Lexware Office Kontakte durchsuchen und als Unternehmen oder
        Kontakt ins CRM importieren. Ansprechpartner können einzeln importiert
        werden.
      </p>

      <input
        type="text"
        className={styles.searchInput}
        placeholder="Kontakte filtern (min. 3 Zeichen)..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />

      {successMessage && (
        <div className={styles.successBanner}>
          <svg
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M3 8.5l3 3 7-7" />
          </svg>
          {successMessage}
        </div>
      )}

      {(importAsCompany.isError ||
        importAsContact.isError ||
        createContact.isError) && (
        <div className={styles.errorBanner}>
          Import fehlgeschlagen:{' '}
          {(
            importAsCompany.error ??
            importAsContact.error ??
            createContact.error
          )?.message ?? 'Unbekannter Fehler'}
        </div>
      )}

      <div className={styles.resultsList}>
        {isLoading && (
          <p className={styles.hint}>Lade Lexware Office Kontakte...</p>
        )}

        {!isLoading && results.length === 0 && (
          <p className={styles.hint}>
            {debouncedTerm.length >= 3
              ? 'Keine Ergebnisse für diese Suche'
              : 'Keine Kontakte in Lexware Office gefunden'}
          </p>
        )}

        {results.map((contact) => {
          const name = lexwareDisplayName(contact);
          const email = lexwareEmail(contact);
          const address = lexwareAddress(contact);
          const roles = lexwareRoles(contact);
          const contactPersons = contact.company?.contactPersons ?? [];
          const isExpanded = expandedIds.has(contact.id);
          const linked = linkedMap.get(contact.id);

          return (
            <div key={contact.id} className={`${styles.resultCard} ${linked ? styles.resultCardLinked : ''}`}>
              {/* Main row */}
              <div className={styles.resultCardMain}>
                <div className={styles.resultInfo}>
                  <div className={styles.resultName}>
                    {name}
                    {linked && (
                      <Link
                        to={linked.type === 'company' ? `/crm/companies/${linked.id}` : `/crm/contacts/${linked.id}`}
                        className={styles.linkedBadge}
                        title={`Bereits als ${linked.type === 'company' ? 'Unternehmen' : 'Kontakt'} importiert — Klicken zum Öffnen`}
                      >
                        <svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                          <path d="M3 8.5l3 3 7-7" />
                        </svg>
                        {linked.type === 'company' ? 'Unternehmen' : 'Kontakt'} im CRM
                      </Link>
                    )}
                  </div>
                  <div className={styles.resultMeta}>
                    {roles !== '—' && (
                      <span className={styles.roleBadge}>{roles}</span>
                    )}
                    {email && <span>{email}</span>}
                    {address && <span>{address}</span>}
                  </div>
                </div>
                <div className={styles.resultActions}>
                  {contactPersons.length > 0 && (
                    <button
                      className={`${styles.expandBtn} ${isExpanded ? styles.expandBtnActive : ''}`}
                      onClick={() => toggleExpanded(contact.id)}
                      title={
                        isExpanded
                          ? 'Ansprechpartner ausblenden'
                          : 'Ansprechpartner anzeigen'
                      }
                    >
                      <svg
                        width="14"
                        height="14"
                        viewBox="0 0 16 16"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="1.5"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        style={{
                          transform: isExpanded
                            ? 'rotate(180deg)'
                            : 'none',
                          transition: 'transform 0.2s',
                        }}
                      >
                        <path d="M4 6l4 4 4-4" />
                      </svg>
                      {contactPersons.length} AP
                    </button>
                  )}
                  {!linked ? (
                    <>
                      <button
                        className={styles.importBtn}
                        disabled={isImporting}
                        onClick={() => handleImportAsCompany(contact.id, name)}
                        title="Als Unternehmen importieren"
                      >
                        <svg
                          width="14"
                          height="14"
                          viewBox="0 0 16 16"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="1.5"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        >
                          <rect x="2" y="6" width="12" height="9" rx="1" />
                          <path d="M5 6V3a1 1 0 011-1h4a1 1 0 011 1v3" />
                        </svg>
                        Unternehmen
                      </button>
                      <button
                        className={styles.importBtn}
                        disabled={isImporting}
                        onClick={() => handleImportAsContact(contact.id, name)}
                        title="Als Kontakt importieren"
                      >
                        <svg
                          width="14"
                          height="14"
                          viewBox="0 0 16 16"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="1.5"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        >
                          <circle cx="8" cy="5" r="3" />
                          <path d="M2 14c0-2.5 2.5-4.5 6-4.5s6 2 6 4.5" />
                        </svg>
                        Kontakt
                      </button>
                    </>
                  ) : (
                    <Link
                      to={linked.type === 'company' ? `/crm/companies/${linked.id}` : `/crm/contacts/${linked.id}`}
                      className={styles.importBtnLinked}
                      title="Im CRM öffnen"
                    >
                      <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M6 3H3v10h10v-3" />
                        <path d="M10 2h4v4M9 7l5-5" />
                      </svg>
                      Öffnen
                    </Link>
                  )}
                </div>
              </div>

              {/* Ansprechpartner expandable section */}
              {isExpanded && contactPersons.length > 0 && (
                <div className={styles.cpSection}>
                  <div className={styles.cpTitle}>
                    <svg
                      width="14"
                      height="14"
                      viewBox="0 0 16 16"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="1.5"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <circle cx="6" cy="5" r="2.5" />
                      <path d="M1 13c0-2 2-3.5 5-3.5" />
                      <circle cx="12" cy="6" r="2" />
                      <path d="M9 13c0-1.5 1.5-2.5 3-2.5s3 1 3 2.5" />
                    </svg>
                    Ansprechpartner ({contactPersons.length})
                  </div>
                  {contactPersons.map((cp, idx) => {
                    const cpName =
                      [cp.firstName, cp.lastName]
                        .filter(Boolean)
                        .join(' ') || 'Unbenannt';
                    return (
                      <div key={idx} className={styles.cpRow}>
                        <div className={styles.cpInfo}>
                          <span className={styles.cpName}>
                            {cpName}
                            {cp.primary && (
                              <span className={styles.cpPrimary}>Haupt</span>
                            )}
                          </span>
                          <span className={styles.cpMeta}>
                            {[cp.emailAddress, cp.phoneNumber]
                              .filter(Boolean)
                              .join(' · ') || 'Keine Kontaktdaten'}
                          </span>
                        </div>
                        <button
                          className={styles.importBtn}
                          disabled={isImporting}
                          onClick={() =>
                            handleImportContactPerson(
                              cp,
                              contact.company?.name ?? '',
                              linked?.type === 'company' ? linked.id : undefined,
                            )
                          }
                          title={`${cpName} als CRM-Kontakt importieren`}
                        >
                          <svg
                            width="14"
                            height="14"
                            viewBox="0 0 16 16"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="1.5"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          >
                            <circle cx="8" cy="5" r="3" />
                            <path d="M2 14c0-2.5 2.5-4.5 6-4.5s6 2 6 4.5" />
                          </svg>
                          Als Kontakt
                        </button>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Pagination */}
      {pagination && totalPages > 1 && (
        <div className={styles.pagination}>
          <button
            className={styles.pageBtn}
            disabled={currentPage === 0}
            onClick={() => setCurrentPage((p) => p - 1)}
          >
            <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
          </button>
          <span className={styles.pageInfo}>
            Seite {currentPage + 1} von {totalPages}
            {pagination.total != null && ` (${pagination.total} Kontakte)`}
          </span>
          <button
            className={styles.pageBtn}
            disabled={currentPage + 1 >= totalPages}
            onClick={() => setCurrentPage((p) => p + 1)}
          >
            Weiter
            <svg
              width="14"
              height="14"
              viewBox="0 0 14 14"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
            >
              <path d="M5 2l5 5-5 5" />
            </svg>
          </button>
        </div>
      )}
    </div>
  );
}

// ============================================================
//  Export Tab — CRM → Lexware
// ============================================================

function ExportTab() {
  const [entityFilter, setEntityFilter] = useState<'companies' | 'contacts'>(
    'companies',
  );
  const [successMessage, setSuccessMessage] = useState('');

  const pushToLexware = usePushToLexware();

  // Fetch all companies (page 1, big page size)
  const companiesQuery = useCompanies({
    page: 1,
    pageSize: 200,
    sort: 'name',
    order: 'asc',
  });
  const contactsQuery = useContacts({
    page: 1,
    pageSize: 200,
    sort: 'lastName',
    order: 'asc',
  });

  const companies: Company[] = companiesQuery.data?.data ?? [];
  const contacts: Contact[] = contactsQuery.data?.data ?? [];

  // Split into linked / unlinked
  const unlinkedCompanies = companies.filter((c) => !c.lexwareContactId);
  const linkedCompanies = companies.filter((c) => !!c.lexwareContactId);
  const unlinkedContacts = contacts.filter((c) => !c.lexwareContactId);
  const linkedContacts = contacts.filter((c) => !!c.lexwareContactId);

  const handlePush = (
    entityType: 'company' | 'contact',
    entityId: string,
    name: string,
  ) => {
    pushToLexware.mutate(
      { entityType, entityId },
      {
        onSuccess: () => {
          setSuccessMessage(`"${name}" nach Lexware exportiert`);
          setTimeout(() => setSuccessMessage(''), 4000);
        },
      },
    );
  };

  const isExporting = pushToLexware.isPending;

  return (
    <div>
      <p className={styles.tabDesc}>
        CRM-Daten zu Lexware Office exportieren. Noch nicht verknüpfte Einträge
        werden als neue Lexware-Kontakte angelegt.
      </p>

      {/* Filter Tabs */}
      <div className={styles.filterTabs}>
        <button
          className={`${styles.filterTab} ${entityFilter === 'companies' ? styles.filterTabActive : ''}`}
          onClick={() => setEntityFilter('companies')}
        >
          Unternehmen
          <span className={styles.countBadge}>{companies.length}</span>
        </button>
        <button
          className={`${styles.filterTab} ${entityFilter === 'contacts' ? styles.filterTabActive : ''}`}
          onClick={() => setEntityFilter('contacts')}
        >
          Kontakte
          <span className={styles.countBadge}>{contacts.length}</span>
        </button>
      </div>

      {successMessage && (
        <div className={styles.successBanner}>
          <svg
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M3 8.5l3 3 7-7" />
          </svg>
          {successMessage}
        </div>
      )}

      {pushToLexware.isError && (
        <div className={styles.errorBanner}>
          Export fehlgeschlagen: {pushToLexware.error?.message ?? 'Unbekannter Fehler'}
        </div>
      )}

      {/* Companies */}
      {entityFilter === 'companies' && (
        <>
          {companiesQuery.isLoading ? (
            <p className={styles.hint}>Unternehmen werden geladen...</p>
          ) : companies.length === 0 ? (
            <p className={styles.hint}>Keine Unternehmen vorhanden</p>
          ) : (
            <>
              {/* Unlinked first */}
              {unlinkedCompanies.length > 0 && (
                <div className={styles.exportSection}>
                  <h3 className={styles.exportSectionTitle}>
                    Noch nicht verknüpft ({unlinkedCompanies.length})
                  </h3>
                  <div className={styles.exportList}>
                    {unlinkedCompanies.map((c) => (
                      <div key={c.id} className={styles.exportItem}>
                        <div className={styles.exportItemInfo}>
                          <span className={styles.exportItemName}>{c.name}</span>
                          <span className={styles.exportItemMeta}>
                            {[c.email, c.city].filter(Boolean).join(' · ') ||
                              'Keine Details'}
                          </span>
                        </div>
                        <button
                          className={styles.exportBtn}
                          disabled={isExporting}
                          onClick={() =>
                            handlePush('company', c.id, c.name)
                          }
                        >
                          <svg
                            width="14"
                            height="14"
                            viewBox="0 0 16 16"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="1.5"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          >
                            <path d="M8 12V3M4 7l4-4 4 4" />
                          </svg>
                          {isExporting ? 'Export...' : 'Exportieren'}
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Linked */}
              {linkedCompanies.length > 0 && (
                <div className={styles.exportSection}>
                  <h3 className={styles.exportSectionTitle}>
                    <span className={styles.linkedDot} />
                    Bereits verknüpft ({linkedCompanies.length})
                  </h3>
                  <div className={styles.exportList}>
                    {linkedCompanies.map((c) => (
                      <div
                        key={c.id}
                        className={`${styles.exportItem} ${styles.exportItemLinked}`}
                      >
                        <div className={styles.exportItemInfo}>
                          <span className={styles.exportItemName}>{c.name}</span>
                          <span className={styles.exportItemMeta}>
                            {c.lexwareSyncedAt
                              ? `Sync: ${new Date(c.lexwareSyncedAt).toLocaleDateString('de-DE')}`
                              : 'Verknüpft'}
                            {c.email ? ` · ${c.email}` : ''}
                          </span>
                        </div>
                        <button
                          className={styles.exportBtnSecondary}
                          disabled={isExporting}
                          onClick={() =>
                            handlePush('company', c.id, c.name)
                          }
                          title="Erneut synchronisieren"
                        >
                          <svg
                            width="14"
                            height="14"
                            viewBox="0 0 16 16"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="1.5"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          >
                            <path d="M1 8a7 7 0 0112.9-3.8M15 8a7 7 0 01-12.9 3.8" />
                            <path d="M14 1v3.2h-3.2M2 15v-3.2h3.2" />
                          </svg>
                          Re-Push
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </>
          )}
        </>
      )}

      {/* Contacts */}
      {entityFilter === 'contacts' && (
        <>
          {contactsQuery.isLoading ? (
            <p className={styles.hint}>Kontakte werden geladen...</p>
          ) : contacts.length === 0 ? (
            <p className={styles.hint}>Keine Kontakte vorhanden</p>
          ) : (
            <>
              {/* Unlinked first */}
              {unlinkedContacts.length > 0 && (
                <div className={styles.exportSection}>
                  <h3 className={styles.exportSectionTitle}>
                    Noch nicht verknüpft ({unlinkedContacts.length})
                  </h3>
                  <div className={styles.exportList}>
                    {unlinkedContacts.map((c) => {
                      const name =
                        [c.firstName, c.lastName].filter(Boolean).join(' ') ||
                        c.companyName ||
                        '—';
                      return (
                        <div key={c.id} className={styles.exportItem}>
                          <div className={styles.exportItemInfo}>
                            <span className={styles.exportItemName}>{name}</span>
                            <span className={styles.exportItemMeta}>
                              {[c.email, c.city, c.company?.name]
                                .filter(Boolean)
                                .join(' · ') || 'Keine Details'}
                            </span>
                          </div>
                          <button
                            className={styles.exportBtn}
                            disabled={isExporting}
                            onClick={() =>
                              handlePush('contact', c.id, name)
                            }
                          >
                            <svg
                              width="14"
                              height="14"
                              viewBox="0 0 16 16"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="1.5"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                            >
                              <path d="M8 12V3M4 7l4-4 4 4" />
                            </svg>
                            {isExporting ? 'Export...' : 'Exportieren'}
                          </button>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* Linked */}
              {linkedContacts.length > 0 && (
                <div className={styles.exportSection}>
                  <h3 className={styles.exportSectionTitle}>
                    <span className={styles.linkedDot} />
                    Bereits verknüpft ({linkedContacts.length})
                  </h3>
                  <div className={styles.exportList}>
                    {linkedContacts.map((c) => {
                      const name =
                        [c.firstName, c.lastName].filter(Boolean).join(' ') ||
                        c.companyName ||
                        '—';
                      return (
                        <div
                          key={c.id}
                          className={`${styles.exportItem} ${styles.exportItemLinked}`}
                        >
                          <div className={styles.exportItemInfo}>
                            <span className={styles.exportItemName}>{name}</span>
                            <span className={styles.exportItemMeta}>
                              {c.lexwareSyncedAt
                                ? `Sync: ${new Date(c.lexwareSyncedAt).toLocaleDateString('de-DE')}`
                                : 'Verknüpft'}
                              {c.email ? ` · ${c.email}` : ''}
                            </span>
                          </div>
                          <button
                            className={styles.exportBtnSecondary}
                            disabled={isExporting}
                            onClick={() =>
                              handlePush('contact', c.id, name)
                            }
                            title="Erneut synchronisieren"
                          >
                            <svg
                              width="14"
                              height="14"
                              viewBox="0 0 16 16"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="1.5"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                            >
                              <path d="M1 8a7 7 0 0112.9-3.8M15 8a7 7 0 01-12.9 3.8" />
                              <path d="M14 1v3.2h-3.2M2 15v-3.2h3.2" />
                            </svg>
                            Re-Push
                          </button>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
            </>
          )}
        </>
      )}
    </div>
  );
}

// ============================================================
//  LexwareSyncContent — Reusable Import/Export tabs
// ============================================================

type SyncTabKey = 'import' | 'export';

export function LexwareSyncContent() {
  const [activeTab, setActiveTab] = useState<SyncTabKey>('import');

  return (
    <>
      {/* Sub-Tab Bar */}
      <div className={styles.tabBar}>
        <button
          className={`${styles.tab} ${activeTab === 'import' ? styles.tabActive : ''}`}
          onClick={() => setActiveTab('import')}
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M8 3v9M4 8l4 4 4-4" />
            <path d="M2 14h12" />
          </svg>
          Import (Lexware → CRM)
        </button>
        <button
          className={`${styles.tab} ${activeTab === 'export' ? styles.tabActive : ''}`}
          onClick={() => setActiveTab('export')}
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M8 12V3M4 7l4-4 4 4" />
            <path d="M2 14h12" />
          </svg>
          Export (CRM → Lexware)
        </button>
      </div>

      {/* Tab Content */}
      <div className={styles.card}>
        {activeTab === 'import' && <ImportTab />}
        {activeTab === 'export' && <ExportTab />}
      </div>
    </>
  );
}

// ============================================================
//  LexwareSyncPage — Standalone page (fallback route)
// ============================================================

export function LexwareSyncPage() {
  const { user } = useAuth();
  const { isModuleEnabled } = useCrmSettings();

  // Zugriffskontrolle
  if (
    user?.role !== 'PLATFORM_ADMIN' &&
    user?.role !== 'TENANT_ADMIN'
  ) {
    return <Navigate to="/" replace />;
  }

  if (!isModuleEnabled('lexware')) {
    return <Navigate to="/crm/settings" replace />;
  }

  return (
    <div>
      {/* Zurück */}
      <Link to="/crm/settings" 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 CRM Einstellungen
      </Link>

      {/* Header */}
      <div className={styles.header}>
        <h1 className={styles.title}>
          <span className={styles.lxBadge}>LX</span>
          Lexware Office Synchronisation
        </h1>
      </div>

      <LexwareSyncContent />
    </div>
  );
}
