'use client';

import { useState, useMemo } from 'react';
import { Plus, X, Search } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { ColumnInfo } from '@/lib/crm/cumas-client';
import { CollapsibleSection, FilterField, DynamicFilterControl, makeDefaultDynamicFilter, type DynamicFilterValue } from './_shared';

export interface SchemaBrowserProps {
  /** Schema-Spalten (vom /api/crm/schema-Endpoint) */
  columns: ColumnInfo[];
  /** Welche Spalten sind bereits über Curated-Filter abgedeckt — werden nicht angeboten */
  excludeColumns?: string[];
  /** Aktive Dynamic-Filter (kontrolliert vom Parent) */
  value: DynamicFilterValue[];
  onChange: (next: DynamicFilterValue[]) => void;
}

const KIND_LABELS: Record<string, string> = {
  string: 'Text',
  number: 'Zahl',
  enum: 'Auswahl',
  date: 'Datum',
  boolean: 'Ja/Nein',
  unknown: '?',
};

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

export function SchemaBrowser({ columns, excludeColumns = [], value, onChange }: SchemaBrowserProps) {
  const [search, setSearch] = useState('');

  // Verfügbar = im Schema, NICHT in excludeColumns, NICHT in value
  const activeColumns = new Set(value.map((v) => v.column));
  const available = useMemo(() => {
    return columns.filter((c) => {
      if (excludeColumns.includes(c.name)) return false;
      if (activeColumns.has(c.name)) return false;
      if (c.kind === 'unknown') return false; // type-detection failed → skip
      if (search && !c.name.toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    });
  }, [columns, excludeColumns, activeColumns, search]);

  const addFilter = (col: ColumnInfo) => {
    onChange([...value, makeDefaultDynamicFilter(col.name, col.kind)]);
  };

  const removeFilter = (column: string) => {
    onChange(value.filter((v) => v.column !== column));
  };

  const updateFilter = (column: string, next: DynamicFilterValue) => {
    onChange(value.map((v) => (v.column === column ? next : v)));
  };

  // Schema-Lookup für topValues per Column (für DynamicFilterControl)
  const colByName = useMemo(() => new Map(columns.map((c) => [c.name, c])), [columns]);

  return (
    <CollapsibleSection title="Weitere Felder filtern" defaultOpen={value.length > 0}>
      {/* Aktive Dynamic-Filter — gerendert oben */}
      {value.length > 0 && (
        <div className="space-y-2">
          {value.map((f) => {
            const col = colByName.get(f.column);
            return (
              <div
                key={f.column}
                className="flex items-start gap-2 rounded-md border border-pink-200 bg-pink-50/40 p-2 dark:border-pink-900/50 dark:bg-pink-950/20"
              >
                <div className="flex-1 min-w-0">
                  <FilterField
                    label={f.column}
                    hint={col ? `${KIND_LABELS[col.kind]} · ${col.filledCount}/${col.totalSampled} gefüllt` : undefined}
                  >
                    <DynamicFilterControl
                      value={f}
                      onChange={(next) => updateFilter(f.column, next)}
                      topValues={col?.topValues}
                    />
                  </FilterField>
                </div>
                <button
                  type="button"
                  onClick={() => removeFilter(f.column)}
                  className="mt-4 rounded p-0.5 text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:hover:bg-zinc-800"
                  aria-label="Filter entfernen"
                  title="Filter entfernen"
                >
                  <X className="h-3.5 w-3.5" />
                </button>
              </div>
            );
          })}
        </div>
      )}

      {/* Suche + Add-Liste */}
      <div className="mt-3 flex flex-col gap-2">
        <div className="relative">
          <Search className="absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-zinc-400" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Spalte suchen (z.B. position_k1, comment)"
            className="w-full rounded-md border border-zinc-200 bg-white py-1.5 pl-7 pr-2 text-xs focus:border-zinc-900 focus:outline-none dark:border-zinc-700 dark:bg-zinc-900"
          />
        </div>
        {available.length === 0 ? (
          <p className="rounded border border-dashed border-zinc-300 p-2 text-center text-[10px] text-zinc-500 dark:border-zinc-700">
            {search ? 'Keine Spalte passt zur Suche' : columns.length === 0 ? 'Schema lädt …' : 'Alle verfügbaren Spalten bereits gefiltert'}
          </p>
        ) : (
          <div className="max-h-48 overflow-y-auto rounded border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-950">
            {available.map((col) => (
              <button
                key={col.name}
                type="button"
                onClick={() => addFilter(col)}
                className="flex w-full items-center gap-2 border-b border-zinc-100 px-2 py-1.5 text-left text-[11px] last:border-b-0 hover:bg-zinc-50 dark:border-zinc-900 dark:hover:bg-zinc-900/50"
              >
                <Plus className="h-3 w-3 shrink-0 text-zinc-400" />
                <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] ?? KIND_COLORS.unknown,
                )}>
                  {KIND_LABELS[col.kind] ?? col.kind}
                </span>
                <span className="text-[9px] text-zinc-400">
                  {col.filledCount}/{col.totalSampled}
                </span>
              </button>
            ))}
          </div>
        )}
      </div>
    </CollapsibleSection>
  );
}
