"use client"

import { IconFilter, IconRefresh } from "@tabler/icons-react"
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 { DatePicker } from "@/components/ui/date-picker"

export type PortalTicketFiltersState = {
  queue: string | null
  company: string | null
  categoryId: string | null
  assigneeId: string | null
  status: "active" | "resolved"
  sort: "recent" | "oldest"
  dateFrom: string | null
  dateTo: string | null
}

export const defaultPortalTicketFilters: PortalTicketFiltersState = {
  queue: null,
  company: null,
  categoryId: null,
  assigneeId: null,
  status: "active",
  sort: "recent",
  dateFrom: null,
  dateTo: null,
}

const ALL_VALUE = "ALL"

type Option = { id: string; name: string }

type PortalTicketFiltersProps = {
  filters: PortalTicketFiltersState
  onFiltersChange: (partial: Partial<PortalTicketFiltersState>) => void
  onReset: () => void
  queues: string[]
  companies: string[]
  categories: Option[]
  assignees: Option[]
  /**
   * Quando verdadeiro, oculta filtros avançados que não devem aparecer para
   * usuários finais no app desktop (fila, empresa e responsável).
   * Mantemos categoria, status, ordenação e período.
   */
  hideAdvancedFilters?: boolean
}

export function PortalTicketFilters({
  filters,
  onFiltersChange,
  onReset,
  queues,
  companies,
  categories,
  assignees,
  hideAdvancedFilters = false,
}: PortalTicketFiltersProps) {
  const handleChange = (partial: Partial<PortalTicketFiltersState>) => {
    onFiltersChange(partial)
  }

  const hasAnyFilterApplied =
    Boolean(filters.queue) ||
    Boolean(filters.company) ||
    Boolean(filters.categoryId) ||
    Boolean(filters.assigneeId) ||
    Boolean(filters.dateFrom) ||
    Boolean(filters.dateTo) ||
    filters.status !== "active" ||
    filters.sort !== "recent"

  if (hideAdvancedFilters) {
    return (
      <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-stretch">
          <div className="flex flex-1 flex-wrap gap-3">
            <Select
              value={filters.categoryId ?? ALL_VALUE}
              onValueChange={(value) => handleChange({ categoryId: value === ALL_VALUE ? null : value })}
            >
              <SelectTrigger className="min-w-[200px] flex-1 rounded-xl border-slate-300 bg-slate-50/80 focus:ring-neutral-300">
                <SelectValue placeholder="Categoria" />
              </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>
            <Select
              value={filters.status}
              onValueChange={(value) => handleChange({ status: value as PortalTicketFiltersState["status"] })}
            >
              <SelectTrigger className="min-w-[160px] flex-1 rounded-xl border-slate-300 bg-slate-50/80 focus:ring-neutral-300 lg:flex-none">
                <SelectValue placeholder="Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="active">Em andamento</SelectItem>
                <SelectItem value="resolved">Concluídos</SelectItem>
              </SelectContent>
            </Select>
            <Select
              value={filters.sort}
              onValueChange={(value) => handleChange({ sort: value as PortalTicketFiltersState["sort"] })}
            >
              <SelectTrigger className="min-w-[180px] flex-1 rounded-xl border-slate-300 bg-slate-50/80 focus:ring-neutral-300 lg:flex-none">
                <SelectValue placeholder="Ordenação" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="recent">Mais recentes</SelectItem>
                <SelectItem value="oldest">Mais antigos</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="w-full rounded-2xl border border-slate-200 bg-slate-50/70 p-4 shadow-inner lg:max-w-md">
            <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Período</p>
            <div className="mt-3 grid gap-3 sm:grid-cols-2">
              <div className="space-y-1">
                <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">A partir de</p>
                <DatePicker
                  value={filters.dateFrom}
                  onChange={(value) => handleChange({ dateFrom: value })}
                  placeholder="Selecionar data"
                  className="rounded-xl border-slate-300 bg-white"
                />
              </div>
              <div className="space-y-1">
                <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Até</p>
                <DatePicker
                  value={filters.dateTo}
                  onChange={(value) => handleChange({ dateTo: value })}
                  placeholder="Selecionar data"
                  className="rounded-xl border-slate-300 bg-white"
                />
              </div>
            </div>
          </div>
        </div>
        {hasAnyFilterApplied && (
          <div className="mt-3 flex flex-wrap gap-2">
            <Button
              variant="ghost"
              size="sm"
              className="gap-2 rounded-full px-4 py-2 text-sm font-medium text-neutral-700"
              onClick={onReset}
            >
              <IconRefresh className="size-4" /> Resetar
            </Button>
          </div>
        )}
      </div>
    )
  }

  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {!hideAdvancedFilters && (
          <Select
            value={filters.queue ?? ALL_VALUE}
            onValueChange={(value) => handleChange({ queue: value === ALL_VALUE ? null : value })}
          >
            <SelectTrigger className="w-full">
              <SelectValue placeholder="Todas as filas" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={ALL_VALUE}>Todas as filas</SelectItem>
              {queues.map((queue) => (
                <SelectItem key={queue} value={queue}>
                  {queue}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
        {!hideAdvancedFilters && (
          <Select
            value={filters.company ?? ALL_VALUE}
            onValueChange={(value) => handleChange({ company: value === ALL_VALUE ? null : value })}
          >
            <SelectTrigger className="w-full">
              <SelectValue placeholder="Todas as empresas" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={ALL_VALUE}>Todas as empresas</SelectItem>
              {companies.map((company) => (
                <SelectItem key={company} value={company}>
                  {company}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
        <Select
          value={filters.categoryId ?? ALL_VALUE}
          onValueChange={(value) => handleChange({ categoryId: value === ALL_VALUE ? null : value })}
        >
          <SelectTrigger className="w-full">
            <SelectValue placeholder="Todas as categorias" />
          </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>
        {!hideAdvancedFilters && (
          <Select
            value={filters.assigneeId ?? ALL_VALUE}
            onValueChange={(value) => handleChange({ assigneeId: value === ALL_VALUE ? null : value })}
          >
            <SelectTrigger className="w-full">
              <SelectValue placeholder="Todos os responsáveis" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={ALL_VALUE}>Todos os responsáveis</SelectItem>
              {assignees.map((assignee) => (
                <SelectItem key={assignee.id} value={assignee.id}>
                  {assignee.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
        <Select value={filters.status} onValueChange={(value) => handleChange({ status: value as PortalTicketFiltersState["status"] })}>
          <SelectTrigger className="w-full">
            <SelectValue placeholder="Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="active">Em andamento</SelectItem>
            <SelectItem value="resolved">Concluídos</SelectItem>
          </SelectContent>
        </Select>
        <Select value={filters.sort} onValueChange={(value) => handleChange({ sort: value as PortalTicketFiltersState["sort"] })}>
          <SelectTrigger className="w-full">
            <SelectValue placeholder="Ordenação" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="recent">Mais recentes</SelectItem>
            <SelectItem value="oldest">Mais antigos</SelectItem>
          </SelectContent>
        </Select>
      </div>
      <div className="mt-4 flex flex-wrap items-center gap-2">
        <Popover>
          <PopoverTrigger asChild>
            <Button
              variant="outline"
              size="sm"
              className="gap-2 rounded-full border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-neutral-800"
            >
              <IconFilter className="size-4" /> Período
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-[280px] space-y-3" align="start">
            <div className="space-y-1">
              <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">A partir de</p>
              <Input
                type="date"
                value={filters.dateFrom ?? ""}
                onChange={(event) => handleChange({ dateFrom: event.target.value || null })}
              />
            </div>
            <div className="space-y-1">
              <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Até</p>
              <Input
                type="date"
                value={filters.dateTo ?? ""}
                onChange={(event) => handleChange({ dateTo: event.target.value || null })}
              />
            </div>
          </PopoverContent>
        </Popover>
        {hasAnyFilterApplied && (
          <Button
            variant="ghost"
            size="sm"
            className="gap-2 rounded-full px-4 py-2 text-sm font-medium text-neutral-700"
            onClick={onReset}
          >
            <IconRefresh className="size-4" /> Resetar
          </Button>
        )}
      </div>
    </div>
  )
}
