'use client';

import { useEffect, useRef, useState } from 'react';
import { Settings2, Check, X } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { ColumnInfo } from '@/lib/crm/cumas-client';

export interface ColumnPickerProps {
  /** Welcher Tab — bestimmt den localStorage-Key */
  tableKey: 'business' | 'evb' | 'orders';
  /** Alle verfügbaren Spalten aus dem Schema-Endpoint */
  available: ColumnInfo[];
  /** Aktuell ausgewählte Spalten-Namen (controlled) */
  value: string[];
  onChange: (next: string[]) => void;
}

/**
 * Default-Auswahl pro Tabelle — die UX-typischsten Spalten.
 * Wenn localStorage etwas anderes hat, wird das übernommen.
 */
export const DEFAULT_COLUMNS: Record<ColumnPickerProps['tableKey'], string[]> = {
  business: ['email', 'firma', 'vorname_k1', 'nachname_k1', 'ort', 'branche'],
  evb: ['email', 'vorname', 'nachname', 'typ', 'gesellschaft'],
  orders: ['email', 'client_name', 'product', 'reg_datetime'],
};

const STORAGE_KEY_PREFIX = 'mailforge.colpicker.';

/**
 * Hydratet Initial-Value aus localStorage. Falls leer/invalid → DEFAULT_COLUMNS.
 * Wichtig: nur Client-Side aufrufen (`useEffect`), nicht im SSR.
 */
export function loadColumnsFromStorage(tableKey: ColumnPickerProps['tableKey']): string[] {
  if (typeof window === 'undefined') return DEFAULT_COLUMNS[tableKey];
  try {
    const raw = localStorage.getItem(STORAGE_KEY_PREFIX + tableKey);
    if (!raw) return DEFAULT_COLUMNS[tableKey];
    const parsed = JSON.parse(raw);
    if (Array.isArray(parsed) && parsed.every((x) => typeof x === 'string')) return parsed;
  } catch {
    // ignore — fallback to defaults
  }
  return DEFAULT_COLUMNS[tableKey];
}

export function saveColumnsToStorage(tableKey: ColumnPickerProps['tableKey'], cols: string[]): void {
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(STORAGE_KEY_PREFIX + tableKey, JSON.stringify(cols));
  } catch { /* quota exceeded — ignore */ }
}

export function ColumnPicker({ tableKey, available, value, onChange }: ColumnPickerProps) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  // Click-outside zum Schließen
  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (!ref.current?.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);

  const toggle = (name: string) => {
    const next = value.includes(name) ? value.filter((c) => c !== name) : [...value, name];
    onChange(next);
    saveColumnsToStorage(tableKey, next);
  };

  const selectedCount = value.length;
  const totalCount = available.length;

  return (
    <div ref={ref} className="relative inline-block">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className={cn(
          'inline-flex items-center gap-1.5 rounded-md border border-zinc-200 bg-white px-2.5 py-1 text-[11px] font-medium text-zinc-700 transition hover:border-zinc-300 hover:bg-zinc-50',
          'dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-300 dark:hover:bg-zinc-800',
        )}
      >
        <Settings2 className="h-3 w-3" />
        Spalten
        <span className="rounded bg-zinc-100 px-1 py-0.5 text-[9px] font-semibold text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400">
          {selectedCount}/{totalCount}
        </span>
      </button>

      {open && (
        <div className="absolute right-0 top-full z-30 mt-1 w-72 rounded-lg border border-zinc-200 bg-white shadow-xl dark:border-zinc-800 dark:bg-zinc-950">
          <div className="flex items-center justify-between border-b border-zinc-200 px-3 py-2 dark:border-zinc-800">
            <span className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">Spalten anzeigen</span>
            <button
              type="button"
              onClick={() => setOpen(false)}
              className="rounded p-0.5 text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800"
              aria-label="Schließen"
            >
              <X className="h-3.5 w-3.5" />
            </button>
          </div>
          <div className="max-h-80 overflow-y-auto p-1">
            {available.length === 0 ? (
              <div className="px-3 py-4 text-center text-[11px] text-zinc-400">Schema lädt …</div>
            ) : (
              available.map((col) => {
                const checked = value.includes(col.name);
                return (
                  <button
                    key={col.name}
                    type="button"
                    onClick={() => toggle(col.name)}
                    className={cn(
                      'flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs transition',
                      checked
                        ? 'bg-pink-50 text-pink-900 hover:bg-pink-100 dark:bg-pink-950/30 dark:text-pink-100'
                        : 'text-zinc-700 hover:bg-zinc-100 dark:text-zinc-300 dark:hover:bg-zinc-800',
                    )}
                  >
                    <span
                      className={cn(
                        'flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded border',
                        checked ? 'border-[#ff006a] bg-[#ff006a]' : 'border-zinc-300 dark:border-zinc-600',
                      )}
                    >
                      {checked && <Check className="h-2.5 w-2.5 text-white" />}
                    </span>
                    <span className="flex-1 font-mono">{col.name}</span>
                    <span className={cn(
                      'rounded px-1 py-0.5 text-[9px] uppercase tracking-wider',
                      KIND_COLORS[col.kind] ?? 'bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400',
                    )}>
                      {col.kind}
                    </span>
                  </button>
                );
              })
            )}
          </div>
          <div className="flex items-center justify-between border-t border-zinc-200 px-3 py-2 text-[10px] text-zinc-500 dark:border-zinc-800">
            <button
              type="button"
              onClick={() => { onChange(DEFAULT_COLUMNS[tableKey]); saveColumnsToStorage(tableKey, DEFAULT_COLUMNS[tableKey]); }}
              className="text-zinc-600 underline hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-200"
            >
              Reset auf Default
            </button>
            <span>{selectedCount} von {totalCount}</span>
          </div>
        </div>
      )}
    </div>
  );
}

/** Type-Badge-Farben je `ColumnKind`. */
const KIND_COLORS: Record<string, string> = {
  string: 'bg-blue-100 text-blue-700 dark:bg-blue-950/50 dark:text-blue-300',
  number: 'bg-amber-100 text-amber-700 dark:bg-amber-950/50 dark:text-amber-300',
  enum: 'bg-violet-100 text-violet-700 dark:bg-violet-950/50 dark:text-violet-300',
  date: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-300',
  boolean: 'bg-rose-100 text-rose-700 dark:bg-rose-950/50 dark:text-rose-300',
  unknown: 'bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400',
};
