"use client"

import { useQueryState, parseAsString } from "nuqs"

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { Input } from "@/shared/components/ui/input"
import { FilterBar } from "@/shared/components/ui/filter-bar"

interface AuditLogFiltersProps {
  moduleOptions: string[]
}

export function AuditLogFilters({ moduleOptions }: AuditLogFiltersProps) {
  const [module, setModule] = useQueryState("module", parseAsString.withOptions({ shallow: false }))
  const [action, setAction] = useQueryState("action", parseAsString.withOptions({ shallow: false }))
  const [status, setStatus] = useQueryState("status", parseAsString.withOptions({ shallow: false }))
  const [startDate, setStartDate] = useQueryState(
    "startDate",
    parseAsString.withOptions({ shallow: false }),
  )
  const [endDate, setEndDate] = useQueryState(
    "endDate",
    parseAsString.withOptions({ shallow: false }),
  )

  const hasFilters = Boolean(module || action || status || startDate || endDate)

  return (
    <FilterBar
      layout="wrap"
      hasFilters={hasFilters}
      onReset={() => {
        setModule(null)
        setAction(null)
        setStatus(null)
        setStartDate(null)
        setEndDate(null)
      }}
    >
      <Select value={module || "all"} onValueChange={(val) => setModule(val === "all" ? null : val)}>
        <SelectTrigger className="w-[160px] bg-background">
          <SelectValue placeholder="Module" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">Any Module</SelectItem>
          {moduleOptions.map((m) => (
            <SelectItem key={m} value={m}>
              {m}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      <Input
        placeholder="Action..."
        className="w-full md:w-[180px] bg-background"
        value={action || ""}
        onChange={(e) => setAction(e.target.value || null)}
      />

      <Select value={status || "all"} onValueChange={(val) => setStatus(val === "all" ? null : val)}>
        <SelectTrigger className="w-[140px] bg-background">
          <SelectValue placeholder="Status" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">Any Status</SelectItem>
          <SelectItem value="success">Success</SelectItem>
          <SelectItem value="failure">Failure</SelectItem>
        </SelectContent>
      </Select>

      <Input
        type="date"
        className="w-full md:w-[160px] bg-background"
        value={startDate || ""}
        onChange={(e) => setStartDate(e.target.value || null)}
      />
      <Input
        type="date"
        className="w-full md:w-[160px] bg-background"
        value={endDate || ""}
        onChange={(e) => setEndDate(e.target.value || null)}
      />
    </FilterBar>
  )
}
