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

interface FilterPanelProps {
  onApplyFilter: (filterId: string, params: Record<string, number | boolean | string>) => void;
}

export function FilterPanel({ onApplyFilter }: FilterPanelProps) {
  const [openCategory, setOpenCategory] = useState<string | null>('Transform');
  const [selectedFilter, setSelectedFilter] = useState<FilterDef | null>(null);
  const [paramValues, setParamValues] = useState<Record<string, number | boolean | string>>({});

  const selectFilter = (filter: FilterDef) => {
    setSelectedFilter(filter);
    const defaults: Record<string, number | boolean | string> = {};
    for (const p of filter.params) {
      defaults[p.key] = p.default;
    }
    setParamValues(defaults);
  };

  const handleApply = () => {
    if (!selectedFilter) return;
    onApplyFilter(selectedFilter.id, paramValues);
  };

  return (
    <div
      data-testid="filter-panel"
      style={{
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        background: '#252526',
        color: '#ccc',
        fontSize: 12,
        fontFamily: 'monospace',
      }}
    >
      <div style={{ padding: '6px 10px', fontWeight: 'bold', borderBottom: '1px solid #333' }}>
        Filters
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }}>
        {FILTER_CATEGORIES.map((cat) => (
          <div key={cat.name}>
            <div
              data-testid="filter-category"
              onClick={() => setOpenCategory(openCategory === cat.name ? null : cat.name)}
              style={{
                padding: '5px 8px',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                gap: 4,
                background: '#2d2d2d',
                borderBottom: '1px solid #333',
                fontWeight: 'bold',
              }}
            >
              {openCategory === cat.name ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
              {cat.name}
            </div>
            {openCategory === cat.name && cat.filters.map((f) => (
              <div
                key={f.id}
                data-testid={`filter-${f.id}`}
                onClick={() => f.implemented && selectFilter(f)}
                style={{
                  padding: '4px 8px 4px 22px',
                  cursor: f.implemented ? 'pointer' : 'default',
                  opacity: f.implemented ? 1 : 0.4,
                  background: selectedFilter?.id === f.id ? '#094771' : 'transparent',
                  borderBottom: '1px solid #2a2a2a',
                }}
                title={f.implemented ? '' : 'Not yet implemented'}
              >
                {f.name}
              </div>
            ))}
          </div>
        ))}
      </div>

      {/* Parameter form */}
      {selectedFilter && (
        <div style={{ borderTop: '1px solid #444', padding: 8 }}>
          <div style={{ fontWeight: 'bold', marginBottom: 6 }}>{selectedFilter.name}</div>
          {selectedFilter.params.map((p) => (
            <ParamInput
              key={p.key}
              param={p}
              value={paramValues[p.key]}
              onChange={(val) => setParamValues((prev) => ({ ...prev, [p.key]: val }))}
            />
          ))}
          <button
            data-testid="apply-filter"
            onClick={handleApply}
            disabled={!selectedFilter.implemented}
            style={{
              marginTop: 6,
              width: '100%',
              padding: '5px 0',
              background: selectedFilter.implemented ? '#4a90d9' : '#555',
              color: '#fff',
              border: 'none',
              borderRadius: 3,
              cursor: selectedFilter.implemented ? 'pointer' : 'default',
              fontSize: 12,
            }}
          >
            Apply
          </button>
        </div>
      )}
    </div>
  );
}

function ParamInput({
  param,
  value,
  onChange,
}: {
  param: FilterParam;
  value: number | boolean | string;
  onChange: (v: number | boolean | string) => void;
}) {
  const inputStyle: React.CSSProperties = {
    width: '100%',
    padding: '2px 4px',
    background: '#1e1e1e',
    color: '#ccc',
    border: '1px solid #444',
    borderRadius: 2,
    fontSize: 12,
  };

  return (
    <div style={{ marginBottom: 4 }}>
      <label style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <span style={{ width: 70, flexShrink: 0 }}>{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>
    </div>
  );
}
