'use client'

import { FormEvent, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/Button/Button'
import styles from './styles.module.scss'

type Option = {
  slug: string
  name: string
}

type EventFilterBarProps = {
  groups: Option[]
  parishes: Option[]
  initial: {
    group?: string
    parish?: string
    from?: string
    to?: string
  }
}

export const EventFilterBar = ({ groups, parishes, initial }: EventFilterBarProps) => {
  const router = useRouter()
  const [group, setGroup] = useState(initial.group ?? '')
  const [parish, setParish] = useState(initial.parish ?? '')
  const [from, setFrom] = useState(initial.from ?? '')
  const [to, setTo] = useState(initial.to ?? '')

  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    const params = new URLSearchParams()
    if (group) params.set('group', group)
    if (parish) params.set('parish', parish)
    if (from) params.set('from', from)
    if (to) params.set('to', to)
    const qs = params.toString()
    router.push(qs ? `/veranstaltungen?${qs}` : '/veranstaltungen')
  }

  return (
    <form className={styles.bar} onSubmit={handleSubmit}>
      <label className={styles.field}>
        <span className={styles.label}>Gemeinde</span>
        <select
          name="parish"
          value={parish}
          onChange={(e) => setParish(e.target.value)}
          className={styles.input}
        >
          <option value="">Alle Gemeinden</option>
          {parishes.map((p) => (
            <option key={p.slug} value={p.slug}>
              {p.name}
            </option>
          ))}
        </select>
      </label>

      <label className={styles.field}>
        <span className={styles.label}>Gruppe</span>
        <select
          name="group"
          value={group}
          onChange={(e) => setGroup(e.target.value)}
          className={styles.input}
        >
          <option value="">Alle Gruppen</option>
          {groups.map((g) => (
            <option key={g.slug} value={g.slug}>
              {g.name}
            </option>
          ))}
        </select>
      </label>

      <label className={styles.field}>
        <span className={styles.label}>Von</span>
        <input
          type="date"
          name="from"
          value={from}
          onChange={(e) => setFrom(e.target.value)}
          className={styles.input}
        />
      </label>

      <label className={styles.field}>
        <span className={styles.label}>Bis</span>
        <input
          type="date"
          name="to"
          value={to}
          onChange={(e) => setTo(e.target.value)}
          className={styles.input}
        />
      </label>

      <div className={styles.actions}>
        <Button type="submit" size="md">
          Filtern
        </Button>
      </div>
    </form>
  )
}
