import { useState } from 'react';
import { FILTER_CATEGORIES, FilterDef, FilterParam } from '../stores/filterDefs';

interface FilterDialogProps {
  filterId: string;
  onApply: (filterId: string, params: Record<string, number | boolean | string>) => void;
  onClose: () => void;
}

function findFilter(id: string): FilterDef | undefined {
  for (const cat of FILTER_CATEGORIES) {
    for (const f of cat.filters) if (f.id === id) return f;
  }
  return undefined;
}

export function FilterDialog({ filterId, onApply, onClose }: FilterDialogProps) {
  const filter = findFilter(filterId);
  if (!filter) return null;

  return <FilterDialogInner filter={filter} onApply={onApply} onClose={onClose} />;
}

function FilterDialogInner({ filter, onApply, onClose }: { filter: FilterDef; onApply: (id: string, p: Record<string, number | boolean | string>) => void; onClose: () => void }) {
  const [params, setParams] = useState<Record<string, number | boolean | string>>(() => {
    const d: Record<string, number | boolean | string> = {};
    for (const p of filter.params) d[p.key] = p.default as number | boolean | string;
    return d;
  });

  return (
    <div data-testid="filter-dialog" style={{
      position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
      background: '#f5f5f5', border: '1px solid #a0a0a0', borderRadius: 4,
      boxShadow: '4px 4px 12px rgba(0,0,0,0.3)', zIndex: 300,
      minWidth: 300, fontFamily: 'system-ui, sans-serif', fontSize: 13, color: '#1a1a1a',
    }}>
      <div data-testid="filter-dialog-title" style={{
        padding: '6px 12px', background: '#e0e0e0', borderBottom: '1px solid #c0c0c0',
        display: 'flex', justifyContent: 'space-between', fontWeight: 'bold', fontSize: 13,
      }}>
        <span>{filter.name}</span>
        <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 14 }}>×</button>
      </div>

      <div style={{ padding: 12 }}>
        {filter.params.map((p) => (
          <DialogParam key={p.key} param={p} value={params[p.key]} onChange={(v) => setParams((prev) => ({ ...prev, [p.key]: v }))} />
        ))}
        {filter.params.length === 0 && <div style={{ color: '#888', fontStyle: 'italic' }}>No parameters</div>}
      </div>

      <div style={{ padding: '8px 12px', borderTop: '1px solid #d0d0d0', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <button data-testid="filter-apply" onClick={() => onApply(filter.id, params)}
          style={{ padding: '4px 16px', background: '#e0e0e0', border: '1px solid #a0a0a0', borderRadius: 3, cursor: 'pointer' }}>
          Apply
        </button>
        <button data-testid="filter-close" onClick={onClose}
          style={{ padding: '4px 16px', background: '#e0e0e0', border: '1px solid #a0a0a0', borderRadius: 3, cursor: 'pointer' }}>
          Close
        </button>
      </div>
    </div>
  );
}

function DialogParam({ param, value, onChange }: { param: FilterParam; value: number | boolean | string; onChange: (v: number | boolean | string) => void }) {
  const labelStyle: React.CSSProperties = { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 };
  const inputStyle: React.CSSProperties = { padding: '2px 6px', border: '1px solid #a0a0a0', borderRadius: 2, background: '#fff', width: 120 };

  return (
    <label style={labelStyle}>
      <span style={{ minWidth: 120 }}>{param.label}:</span>
      {param.type === 'bool' ? (
        <input type="checkbox" checked={value as boolean} onChange={(e) => onChange(e.target.checked)} />
      ) : param.type === 'select' ? (
        <select value={value as string} onChange={(e) => onChange(e.target.value)} style={inputStyle}>
          {param.options?.map((o) => <option key={o} value={o}>{o}</option>)}
        </select>
      ) : (
        <input type="number" value={value as number} min={param.min} max={param.max}
          step={param.step ?? (param.type === 'int' ? 1 : 0.01)}
          onChange={(e) => onChange(param.type === 'int' ? parseInt(e.target.value) || 0 : parseFloat(e.target.value) || 0)}
          style={inputStyle} />
      )}
    </label>
  );
}
