"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"

export function LoginLogFilters() {
  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(action || status || startDate || endDate)

  return (
    <FilterBar
      layout="wrap"
      hasFilters={hasFilters}
      onReset={() => {
        setAction(null)
        setStatus(null)
        setStartDate(null)
        setEndDate(null)
      }}
    >
      <Select value={action || "all"} onValueChange={(val) => setAction(val === "all" ? null : val)}>
        <SelectTrigger className="w-[140px] bg-background">
          <SelectValue placeholder="Action" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">Any Action</SelectItem>
          <SelectItem value="signin">Sign In</SelectItem>
          <SelectItem value="signout">Sign Out</SelectItem>
          <SelectItem value="signup">Sign Up</SelectItem>
        </SelectContent>
      </Select>

      <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>
  )
}
