import { useState } from 'react';
import {
  useLinkLexwareCompany,
  useLinkLexwareContact,
  useUnlinkLexwareCompany,
  useUnlinkLexwareContact,
  usePushToLexware,
  useSyncFromLexware,
  useCompanyVouchers,
  useContactVouchers,
  useRefreshCompanyVouchers,
  useRefreshContactVouchers,
} from '../hooks';
import { useCrmSettings } from '../settings/CrmSettingsContext';
import type { LexwareVoucher, VoucherType } from '../types';
import { VOUCHER_TYPE_LABELS } from '../types';
import { LexwareSearchModal } from './LexwareSearchModal';
import styles from './LexwareSection.module.css';

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

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

function voucherTypeClass(type: VoucherType): string {
  switch (type) {
    case 'QUOTATION':
      return styles.typeQuotation;
    case 'ORDER_CONFIRMATION':
      return styles.typeOrderConfirmation;
    case 'INVOICE':
      return styles.typeInvoice;
    case 'CREDIT_NOTE':
      return styles.typeCreditNote;
    default:
      return '';
  }
}

function voucherStatusClass(status: string | null): string {
  if (!status) return '';
  const lower = status.toLowerCase();
  if (lower === 'paid' || lower === 'bezahlt') return styles.statusPaid;
  if (lower === 'overdue' || lower === 'überfällig') return styles.statusOverdue;
  if (lower === 'open' || lower === 'offen') return styles.statusOpen;
  return '';
}

// ============================================================
//  VouchersTable
// ============================================================

function VouchersTable({ vouchers }: { vouchers: LexwareVoucher[] }) {
  if (vouchers.length === 0) {
    return <p className={styles.emptyText}>Keine Belege vorhanden</p>;
  }

  return (
    <table className={styles.voucherTable}>
      <thead>
        <tr>
          <th>Typ</th>
          <th>Nummer</th>
          <th>Datum</th>
          <th>Status</th>
          <th>Betrag</th>
        </tr>
      </thead>
      <tbody>
        {vouchers.map((v) => (
          <tr key={v.id}>
            <td>
              <span
                className={`${styles.voucherTypeBadge} ${voucherTypeClass(v.voucherType)}`}
              >
                {VOUCHER_TYPE_LABELS[v.voucherType]}
              </span>
            </td>
            <td>
              {v.lexwareDeepLink ? (
                <a
                  href={v.lexwareDeepLink}
                  target="_blank"
                  rel="noopener noreferrer"
                  className={styles.voucherLink}
                  style={{ fontSize: '0.8125rem' }}
                >
                  {v.voucherNumber ?? '—'}
                </a>
              ) : (
                v.voucherNumber ?? '—'
              )}
            </td>
            <td>{v.voucherDate ? formatDate(v.voucherDate) : '—'}</td>
            <td>
              <span className={voucherStatusClass(v.voucherStatus)}>
                {v.voucherStatus ?? '—'}
              </span>
            </td>
            <td>
              {v.totalGrossAmount
                ? currencyFormatter.format(parseFloat(v.totalGrossAmount))
                : '—'}
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// ============================================================
//  LexwareSection — Main Component
// ============================================================

interface LexwareSectionProps {
  entityType: 'company' | 'contact';
  entityId: string;
  lexwareContactId: string | null;
  lexwareSyncedAt: string | null;
}

export function LexwareSection({
  entityType,
  entityId,
  lexwareContactId,
  lexwareSyncedAt,
}: LexwareSectionProps) {
  const { isModuleEnabled } = useCrmSettings();
  const [isSearchOpen, setSearchOpen] = useState(false);
  const [voucherTypeFilter, setVoucherTypeFilter] = useState<
    VoucherType | ''
  >('');

  const isLinked = !!lexwareContactId;
  const lexwareEnabled = isModuleEnabled('lexware');

  // Mutations — all hooks must be called before any conditional return
  const linkCompany = useLinkLexwareCompany();
  const linkContact = useLinkLexwareContact();
  const unlinkCompany = useUnlinkLexwareCompany();
  const unlinkContact = useUnlinkLexwareContact();
  const pushToLexware = usePushToLexware();
  const syncFromLexware = useSyncFromLexware();
  const refreshCompanyVouchers = useRefreshCompanyVouchers();
  const refreshContactVouchers = useRefreshContactVouchers();

  // Vouchers (only fetch when linked AND module enabled)
  const vouchersParams = voucherTypeFilter
    ? { voucherType: voucherTypeFilter as VoucherType, pageSize: 50 }
    : { pageSize: 50 };
  const companyVouchers = useCompanyVouchers(
    entityType === 'company' ? entityId : '',
    entityType === 'company' && isLinked && lexwareEnabled
      ? vouchersParams
      : undefined,
  );
  const contactVouchers = useContactVouchers(
    entityType === 'contact' ? entityId : '',
    entityType === 'contact' && isLinked && lexwareEnabled
      ? vouchersParams
      : undefined,
  );

  // Hide entire section if Lexware module is disabled
  if (!lexwareEnabled) return null;

  const vouchersData =
    entityType === 'company' ? companyVouchers : contactVouchers;
  const vouchers: LexwareVoucher[] = vouchersData.data?.data ?? [];
  const isLoadingVouchers = vouchersData.isLoading;

  const isAnyMutating =
    linkCompany.isPending ||
    linkContact.isPending ||
    unlinkCompany.isPending ||
    unlinkContact.isPending ||
    pushToLexware.isPending ||
    syncFromLexware.isPending ||
    refreshCompanyVouchers.isPending ||
    refreshContactVouchers.isPending;

  const handleLink = (lexwareId: string) => {
    if (entityType === 'company') {
      linkCompany.mutate(
        { lexwareContactId: lexwareId, companyId: entityId },
        { onSuccess: () => setSearchOpen(false) },
      );
    } else {
      linkContact.mutate(
        { lexwareContactId: lexwareId, contactId: entityId },
        { onSuccess: () => setSearchOpen(false) },
      );
    }
  };

  const handleUnlink = () => {
    if (entityType === 'company') {
      unlinkCompany.mutate(entityId);
    } else {
      unlinkContact.mutate(entityId);
    }
  };

  const handlePush = () => {
    pushToLexware.mutate({ entityType, entityId });
  };

  const handleSync = () => {
    syncFromLexware.mutate({ entityType, entityId });
  };

  const handleRefresh = () => {
    if (entityType === 'company') {
      refreshCompanyVouchers.mutate(entityId);
    } else {
      refreshContactVouchers.mutate(entityId);
    }
  };

  return (
    <div className={styles.card}>
      {/* Header */}
      <div className={styles.cardHeader}>
        <h2 className={styles.cardTitle}>
          <span className={styles.lexwareLogo}>LX</span>
          Lexware Office
        </h2>
        <span
          className={`${styles.statusBadge} ${
            isLinked ? styles.statusLinked : styles.statusNotLinked
          }`}
        >
          <span
            style={{
              width: 6,
              height: 6,
              borderRadius: '50%',
              background: isLinked ? '#059669' : 'var(--color-text-muted)',
              display: 'inline-block',
            }}
          />
          {isLinked ? 'Verknüpft' : 'Nicht verknüpft'}
        </span>
      </div>

      {/* Sync info */}
      {isLinked && lexwareSyncedAt && (
        <p className={styles.syncInfo}>
          Letzte Synchronisation: {formatDate(lexwareSyncedAt)}
        </p>
      )}

      {/* Action buttons */}
      <div className={styles.actions}>
        {!isLinked ? (
          <button
            className={styles.actionBtnPrimary}
            onClick={() => setSearchOpen(true)}
            disabled={isAnyMutating}
          >
            <svg
              width="14"
              height="14"
              viewBox="0 0 16 16"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <circle cx="7" cy="7" r="5" />
              <path d="M11 11l3.5 3.5" />
            </svg>
            Lexware Kontakt suchen
          </button>
        ) : (
          <>
            <button
              className={styles.actionBtn}
              onClick={handleSync}
              disabled={isAnyMutating}
              title="Daten aus Lexware aktualisieren"
            >
              <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>
              {syncFromLexware.isPending ? 'Sync...' : 'Sync'}
            </button>
            <button
              className={styles.actionBtn}
              onClick={handlePush}
              disabled={isAnyMutating}
              title="Daten zu Lexware übertragen"
            >
              <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>
              {pushToLexware.isPending ? 'Push...' : 'Push'}
            </button>
            <button
              className={styles.actionBtn}
              onClick={handleRefresh}
              disabled={isAnyMutating}
              title="Belege aus Lexware neu laden"
            >
              <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>
              Belege aktualisieren
            </button>
            <button
              className={styles.actionBtnDanger}
              onClick={handleUnlink}
              disabled={isAnyMutating}
              title="Verknüpfung aufheben"
            >
              {(unlinkCompany.isPending || unlinkContact.isPending)
                ? 'Trennen...'
                : 'Trennen'}
            </button>
          </>
        )}
      </div>

      {/* Vouchers */}
      {isLinked && (
        <>
          <div className={styles.filterRow}>
            <select
              className={styles.filterSelect}
              value={voucherTypeFilter}
              onChange={(e) =>
                setVoucherTypeFilter(e.target.value as VoucherType | '')
              }
            >
              <option value="">Alle Belegarten</option>
              <option value="QUOTATION">Angebote</option>
              <option value="ORDER_CONFIRMATION">Auftragsbestätigungen</option>
              <option value="INVOICE">Rechnungen</option>
              <option value="CREDIT_NOTE">Gutschriften</option>
            </select>
          </div>

          {isLoadingVouchers ? (
            <p className={styles.loadingText}>Belege werden geladen...</p>
          ) : (
            <VouchersTable vouchers={vouchers} />
          )}
        </>
      )}

      {/* Search Modal */}
      <LexwareSearchModal
        isOpen={isSearchOpen}
        onClose={() => setSearchOpen(false)}
        onLink={handleLink}
        isLinking={linkCompany.isPending || linkContact.isPending}
      />
    </div>
  );
}
