"use client"

import { useMemo } from "react"
import { SlidersHorizontal } from "lucide-react"

import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { priorityStyles } from "@/lib/ticket-priority-style"
import { cn } from "@/lib/utils"
import type { TicketPriority } from "@/lib/schemas/ticket"

export type AgendaPeriod = "today" | "week" | "month"

export type AgendaFilterState = {
  period: AgendaPeriod
  queues: string[]
  priorities: TicketPriority[]
  onlyMyTickets: boolean
  focusVisits: boolean
}

export const defaultAgendaFilters: AgendaFilterState = {
  period: "week",
  queues: [],
  priorities: [],
  onlyMyTickets: true,
  focusVisits: false,
}

type AgendaFiltersProps = {
  filters: AgendaFilterState
  queues: string[]
  onChange: (next: AgendaFilterState) => void
}

export function AgendaFilters({ filters, queues, onChange }: AgendaFiltersProps) {
  const periodOptions: Array<{ value: AgendaPeriod; label: string }> = [
    { value: "today", label: "Hoje" },
    { value: "week", label: "Semana" },
    { value: "month", label: "Mês" },
  ]

  const queueLabel = useMemo(() => {
    if (filters.queues.length === 0) return "Todas as filas"
    if (filters.queues.length === 1) return filters.queues[0]
    return `${filters.queues[0]} +${filters.queues.length - 1}`
  }, [filters.queues])

  const priorityLabel = useMemo(() => {
    if (filters.priorities.length === 0) return "Todas prioridades"
    if (filters.priorities.length === 1) {
      return priorityStyles[filters.priorities[0]].label
    }
    return `${priorityStyles[filters.priorities[0]].label} +${filters.priorities.length - 1}`
  }, [filters.priorities])

  const updateFilters = (partial: Partial<AgendaFilterState>) => {
    onChange({ ...filters, ...partial })
  }

  const handleQueueToggle = (queue: string, checked: boolean) => {
    const set = new Set(filters.queues)
    if (checked) {
      set.add(queue)
    } else {
      set.delete(queue)
    }
    updateFilters({ queues: Array.from(set) })
  }

  const handlePriorityToggle = (priority: TicketPriority, checked: boolean) => {
    const set = new Set(filters.priorities)
    if (checked) {
      set.add(priority)
    } else {
      set.delete(priority)
    }
    updateFilters({ priorities: Array.from(set) })
  }

  const resetFilters = () => {
    onChange(defaultAgendaFilters)
  }

  return (
    <div className="flex flex-col gap-3 rounded-2xl border border-border/70 bg-card/70 p-4 shadow-sm sm:flex-row sm:items-center sm:justify-between">
      <div className="flex flex-wrap items-center gap-3">
        <div className="flex flex-wrap items-center gap-2 rounded-2xl border border-slate-200 bg-white/80 px-2 py-1.5 shadow-sm">
          {periodOptions.map((option) => {
            const isActive = filters.period === option.value
            return (
              <Button
                key={option.value}
                type="button"
                size="sm"
                variant={isActive ? "secondary" : "ghost"}
                onClick={() => updateFilters({ period: option.value })}
                className={cn(
                  "gap-2 rounded-full border px-3 text-sm font-medium transition",
                  isActive
                    ? "border-slate-200 bg-slate-900 text-white"
                    : "border-slate-200 text-neutral-700 hover:border-slate-300 hover:bg-white"
                )}
              >
                {option.label}
              </Button>
            )
          })}
        </div>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" className="gap-2">
              {queueLabel}
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent className="w-56" align="start">
            <DropdownMenuLabel>Filtrar filas</DropdownMenuLabel>
            <DropdownMenuSeparator />
            {queues.length === 0 ? (
              <div className="px-2 py-1.5 text-sm text-muted-foreground">Nenhuma fila disponível.</div>
            ) : (
              queues.map((queue) => (
                <DropdownMenuCheckboxItem
                  key={queue}
                  checked={filters.queues.includes(queue)}
                  onCheckedChange={(checked) => handleQueueToggle(queue, Boolean(checked))}
                >
                  {queue}
                </DropdownMenuCheckboxItem>
              ))
            )}
          </DropdownMenuContent>
        </DropdownMenu>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" className="gap-2">
              {priorityLabel}
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent className="w-64" align="start">
            <DropdownMenuLabel>Prioridades</DropdownMenuLabel>
            <DropdownMenuSeparator />
            {(Object.keys(priorityStyles) as TicketPriority[]).map((priority) => (
              <DropdownMenuCheckboxItem
                key={priority}
                checked={filters.priorities.includes(priority)}
                onCheckedChange={(checked) => handlePriorityToggle(priority, Boolean(checked))}
                className="gap-2"
              >
                <div className="flex items-center gap-2">
                  <Badge className={cn("rounded-full px-2.5 py-0.5 text-xs font-semibold", priorityStyles[priority].badgeClass ?? "")}>
                    {priorityStyles[priority].label}
                  </Badge>
                  <span className="text-sm text-foreground">{priorityStyles[priority].label}</span>
                </div>
              </DropdownMenuCheckboxItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
      <div className="flex flex-wrap items-center gap-4">
        <div className="flex items-center gap-2">
          <Switch
            id="onlyMe"
            checked={filters.onlyMyTickets}
            onCheckedChange={(checked) => updateFilters({ onlyMyTickets: checked })}
            className="data-[state=checked]:border-sidebar-ring data-[state=checked]:bg-sidebar-accent"
          />
          <Label htmlFor="onlyMe" className="text-sm text-muted-foreground">
            Somente meus tickets
          </Label>
        </div>
        <div className="flex items-center gap-2">
          <Switch
            id="visitsOnly"
            checked={filters.focusVisits}
            onCheckedChange={(checked) => updateFilters({ focusVisits: checked })}
            className="data-[state=checked]:border-sidebar-ring data-[state=checked]:bg-sidebar-accent"
          />
          <Label htmlFor="visitsOnly" className="text-sm text-muted-foreground">
            Apenas visitas
          </Label>
        </div>
        <Button variant="ghost" size="sm" className="gap-2" onClick={resetFilters}>
          <SlidersHorizontal className="size-4" />
          Resetar
        </Button>
      </div>
    </div>
  )
}
