import { useState } from 'react';
import {
  useDealVouchers,
  useLinkVoucherToDeal,
  useUnlinkVoucherFromDeal,
  useCompanyVouchers,
  useContactVouchers,
} from '../hooks';
import { useCrmSettings } from '../settings/CrmSettingsContext';
import type { LexwareVoucher, DealVoucher, VoucherType } from '../types';
import { VOUCHER_TYPE_LABELS } from '../types';
import { Modal } from '../../components/Modal';
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 '';
}

// ============================================================
//  LinkVoucherModal — pick from available vouchers
// ============================================================

interface LinkVoucherModalProps {
  isOpen: boolean;
  onClose: () => void;
  dealId: string;
  companyId: string | null;
  contactId: string | null;
  linkedVoucherIds: Set<string>;
}

function LinkVoucherModal({
  isOpen,
  onClose,
  dealId,
  companyId,
  contactId,
  linkedVoucherIds,
}: LinkVoucherModalProps) {
  const linkMutation = useLinkVoucherToDeal();

  // Fetch available vouchers from company or contact
  const companyVouchers = useCompanyVouchers(
    companyId ?? '',
    companyId && isOpen ? { pageSize: 100 } : undefined,
  );
  const contactVouchers = useContactVouchers(
    contactId ?? '',
    contactId && !companyId && isOpen ? { pageSize: 100 } : undefined,
  );

  const sourceData = companyId ? companyVouchers : contactVouchers;
  const allVouchers: LexwareVoucher[] = sourceData.data?.data ?? [];
  // Filter out already linked vouchers
  const available = allVouchers.filter((v) => !linkedVoucherIds.has(v.id));

  const handleLink = (voucherId: string) => {
    linkMutation.mutate(
      { dealId, voucherId },
      { onSuccess: () => onClose() },
    );
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="Beleg verknüpfen"
      maxWidth="560px"
    >
      {!companyId && !contactId && (
        <p className={styles.emptyText}>
          Dieser Vorgang hat kein verknüpftes Unternehmen oder Kontakt mit
          Lexware-Verbindung. Bitte zuerst einen Lexware-Kontakt verknüpfen.
        </p>
      )}

      {(companyId || contactId) && sourceData.isLoading && (
        <p className={styles.loadingText}>Belege werden geladen...</p>
      )}

      {(companyId || contactId) && !sourceData.isLoading && available.length === 0 && (
        <p className={styles.emptyText}>
          Keine weiteren Belege zum Verknüpfen verfügbar
        </p>
      )}

      {available.length > 0 && (
        <div className={styles.searchResults}>
          {available.map((v) => (
            <div key={v.id} className={styles.searchResultItem}>
              <div className={styles.searchResultInfo}>
                <div className={styles.searchResultName}>
                  <span
                    className={`${styles.voucherTypeBadge} ${voucherTypeClass(v.voucherType)}`}
                    style={{ marginRight: '0.5rem' }}
                  >
                    {VOUCHER_TYPE_LABELS[v.voucherType]}
                  </span>
                  {v.voucherNumber ?? 'Ohne Nummer'}
                </div>
                <div className={styles.searchResultMeta}>
                  {v.voucherDate ? formatDate(v.voucherDate) : '—'}
                  {v.totalGrossAmount && (
                    <>
                      {' · '}
                      {currencyFormatter.format(
                        parseFloat(v.totalGrossAmount),
                      )}
                    </>
                  )}
                  {v.title && <> · {v.title}</>}
                </div>
              </div>
              <button
                className={styles.searchResultBtn}
                disabled={linkMutation.isPending}
                onClick={() => handleLink(v.id)}
              >
                {linkMutation.isPending ? '...' : 'Verknüpfen'}
              </button>
            </div>
          ))}
        </div>
      )}
    </Modal>
  );
}

// ============================================================
//  DealVouchersSection
// ============================================================

interface DealVouchersSectionProps {
  dealId: string;
  companyId: string | null;
  contactId: string | null;
}

export function DealVouchersSection({
  dealId,
  companyId,
  contactId,
}: DealVouchersSectionProps) {
  const { isModuleEnabled } = useCrmSettings();
  const [isLinkOpen, setLinkOpen] = useState(false);

  // All hooks must be called before any conditional return
  const { data, isLoading } = useDealVouchers(dealId);
  const unlinkMutation = useUnlinkVoucherFromDeal();

  // Hide entire section if Lexware module is disabled
  if (!isModuleEnabled('lexware')) return null;

  const dealVouchers: DealVoucher[] = data?.data ?? [];
  const linkedVoucherIds = new Set(dealVouchers.map((dv) => dv.voucher.id));

  return (
    <div className={styles.card}>
      {/* Header */}
      <div className={styles.cardHeader}>
        <h2 className={styles.cardTitle}>
          <span className={styles.lexwareLogo}>LX</span>
          Belege ({dealVouchers.length})
        </h2>
        <button
          className={styles.actionBtnPrimary}
          onClick={() => setLinkOpen(true)}
          style={{ padding: '0.25rem 0.625rem', fontSize: '0.8125rem' }}
        >
          + Beleg verknüpfen
        </button>
      </div>

      {isLoading ? (
        <p className={styles.loadingText}>Belege werden geladen...</p>
      ) : dealVouchers.length === 0 ? (
        <p className={styles.emptyText}>
          Keine Belege mit diesem Vorgang verknüpft
        </p>
      ) : (
        <table className={styles.voucherTable}>
          <thead>
            <tr>
              <th>Typ</th>
              <th>Nummer</th>
              <th>Datum</th>
              <th>Status</th>
              <th>Betrag</th>
              <th style={{ width: 36 }} />
            </tr>
          </thead>
          <tbody>
            {dealVouchers.map((dv) => {
              const v = dv.voucher;
              return (
                <tr key={dv.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>
                  <td>
                    <button
                      onClick={() =>
                        unlinkMutation.mutate({
                          dealId,
                          voucherId: v.id,
                        })
                      }
                      disabled={unlinkMutation.isPending}
                      title="Verknüpfung aufheben"
                      style={{
                        background: 'none',
                        border: 'none',
                        cursor: unlinkMutation.isPending
                          ? 'wait'
                          : 'pointer',
                        color: 'var(--color-text-muted)',
                        padding: '0.25rem',
                        display: 'flex',
                        alignItems: 'center',
                      }}
                    >
                      <svg
                        width="14"
                        height="14"
                        viewBox="0 0 16 16"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="1.5"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      >
                        <path d="M4 4l8 8M12 4l-8 8" />
                      </svg>
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      )}

      {/* Link Voucher Modal */}
      <LinkVoucherModal
        isOpen={isLinkOpen}
        onClose={() => setLinkOpen(false)}
        dealId={dealId}
        companyId={companyId}
        contactId={contactId}
        linkedVoucherIds={linkedVoucherIds}
      />
    </div>
  );
}
