const FILTER_FIELDS = [
  { key: 'completed',    label: 'Status',      options: [{ value: '', label: 'All' }, { value: 'true', label: 'Completed' }, { value: 'false', label: 'Pending' }] },
  { key: 'interference', label: 'Type', options: [{ value: '', label: 'All' }, { value: 'COE', label: 'COE' }, { value: 'P2P', label: 'P2P' }, { value: 'P3P', label: 'P3P' }] },
]

const DERIVED_FIELDS = [
  { key: 'device',    label: 'Device' },
  { key: 'rotation',  label: 'Rotation' },
  { key: 'test_point', label: 'Test Point' },
  { key: 'rssi',      label: 'RSSI' },
  { key: 'station',   label: 'Station' },
  { key: 'band',      label: 'Band' },
  { key: 'channel',   label: 'Channel' },
  { key: 'bandwidth', label: 'Bandwidth' },
  { key: 'direction', label: 'Direction' },
]

function unique(tests, key) {
  return [...new Set(tests.map(t => t[key]).filter(Boolean))].sort()
}

export default function FilterPanel({ filters, onChange, allTests = [] }) {
  function set(key, value) {
    onChange({ ...filters, [key]: value })
  }

  function reset() {
    onChange({})
  }

  const hasActive = Object.values(filters).some(v => v !== '' && v != null)

  return (
    <div className="flex flex-wrap gap-2 items-center">
      {FILTER_FIELDS.map(({ key, label, options }) => (
        <select
          key={key}
          value={filters[key] ?? ''}
          onChange={e => set(key, e.target.value)}
          className="bg-slate-800 border border-slate-700 text-slate-200 text-sm rounded-lg px-3 py-1.5 focus:outline-none focus:border-blue-500"
        >
          <option value="">{label}: All</option>
          {options.slice(1).map(o => (
            <option key={o.value} value={o.value}>{o.label}</option>
          ))}
        </select>
      ))}

      {DERIVED_FIELDS.map(({ key, label }) => {
        const vals = unique(allTests, key)
        if (vals.length === 0) return null
        return (
          <select
            key={key}
            value={filters[key] ?? ''}
            onChange={e => set(key, e.target.value)}
            className="bg-slate-800 border border-slate-700 text-slate-200 text-sm rounded-lg px-3 py-1.5 focus:outline-none focus:border-blue-500"
          >
            <option value="">{label}: All</option>
            {vals.map(v => <option key={v} value={v}>{v}</option>)}
          </select>
        )
      })}

      {hasActive && (
        <button
          onClick={reset}
          className="text-slate-400 hover:text-slate-200 text-sm px-2 py-1.5 rounded-lg hover:bg-slate-800 transition-colors"
        >
          ✕ Clear
        </button>
      )}
    </div>
  )
}
