"use client"

import { useEffect, useMemo, useState } from "react"
import { IconFilter, IconRefresh, IconSearch, IconList, IconBuilding, IconTags, IconUser } from "@tabler/icons-react"

import { ticketPrioritySchema, type TicketStatus } from "@/lib/schemas/ticket"
import { PriorityIcon } from "@/components/tickets/priority-select"
import type { TicketFiltersState } from "@/lib/ticket-filters"
import { defaultTicketFilters } from "@/lib/ticket-filters"

export type { TicketFiltersState }
export { defaultTicketFilters }

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"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { SearchableCombobox, type SearchableComboboxOption } from "@/components/ui/searchable-combobox"
import { DateRangeButton } from "@/components/date-range-button"

type QueueOption = string

interface TicketsFiltersProps {
  onChange?: (filters: TicketFiltersState) => void
  queues?: QueueOption[]
  companies?: string[]
  assignees?: Array<{ id: string; name: string }>
  categories?: Array<{ id: string; name: string }>
  initialState?: Partial<TicketFiltersState>
  viewerRole?: string | null
}

const ALL_VALUE = "ALL"

const statusOptions: Array<{ value: TicketStatus; label: string }> = [
  { value: "PENDING", label: "Pendente" },
  { value: "AWAITING_ATTENDANCE", label: "Em andamento" },
  { 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],
}))

export function TicketsFilters({
  onChange,
  queues = [],
  companies = [],
  assignees = [],
  categories = [],
  initialState,
  viewerRole,
}: TicketsFiltersProps) {
  const mergedDefaults = useMemo(
    () => ({
      ...defaultTicketFilters,
      ...(initialState ?? {}),
    }),
    [initialState]
  )
  const [filters, setFilters] = useState<TicketFiltersState>(mergedDefaults)

  useEffect(() => {
    setFilters(mergedDefaults)
  }, [mergedDefaults])

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

  useEffect(() => {
    onChange?.(filters)
  }, [filters, onChange])

  const normalizedRole = viewerRole?.toLowerCase() ?? null
  const canUseAdvancedFilters = normalizedRole === "admin" || normalizedRole === "agent"

  const companyOptionsMemo = useMemo<SearchableComboboxOption[]>(() => {
    return Array.from(new Set(companies.filter((company): company is string => Boolean(company)))).map((company) => ({
      value: company,
      label: company,
    }))
  }, [companies])

  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 && canUseAdvancedFilters) chips.push(`Fila: ${filters.queue}`)
    if (filters.channel) chips.push(`Canal: ${filters.channel}`)
    if (filters.company && canUseAdvancedFilters) chips.push(`Empresa: ${filters.company}`)
    if (filters.assigneeId && canUseAdvancedFilters) {
      const found = assignees.find((a) => a.id === filters.assigneeId)
      chips.push(`Responsável: ${found?.name ?? filters.assigneeId}`)
    }
    if (filters.categoryId) {
      const category = categories.find((category) => category.id === filters.categoryId)
      chips.push(`Categoria: ${category?.name ?? filters.categoryId}`)
    }
    if (!filters.status && filters.view === "completed") chips.push("Exibindo concluídos")
    if (filters.focusVisits) chips.push("Somente visitas/lab")
    if (filters.dateFrom || filters.dateTo) chips.push(formatDateRangeChip(filters.dateFrom, filters.dateTo))
    if (filters.sort === "oldest") chips.push("Ordenados por mais antigos")
    return chips
  }, [filters, assignees, categories, canUseAdvancedFilters])

  const advancedFiltersCount = Number(Boolean(filters.status)) + Number(Boolean(filters.priority))

  return (
    <div className="flex flex-col gap-4">
      <section className="rounded-3xl border border-slate-200 bg-white/90 p-4 shadow-sm">
        <div className="flex flex-col gap-4">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:gap-4">
            <div className="flex flex-1 flex-col gap-2">
              <div className="relative">
                <IconSearch className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-neutral-400" />
                <Input
                  placeholder="Buscar por assunto ou #ID"
                  value={filters.search}
                  onChange={(event) => setPartial({ search: event.target.value })}
                  className="w-full rounded-2xl border-slate-300 bg-white/95 pl-9"
                />
              </div>
            </div>
            <div className="flex flex-wrap items-center gap-2">
              <DateRangeButton
                from={filters.dateFrom}
                to={filters.dateTo}
                onChange={({ from, to }) => setPartial({ dateFrom: from, dateTo: to })}
                className="w-full min-w-[200px] rounded-2xl border-slate-300 bg-white/95 text-left text-sm font-semibold text-neutral-700 lg:w-auto"
                align="center"
              />
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    variant="ghost"
                    className="h-10 gap-2 rounded-full px-4 text-sm font-medium text-neutral-700 hover:bg-slate-100"
                  >
                    <IconFilter className="size-4" />
                    <span>Filtros rápidos</span>
                    {advancedFiltersCount > 0 ? (
                      <Badge className="rounded-full bg-neutral-900 px-2 py-0 text-[0.65rem] font-semibold text-white">
                        {advancedFiltersCount}
                      </Badge>
                    ) : null}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-72 space-y-4" align="end">
                  <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 className="w-full">
                        <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 className="w-full">
                        <SelectValue placeholder="Todas" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value={ALL_VALUE}>Todas</SelectItem>
                        {priorityOptions.map((option) => (
                          <SelectItem key={option.value} value={option.value}>
                            <span className="flex items-center gap-2">
                              <PriorityIcon value={option.value} />
                              {option.label}
                            </span>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </PopoverContent>
              </Popover>
              <Button
                variant="ghost"
                className="h-10 gap-2 rounded-full text-sm font-medium text-neutral-700 hover:bg-slate-100"
                onClick={() => setFilters(mergedDefaults)}
              >
                <IconRefresh className="size-4" />
                Limpar
              </Button>
            </div>
          </div>
          <div className="flex flex-wrap gap-3">
            {canUseAdvancedFilters && (
              <div className={fieldWrap}>
                <Select
                  value={filters.queue ?? ALL_VALUE}
                  onValueChange={(value) => setPartial({ queue: value === ALL_VALUE ? null : value })}
                >
                  <SelectTrigger className={fieldTrigger}>
                    <IconList className="size-4 text-neutral-400" />
                    <SelectValue placeholder="Fila" className="flex-1 text-left" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={ALL_VALUE}>Todas as filas</SelectItem>
                    {queues.map((queue) => (
                      <SelectItem key={queue!} value={queue!}>
                        {queue}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
            {canUseAdvancedFilters && (
              <div className={fieldWrap}>
                <SearchableCombobox
                  value={filters.company}
                  onValueChange={(value) => setPartial({ company: value })}
                  options={companyOptionsMemo}
                  placeholder="Empresa"
                  allowClear
                  clearLabel="Todas as empresas"
                  triggerClassName={fieldTrigger}
                  prefix={<IconBuilding className="size-4 text-neutral-400" />}
                  align="center"
                />
              </div>
            )}
            <div className={fieldWrap}>
              <Select
                value={filters.categoryId ?? ALL_VALUE}
                onValueChange={(value) => setPartial({ categoryId: value === ALL_VALUE ? null : value })}
              >
                <SelectTrigger className={fieldTrigger}>
                  <IconTags className="size-4 text-neutral-400" />
                  <SelectValue placeholder="Categoria" className="flex-1 text-left" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value={ALL_VALUE}>Todas as categorias</SelectItem>
                  {categories.map((category) => (
                    <SelectItem key={category.id} value={category.id}>
                      {category.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            {canUseAdvancedFilters && (
              <div className={fieldWrap}>
                <Select
                  value={filters.assigneeId ?? ALL_VALUE}
                  onValueChange={(value) => setPartial({ assigneeId: value === ALL_VALUE ? null : value })}
                >
                  <SelectTrigger className={fieldTrigger}>
                    <IconUser className="size-4 text-neutral-400" />
                    <SelectValue placeholder="Responsável" className="flex-1 text-left" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={ALL_VALUE}>Todos os responsáveis</SelectItem>
                    {assignees.map((user) => (
                      <SelectItem key={user.id} value={user.id}>
                        {user.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
          </div>
          <div className="flex flex-wrap gap-3">
            <ToggleGroup
              type="single"
              value={filters.view}
              onValueChange={(value) => value && setPartial({ view: value as TicketFiltersState["view"] })}
              className={segmentedRoot}
            >
              <ToggleGroupItem value="active" className={segmentedItem}>
                Em andamento
              </ToggleGroupItem>
              <ToggleGroupItem value="completed" className={segmentedItem}>
                Concluídos
              </ToggleGroupItem>
            </ToggleGroup>
            <ToggleGroup
              type="single"
              value={filters.sort}
              onValueChange={(value) => value && setPartial({ sort: value as TicketFiltersState["sort"] })}
              className={segmentedRoot}
            >
              <ToggleGroupItem value="recent" className={segmentedItem}>
                Mais recentes
              </ToggleGroupItem>
              <ToggleGroupItem value="oldest" className={segmentedItem}>
                Mais antigos
              </ToggleGroupItem>
            </ToggleGroup>
          </div>
        </div>
      </section>
      {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>
  )
}

function formatDateRangeChip(from: string | null, to: string | null) {
  const fromLabel = formatDateValue(from)
  const toLabel = formatDateValue(to)

  if (fromLabel && toLabel) {
    return `Período: ${fromLabel} até ${toLabel}`
  }
  if (fromLabel) {
    return `A partir de ${fromLabel}`
  }
  if (toLabel) {
    return `Até ${toLabel}`
  }
  return "Período personalizado"
}

function formatDateValue(value: string | null) {
  if (!value) return null
  const [year, month, day] = value.split("-").map((part) => Number(part))
  if (!year || !month || !day) {
    return value
  }
  try {
    return new Date(year, month - 1, day).toLocaleDateString("pt-BR")
  } catch {
    return value
  }
}
  const segmentedRoot =
    "flex h-10 min-w-[220px] flex-1 items-stretch rounded-full border border-slate-200 bg-slate-50/70 p-1 gap-1"
  const segmentedItem =
    "inline-flex h-full flex-1 items-center justify-center rounded-full first:rounded-full last:rounded-full px-4 text-sm font-semibold text-neutral-600 transition-colors hover:bg-slate-100 data-[state=on]:bg-neutral-900 data-[state=on]:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-300"
  const fieldWrap = "min-w-[220px] flex-1"
  const fieldTrigger =
    "h-10 w-full rounded-2xl border border-slate-300 bg-slate-50/80 px-3 text-left text-sm font-semibold text-neutral-700 focus:ring-neutral-300 flex items-center gap-2"
