"use client"

import { useEffect, useMemo, useState } from "react"
import { IconFilter, IconRefresh } from "@tabler/icons-react"

import {
  ticketChannelSchema,
  ticketPrioritySchema,
  type TicketStatus,
} from "@/lib/schemas/ticket"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"

const statusOptions: Array<{ value: TicketStatus; label: string }> = [
  { value: "PENDING", label: "Pendente" },
  { value: "AWAITING_ATTENDANCE", label: "Aguardando atendimento" },
  { value: "PAUSED", label: "Pausado" },
  { value: "RESOLVED", label: "Resolvido" },
]

const statusLabelMap = statusOptions.reduce<Record<TicketStatus, string>>((acc, option) => {
  acc[option.value] = option.label
  return acc
}, {} as Record<TicketStatus, string>)

const priorityOptions = ticketPrioritySchema.options.map((priority) => ({
  value: priority,
  label: {
    LOW: "Baixa",
    MEDIUM: "Média",
    HIGH: "Alta",
    URGENT: "Urgente",
  }[priority],
}))

const channelOptions = ticketChannelSchema.options.map((channel) => ({
  value: channel,
  label: {
    EMAIL: "E-mail",
    WHATSAPP: "WhatsApp",
    CHAT: "Chat",
    PHONE: "Telefone",
    API: "API",
    MANUAL: "Manual",
  }[channel],
}))

type QueueOption = string

export type TicketFiltersState = {
  search: string
  status: TicketStatus | null
  priority: string | null
  queue: string | null
  channel: string | null
  company: string | null
  view: "active" | "completed"
}

export const defaultTicketFilters: TicketFiltersState = {
  search: "",
  status: null,
  priority: null,
  queue: null,
  channel: null,
  company: null,
  view: "active",
}

interface TicketsFiltersProps {
  onChange?: (filters: TicketFiltersState) => void
  queues?: QueueOption[]
  companies?: string[]
}

const ALL_VALUE = "ALL"

export function TicketsFilters({ onChange, queues = [], companies = [] }: TicketsFiltersProps) {
  const [filters, setFilters] = useState<TicketFiltersState>(defaultTicketFilters)

  function setPartial(partial: Partial<TicketFiltersState>) {
    setFilters((prev) => ({ ...prev, ...partial }))
  }

  // Propaga as mudancas de filtros para o componente pai sem disparar durante a renderizacao
  useEffect(() => {
    onChange?.(filters)
  }, [filters, onChange])

  const activeFilters = useMemo(() => {
    const chips: string[] = []
    if (filters.status) chips.push(`Status: ${statusLabelMap[filters.status] ?? filters.status}`)
    if (filters.priority) chips.push(`Prioridade: ${filters.priority}`)
    if (filters.queue) chips.push(`Fila: ${filters.queue}`)
    if (filters.channel) chips.push(`Canal: ${filters.channel}`)
    if (filters.company) chips.push(`Empresa: ${filters.company}`)
    if (!filters.status && filters.view === "completed") chips.push("Exibindo concluídos")
    return chips
  }, [filters])

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
        <div className="flex flex-1 flex-col gap-2 md:flex-row">
          <Input
            placeholder="Buscar por assunto ou #ID"
            value={filters.search}
            onChange={(event) => setPartial({ search: event.target.value })}
            className="md:max-w-sm"
          />
          <Select
            value={filters.queue ?? ALL_VALUE}
            onValueChange={(value) => setPartial({ queue: value === ALL_VALUE ? null : value })}
          >
            <SelectTrigger className="md:w-[180px]">
              <SelectValue placeholder="Fila" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={ALL_VALUE}>Todas as filas</SelectItem>
              {queues.map((queue) => (
                <SelectItem key={queue!} value={queue!}>
                  {queue}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select
            value={filters.company ?? ALL_VALUE}
            onValueChange={(value) => setPartial({ company: value === ALL_VALUE ? null : value })}
          >
            <SelectTrigger className="md:w-[220px]">
              <SelectValue placeholder="Empresa" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={ALL_VALUE}>Todas as empresas</SelectItem>
              {companies.map((company) => (
                <SelectItem key={company!} value={company!}>
                  {company}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="flex items-center gap-2">
          <Select
            value={filters.view}
            onValueChange={(value) => setPartial({ view: value as TicketFiltersState["view"] })}
          >
            <SelectTrigger className="w-[150px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="active">Em andamento</SelectItem>
              <SelectItem value="completed">Concluídos</SelectItem>
            </SelectContent>
          </Select>
          <Popover>
            <PopoverTrigger asChild>
              <Button
                variant="outline"
                size="sm"
                className="gap-2 rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm font-medium text-neutral-800 shadow-sm hover:bg-slate-50"
              >
                <IconFilter className="size-4 text-neutral-800" />
                Filtros
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-64 space-y-4">
              <div className="space-y-2">
                <p className="text-xs font-semibold uppercase text-neutral-500">
                  Status
                </p>
                <Select
                  value={filters.status ?? ALL_VALUE}
                  onValueChange={(value) =>
                    setPartial({ status: value === ALL_VALUE ? null : (value as TicketStatus) })
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Todos" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={ALL_VALUE}>Todos</SelectItem>
                    {statusOptions.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <p className="text-xs font-semibold uppercase text-neutral-500">
                  Prioridade
                </p>
                <Select
                  value={filters.priority ?? ALL_VALUE}
                  onValueChange={(value) => setPartial({ priority: value === ALL_VALUE ? null : value })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Todas" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={ALL_VALUE}>Todas</SelectItem>
                    {priorityOptions.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <p className="text-xs font-semibold uppercase text-neutral-500">
                  Canal
                </p>
                <Select
                  value={filters.channel ?? ALL_VALUE}
                  onValueChange={(value) => setPartial({ channel: value === ALL_VALUE ? null : value })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Todos" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={ALL_VALUE}>Todos</SelectItem>
                    {channelOptions.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </PopoverContent>
          </Popover>
          <Button
            variant="ghost"
            size="sm"
            className="gap-2 rounded-lg px-3 py-2 text-sm font-medium text-neutral-700 hover:bg-slate-100"
            onClick={() => setPartial(defaultTicketFilters)}
          >
            <IconRefresh className="size-4" />
            Resetar
          </Button>
        </div>
      </div>
      {activeFilters.length > 0 && (
        <div className="flex flex-wrap gap-2">
          {activeFilters.map((chip) => (
            <Badge key={chip} className="rounded-full border border-slate-300 bg-slate-100 px-3 py-1 text-xs font-medium text-neutral-700">
              {chip}
            </Badge>
          ))}
        </div>
      )}
    </div>
  )
}
