'use client';

import { EVB_TYPE_LABELS } from '@/lib/crm/cumas-codes';
import {
  CheckboxGroup,
  CollapsibleSection,
  FilterField,
  FilterHint,
  FilterInput,
  FilterVisibilityPicker,
  SampleSizeBanner,
  SectionLabel,
  StringMultiSelect,
  TriStateToggle,
  useFilterVisibility,
  type DynamicFilterValue,
  type FilterDef,
} from './_shared';
import { DateRangeInput, type DateRangeValue } from './DateRangeInput';
import { SchemaBrowser } from './SchemaBrowser';
import type { ColumnInfo } from '@/lib/crm/cumas-client';

export interface EvbFilterState {
  server: {
    evbnr?: string;
    rechnr?: string;
    idkdnr?: number;
    itsBusinessData?: number;
    orderPrivateShop?: number;
    rechdatumAfter?: string;
    rechdatumBefore?: string;
  };
  client: {
    typIn?: string[];
    gesellschaftIn?: string[];
    resellerIn?: string[];
    storno?: boolean;
    aktiviert?: boolean;
    bezahlt?: boolean;
    vkverstMin?: number;
    vkverstMax?: number;
  };
}

export const DEFAULT_EVB_STATE: EvbFilterState = {
  server: {},
  client: { storno: false }, // Default: keine stornierten EVBs
};

const EVB_FILTER_DEFS: FilterDef[] = [
  { key: 'hint', label: 'Info-Hinweis (oben)', group: 'Allgemein' },
  { key: 'evbnr', label: 'EVB-Nr', group: 'API-Filter', defaultVisible: true },
  { key: 'rechnr', label: 'Rechnungs-Nr', group: 'API-Filter' },
  { key: 'rechdatum', label: 'Rechnungsdatum', group: 'API-Filter' },
  { key: 'idnumbers', label: 'idkdnr + Business-FK', group: 'API-Filter' },
  { key: 'orderFk', label: 'Order-FK', group: 'API-Filter' },
  { key: 'typ', label: 'Typ (KZK/KZKA)', group: 'Klassifizierung', defaultVisible: true },
  { key: 'gesellschaft', label: 'Versicherer', group: 'Klassifizierung', defaultVisible: true },
  { key: 'reseller', label: 'Reseller', group: 'Klassifizierung' },
  { key: 'statusPreis', label: 'Status & Preis (collapsible)', group: 'Erweitert', defaultVisible: true },
  { key: 'schemaBrowser', label: 'Schema-Browser (ad-hoc)', group: 'Erweitert' },
];

export function EvbFilters({
  state,
  onChange,
  facets,
  facetCounts,
  schemaColumns,
  dynamicFilters,
  onDynamicFiltersChange,
  totalSampled,
  onLoadMoreSamples,
  loadingMoreSamples,
}: {
  state: EvbFilterState;
  onChange: (next: EvbFilterState) => void;
  facets: { evbTyp: string[]; evbGesellschaft: string[]; evbReseller: string[] };
  facetCounts?: { evbGesellschaft?: Record<string, number>; evbReseller?: Record<string, number> };
  /** Optional: alle verfügbaren Spalten aus dem Schema-Endpoint (für SchemaBrowser). */
  schemaColumns?: ColumnInfo[];
  dynamicFilters?: DynamicFilterValue[];
  onDynamicFiltersChange?: (next: DynamicFilterValue[]) => void;
  totalSampled?: number;
  onLoadMoreSamples?: () => void;
  loadingMoreSamples?: boolean;
}) {
  const setServer = (patch: Partial<EvbFilterState['server']>) =>
    onChange({ ...state, server: { ...state.server, ...patch } });
  const setClient = (patch: Partial<EvbFilterState['client']>) =>
    onChange({ ...state, client: { ...state.client, ...patch } });

  const numField = (raw: string): number | undefined => {
    if (!raw) return undefined;
    const n = parseInt(raw, 10);
    return isNaN(n) ? undefined : n;
  };
  const floatField = (raw: string): number | undefined => {
    if (!raw) return undefined;
    const n = parseFloat(raw);
    return isNaN(n) ? undefined : n;
  };

  const dateRange: DateRangeValue = {
    after: state.server.rechdatumAfter,
    before: state.server.rechdatumBefore,
  };

  const { isVisible } = useFilterVisibility('evb', EVB_FILTER_DEFS);
  const apiVisible = isVisible('evbnr') || isVisible('rechnr') || isVisible('rechdatum') || isVisible('idnumbers') || isVisible('orderFk');
  const klassVisible = isVisible('typ') || isVisible('gesellschaft') || isVisible('reseller');

  return (
    <div className="space-y-1">
      <FilterVisibilityPicker tabKey="evb" defs={EVB_FILTER_DEFS} />

      {totalSampled !== undefined && onLoadMoreSamples && (
        <SampleSizeBanner
          totalSampled={totalSampled}
          loading={loadingMoreSamples ?? false}
          onLoadMore={onLoadMoreSamples}
        />
      )}

      {isVisible('hint') && (
        <FilterHint>
          EVBs sind Versicherungs-Datensätze. Sie haben keine Email — die abgeleiteten Empfänger werden über die
          verknüpften Geschäftskunden (idkdnr) bestimmt.
        </FilterHint>
      )}

      {apiVisible && <SectionLabel>API-Filter (Server-side)</SectionLabel>}
      {isVisible('evbnr') && (
        <FilterField label="EVB-Nr">
          <FilterInput
            value={state.server.evbnr ?? ''}
            onChange={(v) => setServer({ evbnr: v || undefined })}
            placeholder="z.B. WQUD5YF"
          />
        </FilterField>
      )}
      {isVisible('rechnr') && (
        <FilterField label="Rechnungs-Nr">
          <FilterInput
            value={state.server.rechnr ?? ''}
            onChange={(v) => setServer({ rechnr: v || undefined })}
            placeholder="z.B. C 000001/19"
          />
        </FilterField>
      )}
      {isVisible('rechdatum') && (
        <FilterField label="Rechnungsdatum">
          <DateRangeInput
            value={dateRange}
            onChange={(v) => setServer({ rechdatumAfter: v.after, rechdatumBefore: v.before })}
          />
        </FilterField>
      )}
      {isVisible('idnumbers') && (
        <div className="grid grid-cols-2 gap-1.5">
          <FilterField label="Kunden-ID (idkdnr)" layout="stacked">
            <FilterInput
              type="number"
              value={state.server.idkdnr?.toString() ?? ''}
              onChange={(v) => setServer({ idkdnr: numField(v) })}
              placeholder="ID"
            />
          </FilterField>
          <FilterField label="Business-FK" layout="stacked">
            <FilterInput
              type="number"
              value={state.server.itsBusinessData?.toString() ?? ''}
              onChange={(v) => setServer({ itsBusinessData: numField(v) })}
              placeholder="Business-ID"
            />
          </FilterField>
        </div>
      )}
      {isVisible('orderFk') && (
        <FilterField label="Order-FK">
          <FilterInput
            type="number"
            value={state.server.orderPrivateShop?.toString() ?? ''}
            onChange={(v) => setServer({ orderPrivateShop: numField(v) })}
            placeholder="Order-ID"
          />
        </FilterField>
      )}

      {klassVisible && <SectionLabel>Klassifizierung (Client-side)</SectionLabel>}
      {isVisible('typ') && (
        <FilterField label="Typ" layout="stacked">
          <CheckboxGroup
            options={EVB_TYPE_LABELS}
            value={(state.client.typIn ?? []) as ('KZK' | 'KZKA')[]}
            onChange={(v) => setClient({ typIn: v.length ? v : undefined })}
          />
        </FilterField>
      )}
      {isVisible('gesellschaft') && (
        <FilterField
          label="Versicherer (Gesellschaft)"
          hint="seltene Versicherer manuell eintragen"
          layout="stacked"
        >
          <StringMultiSelect
            options={facets.evbGesellschaft}
            value={state.client.gesellschaftIn ?? []}
            onChange={(v) => setClient({ gesellschaftIn: v.length ? v : undefined })}
            counts={facetCounts?.evbGesellschaft}
            emptyLabel="Lade Werte..."
            allowCustomAdd
            customAddPlaceholder="z.B. WPRO, AXA, GEFION…"
          />
        </FilterField>
      )}
      {isVisible('reseller') && (
        <FilterField
          label="Reseller"
          hint="seltene Werte manuell hinzufügen"
          layout="stacked"
        >
          <StringMultiSelect
            options={facets.evbReseller}
            value={state.client.resellerIn ?? []}
            onChange={(v) => setClient({ resellerIn: v.length ? v : undefined })}
            counts={facetCounts?.evbReseller}
            emptyLabel="Lade Werte..."
            allowCustomAdd
            customAddPlaceholder="z.B. its, spa…"
          />
        </FilterField>
      )}

      {isVisible('statusPreis') && (
        <CollapsibleSection title="Status & Preis">
          <TriStateToggle
            label="Storniert"
            value={state.client.storno}
            onChange={(v) => setClient({ storno: v })}
          />
          <TriStateToggle
            label="Aktiviert"
            value={state.client.aktiviert}
            onChange={(v) => setClient({ aktiviert: v })}
          />
          <TriStateToggle
            label="Bezahlt"
            value={state.client.bezahlt}
            onChange={(v) => setClient({ bezahlt: v })}
          />
          <div className="grid grid-cols-2 gap-1.5">
            <FilterField label="VK-Preis Min (€)" layout="stacked">
              <FilterInput
                type="number"
                value={state.client.vkverstMin?.toString() ?? ''}
                onChange={(v) => setClient({ vkverstMin: floatField(v) })}
                placeholder="z.B. 20"
              />
            </FilterField>
            <FilterField label="VK-Preis Max (€)" layout="stacked">
              <FilterInput
                type="number"
                value={state.client.vkverstMax?.toString() ?? ''}
                onChange={(v) => setClient({ vkverstMax: floatField(v) })}
                placeholder="z.B. 50"
              />
            </FilterField>
          </div>
        </CollapsibleSection>
      )}

      {/* Schema-Browser für ad-hoc Filter auf zusätzliche EVB-Spalten.
          Excludes = Spalten die schon im curated UI abgedeckt sind. */}
      {isVisible('schemaBrowser') && schemaColumns && onDynamicFiltersChange && (
        <SchemaBrowser
          columns={schemaColumns}
          excludeColumns={[
            'evbnr', 'rechnr', 'typ', 'gesellschaft', 'reseller', 'rechdatum',
            'storno', 'aktiviert', 'erloeschen', 'vkverst',
          ]}
          value={dynamicFilters ?? []}
          onChange={onDynamicFiltersChange}
        />
      )}
    </div>
  );
}

export function serializeEvbFilter(s: EvbFilterState) {
  return { server: s.server, client: s.client };
}
