// ============================================================
//  CustomFieldsDisplay — zeigt Custom Fields in Entity-Detail-Pages
// ============================================================

import type { CustomFieldValue } from './types';

interface CustomFieldsDisplayProps {
  fields: CustomFieldValue[];
}

const labelStyle: React.CSSProperties = {
  fontSize: '0.8125rem',
  color: 'var(--color-text-muted)',
  minWidth: 120,
};

const valueStyle: React.CSSProperties = {
  fontSize: '0.875rem',
  color: 'var(--color-text)',
  wordBreak: 'break-word',
};

function formatValue(field: CustomFieldValue): React.ReactNode {
  if (field.value === null || field.value === undefined) return null;

  switch (field.fieldType) {
    case 'CHECKBOX':
      return field.value ? 'Ja' : 'Nein';

    case 'DATE':
      if (typeof field.value === 'string') {
        try {
          return new Date(field.value).toLocaleDateString('de-DE', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
          });
        } catch {
          return String(field.value);
        }
      }
      return String(field.value);

    case 'URL':
      if (typeof field.value === 'string' && field.value) {
        return (
          <a
            href={field.value.startsWith('http') ? field.value : `https://${field.value}`}
            target="_blank"
            rel="noopener noreferrer"
            style={{ color: 'var(--color-primary)' }}
          >
            {field.value}
          </a>
        );
      }
      return String(field.value);

    case 'MULTI_SELECT':
      if (Array.isArray(field.value)) {
        return (
          <span style={{ display: 'flex', flexWrap: 'wrap', gap: '0.25rem' }}>
            {(field.value as string[]).map((v) => (
              <span
                key={v}
                style={{
                  display: 'inline-block',
                  padding: '0.0625rem 0.375rem',
                  background: '#eff6ff',
                  color: '#1e40af',
                  borderRadius: '9999px',
                  fontSize: '0.75rem',
                  fontWeight: 500,
                }}
              >
                {v}
              </span>
            ))}
          </span>
        );
      }
      return String(field.value);

    case 'NUMBER':
      return typeof field.value === 'number'
        ? field.value.toLocaleString('de-DE')
        : String(field.value);

    case 'TEXTAREA':
      return (
        <span style={{ whiteSpace: 'pre-wrap' }}>
          {String(field.value)}
        </span>
      );

    default:
      return String(field.value);
  }
}

export function CustomFieldsDisplay({ fields }: CustomFieldsDisplayProps) {
  // Nur Felder mit Wert anzeigen
  const fieldsWithValues = fields.filter((f) => {
    if (f.value === null || f.value === undefined) return false;
    if (typeof f.value === 'string' && f.value === '') return false;
    if (Array.isArray(f.value) && f.value.length === 0) return false;
    return true;
  });

  if (fieldsWithValues.length === 0) return null;

  return (
    <div style={{ marginTop: '1.25rem' }}>
      <span
        style={{
          display: 'block',
          fontSize: '0.8125rem',
          fontWeight: 600,
          color: 'var(--color-text-muted)',
          textTransform: 'uppercase',
          letterSpacing: '0.03em',
          marginBottom: '0.625rem',
        }}
      >
        Zusatzfelder
      </span>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'auto 1fr',
          gap: '0.375rem 1rem',
          alignItems: 'baseline',
        }}
      >
        {fieldsWithValues.map((field) => (
          <div key={field.fieldDefId} style={{ display: 'contents' }}>
            <span style={labelStyle}>{field.label}</span>
            <span style={valueStyle}>{formatValue(field)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}
