'use client'

import { useRouter, useSearchParams } from 'next/navigation'

type Preset = {
  key: string
  label: string
  hint: string
  build: (current: URLSearchParams) => URLSearchParams
}

// Each preset returns the URL params to apply. We don't preserve other
// filter params — these are one-click resets to a known view. Click again
// to clear (handled by the "active" check below).

const PRESETS: Preset[] = [
  {
    key: 'hourly',
    label: 'Hourly',
    hint: 'Projects with "hour" in the name, sorted by billout hours.',
    build: () => {
      const p = new URLSearchParams()
      p.set('date', 'all')
      p.set('project', 'hour')
      p.set('sort', 'billout_hrs')
      p.set('dir', 'desc')
      return p
    },
  },
  {
    key: 'missing-info',
    label: 'Missing info',
    hint: 'Projects missing operator, client, or project name.',
    build: () => {
      const p = new URLSearchParams()
      p.set('date', 'all')
      p.set('missing_info', '1')
      return p
    },
  },
  {
    key: 'last-month-admin',
    label: 'Last month admin',
    hint: 'Projects with "admin" in the name, restricted to last month.',
    build: () => {
      const p = new URLSearchParams()
      p.set('date', 'last-month')
      p.set('project', 'admin')
      return p
    },
  },
]

function matchesPreset(p: Preset, current: URLSearchParams): boolean {
  const target = p.build(current)
  // A preset is "active" when every param it sets is present with the
  // same value in the current URL.
  for (const [k, v] of target) {
    if (current.get(k) !== v) return false
  }
  return true
}

export function QuickFilters() {
  const router = useRouter()
  const params = useSearchParams()

  function apply(p: Preset) {
    const next = p.build(new URLSearchParams())
    router.push(`/projects?${next.toString()}`)
  }

  return (
    <div
      style={{
        display: 'flex',
        gap: '0.4rem',
        flexWrap: 'wrap',
        margin: '0 0 0.5rem',
      }}
    >
      <span
        className="muted"
        style={{
          alignSelf: 'center',
          fontSize: '0.85em',
          marginRight: '0.25rem',
        }}
      >
        Quick filters:
      </span>
      {PRESETS.map((p) => {
        const active = matchesPreset(p, new URLSearchParams(params.toString()))
        return (
          <button
            type="button"
            key={p.key}
            onClick={() => apply(p)}
            title={p.hint}
            className={active ? '' : 'secondary'}
            style={{ padding: '0.3rem 0.7rem', fontSize: '0.85em' }}
          >
            {p.label}
          </button>
        )
      })}
    </div>
  )
}
