// ============================================================
//  CustomFieldsForm — Custom Fields im Entity-Formular bearbeiten
//  Wird in ContactFormModal, CompanyFormModal, DealFormModal eingebettet
// ============================================================

import { useState, useEffect, useCallback } from 'react';
import type { CustomFieldValue } from './types';

interface CustomFieldsFormProps {
  /** customFields-Array aus der Entity-Detail-Response (alle definierten Felder) */
  fields: CustomFieldValue[];
  /** Callback bei Wertaenderung — liefert aktualisierte Map fieldDefId → value */
  onChange: (values: Record<string, string | number | boolean | string[] | null>) => void;
}

const labelStyle: React.CSSProperties = {
  fontSize: '0.875rem',
  fontWeight: 500,
  color: 'var(--color-text)',
  marginBottom: '0.25rem',
  display: 'block',
};

const inputStyle: React.CSSProperties = {
  width: '100%',
  padding: '0.625rem 0.75rem',
  border: '1px solid var(--color-border)',
  borderRadius: 'var(--radius-sm)',
  fontSize: '0.9375rem',
  outline: 'none',
  boxSizing: 'border-box',
  background: 'var(--color-bg-card)',
  color: 'var(--color-text)',
};

export function CustomFieldsForm({ fields, onChange }: CustomFieldsFormProps) {
  const [values, setValues] = useState<Record<string, string | number | boolean | string[] | null>>({});

  // Initialisierung aus fields
  useEffect(() => {
    const init: Record<string, string | number | boolean | string[] | null> = {};
    for (const f of fields) {
      init[f.fieldDefId] = f.value;
    }
    setValues(init);
  }, [fields]);

  const updateValue = useCallback(
    (fieldDefId: string, value: string | number | boolean | string[] | null) => {
      setValues((prev) => {
        const next = { ...prev, [fieldDefId]: value };
        onChange(next);
        return next;
      });
    },
    [onChange],
  );

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

  return (
    <div style={{ marginTop: '0.5rem' }}>
      <div
        style={{
          fontSize: '0.8125rem',
          fontWeight: 600,
          color: 'var(--color-text-muted)',
          textTransform: 'uppercase',
          letterSpacing: '0.03em',
          marginBottom: '0.75rem',
          paddingTop: '0.75rem',
          borderTop: '1px solid var(--color-border)',
        }}
      >
        Zusatzfelder
      </div>
      {fields.map((field) => (
        <div key={field.fieldDefId} style={{ marginBottom: '1rem' }}>
          <label style={labelStyle}>
            {field.label}
            {/* isRequired info not in CustomFieldValue, handled at submit */}
          </label>
          <FieldInput
            field={field}
            value={values[field.fieldDefId] ?? null}
            onChange={(v) => updateValue(field.fieldDefId, v)}
          />
        </div>
      ))}
    </div>
  );
}

// --- Per-type field renderer ---

interface FieldInputProps {
  field: CustomFieldValue;
  value: string | number | boolean | string[] | null;
  onChange: (value: string | number | boolean | string[] | null) => void;
}

function FieldInput({ field, value, onChange }: FieldInputProps) {
  switch (field.fieldType) {
    case 'TEXT':
      return (
        <input
          style={inputStyle}
          value={typeof value === 'string' ? value : ''}
          onChange={(e) => onChange(e.target.value || null)}
          placeholder={field.label}
        />
      );

    case 'TEXTAREA':
      return (
        <textarea
          style={{ ...inputStyle, minHeight: 60, resize: 'vertical' }}
          value={typeof value === 'string' ? value : ''}
          onChange={(e) => onChange(e.target.value || null)}
          placeholder={field.label}
        />
      );

    case 'NUMBER':
      return (
        <input
          type="number"
          style={inputStyle}
          value={value !== null && value !== undefined ? String(value) : ''}
          onChange={(e) => {
            const v = e.target.value;
            onChange(v === '' ? null : Number(v));
          }}
          placeholder="0"
        />
      );

    case 'DATE':
      return (
        <input
          type="date"
          style={inputStyle}
          value={typeof value === 'string' ? value.split('T')[0] : ''}
          onChange={(e) => {
            const v = e.target.value;
            onChange(v ? new Date(v).toISOString() : null);
          }}
        />
      );

    case 'CHECKBOX':
      return (
        <label
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: '0.5rem',
            fontSize: '0.9375rem',
            cursor: 'pointer',
          }}
        >
          <input
            type="checkbox"
            checked={!!value}
            onChange={(e) => onChange(e.target.checked)}
            style={{ width: 18, height: 18 }}
          />
          {field.label}
        </label>
      );

    case 'URL':
      return (
        <input
          type="url"
          style={inputStyle}
          value={typeof value === 'string' ? value : ''}
          onChange={(e) => onChange(e.target.value || null)}
          placeholder="https://..."
        />
      );

    case 'DROPDOWN':
      return (
        <DropdownField value={value} onChange={onChange} field={field} />
      );

    case 'MULTI_SELECT':
      return (
        <MultiSelectField value={value} onChange={onChange} field={field} />
      );

    default:
      return (
        <input
          style={inputStyle}
          value={typeof value === 'string' ? value : ''}
          onChange={(e) => onChange(e.target.value || null)}
        />
      );
  }
}

// --- Dropdown (single select) ---

function DropdownField({
  value,
  onChange,
  field,
}: {
  value: string | number | boolean | string[] | null;
  onChange: (v: string | null) => void;
  field: CustomFieldValue;
}) {
  // Options come from the field definition (not in CustomFieldValue directly)
  // We parse them from the backend's customFields response which may include options
  // For now we use the value as-is and provide a text input with a hint
  // The admin has defined options, but they're in the definitions, not in the value response
  // We'll use a simple select if we can derive options from context

  // CustomFieldValue doesn't carry options, so we use a text input as fallback
  // The actual options are defined in the admin. Since we don't have them here,
  // we render a text input. In a future improvement, we could pass definitions too.
  // UPDATE: Actually the backend sends customFields in detail response that includes
  // the field defs. We should fetch defs and match. For now, simple text.

  return (
    <input
      style={inputStyle}
      value={typeof value === 'string' ? value : ''}
      onChange={(e) => onChange(e.target.value || null)}
      placeholder={`${field.label} eingeben`}
    />
  );
}

// --- Multi-Select ---

function MultiSelectField({
  value,
  onChange,
  field,
}: {
  value: string | number | boolean | string[] | null;
  onChange: (v: string[] | null) => void;
  field: CustomFieldValue;
}) {
  const selected: string[] = Array.isArray(value) ? value : [];
  const [input, setInput] = useState('');

  const addTag = useCallback(() => {
    const trimmed = input.trim();
    if (trimmed && !selected.includes(trimmed)) {
      const next = [...selected, trimmed];
      onChange(next.length > 0 ? next : null);
    }
    setInput('');
  }, [input, selected, onChange]);

  const removeTag = useCallback(
    (tag: string) => {
      const next = selected.filter((s) => s !== tag);
      onChange(next.length > 0 ? next : null);
    },
    [selected, onChange],
  );

  return (
    <div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.25rem', marginBottom: selected.length > 0 ? '0.5rem' : 0 }}>
        {selected.map((tag) => (
          <span
            key={tag}
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: '0.25rem',
              padding: '0.125rem 0.5rem',
              background: '#eff6ff',
              color: '#1e40af',
              borderRadius: '9999px',
              fontSize: '0.8125rem',
              fontWeight: 500,
            }}
          >
            {tag}
            <button
              type="button"
              onClick={() => removeTag(tag)}
              style={{
                background: 'none',
                border: 'none',
                cursor: 'pointer',
                fontSize: '0.875rem',
                lineHeight: 1,
                color: '#1e40af',
                padding: 0,
              }}
            >
              &times;
            </button>
          </span>
        ))}
      </div>
      <input
        style={inputStyle}
        value={input}
        onChange={(e) => setInput(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter') {
            e.preventDefault();
            addTag();
          }
        }}
        placeholder={`${field.label} hinzufuegen (Enter)`}
      />
    </div>
  );
}
