"use client";

import { useState } from "react";
import { Search, SlidersHorizontal, ChevronDown, ArrowUpDown, X } from "lucide-react";
import { cn } from "@/shared/lib/utils";
import { useT } from "@/shared/i18n/client";
import { Input } from "@/presentation/components/ui/input";
import { Button } from "@/presentation/components/ui/button";
import { Badge } from "@/presentation/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/presentation/components/ui/select";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/presentation/components/ui/collapsible";
import {
  ANTAI_COMPANY_STATUS_VALUES,
  ANTAI_VISIBILITY_VALUES,
  ANTAI_BINDING_VALUES,
  ANTAI_ARCHIVED_VALUES,
  ANTAI_UNBINDING_REASON_VALUES,
  ANTAI_EXCEPTION_TYPE_VALUES,
  ANTAI_EXCEPTION_STATUS_VALUES,
} from "@/shared/constants/antai";
import type { AntaiOption, AntaiVehicleOptions } from "@/domain/entities/antai-vehicle";

/** Backend query-param keys driven by this filter bar. */
const FILTER_KEYS = [
  "company_id",
  "company_status",
  "vehicle_status_id",
  "antai_visibility",
  "binding_status",
  "archived",
  "unbinding_reason",
  "exception_type",
  "exception_status",
] as const;

interface AntaiFiltersProps {
  options: AntaiVehicleOptions | null;
  filters: Record<string, string | number | undefined>;
  onFilter: (key: string, value: string | undefined) => void;
  search: string;
  onSearch: (value: string) => void;
  /** `${order_by}:${order}`, e.g. "last_antai_updated_date:DESC". */
  sortValue: string;
  onSort: (value: string) => void;
  onReset: () => void;
}

export function AntaiFilters({
  options,
  filters,
  onFilter,
  search,
  onSearch,
  sortValue,
  onSort,
  onReset,
}: AntaiFiltersProps) {
  const t = useT();
  const [open, setOpen] = useState(false);

  const activeCount = FILTER_KEYS.filter(
    (k) => filters[k] !== undefined && filters[k] !== ""
  ).length;
  const hasAny = activeCount > 0 || search.trim() !== "";

  const enumOpts = (values: readonly string[], labels: Record<string, string>): AntaiOption[] =>
    values.map((v) => ({ value: v, label: labels[v] ?? v }));

  const descriptors: { key: string; label: string; opts: AntaiOption[] }[] = [
    { key: "company_id", label: t.antai.filters.company, opts: options?.companies ?? [] },
    {
      key: "company_status",
      label: t.antai.filters.companyStatus,
      opts: enumOpts(ANTAI_COMPANY_STATUS_VALUES, t.antai.enums.companyStatus),
    },
    {
      key: "vehicle_status_id",
      label: t.antai.filters.vehicleStatus,
      opts: options?.vehicle_statuses ?? [],
    },
    {
      key: "antai_visibility",
      label: t.antai.filters.visibility,
      opts: enumOpts(ANTAI_VISIBILITY_VALUES, t.antai.enums.visibility),
    },
    {
      key: "binding_status",
      label: t.antai.filters.binding,
      opts: enumOpts(ANTAI_BINDING_VALUES, t.antai.enums.binding),
    },
    {
      key: "archived",
      label: t.antai.filters.archived,
      opts: enumOpts(ANTAI_ARCHIVED_VALUES, t.antai.enums.archived),
    },
    {
      key: "unbinding_reason",
      label: t.antai.filters.unbindingReason,
      opts: enumOpts(ANTAI_UNBINDING_REASON_VALUES, t.antai.enums.unbindingReason),
    },
    {
      key: "exception_type",
      label: t.antai.filters.exceptionType,
      opts: enumOpts(ANTAI_EXCEPTION_TYPE_VALUES, t.antai.enums.exceptionType),
    },
    {
      key: "exception_status",
      label: t.antai.filters.exceptionStatus,
      opts: enumOpts(ANTAI_EXCEPTION_STATUS_VALUES, t.antai.enums.exceptionStatus),
    },
  ];

  return (
    <Collapsible
      open={open}
      onOpenChange={setOpen}
      className="rounded-xl border border-border bg-card p-3 shadow-sm space-y-3"
    >
      <div className="flex flex-col sm:flex-row sm:items-center gap-2">
        <div className="relative flex-1 sm:max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input
            placeholder={t.antai.searchPlaceholder}
            value={search}
            onChange={(e) => onSearch(e.target.value)}
            className="pl-9 h-9"
          />
        </div>

        <CollapsibleTrigger asChild>
          <Button variant="outline" size="sm" className="h-9 gap-2">
            <SlidersHorizontal className="w-4 h-4" />
            {t.antai.filters.title}
            {activeCount > 0 && (
              <Badge className="h-5 px-1.5 bg-primary text-primary-foreground border-0 text-[10px]">
                {activeCount}
              </Badge>
            )}
            <ChevronDown
              className={cn("w-4 h-4 transition-transform", open && "rotate-180")}
            />
          </Button>
        </CollapsibleTrigger>

        <Select value={sortValue} onValueChange={onSort}>
          <SelectTrigger size="sm" className="h-9 w-44 gap-2 sm:ml-auto" aria-label={t.antai.sort.label}>
            <ArrowUpDown className="w-3.5 h-3.5 text-muted-foreground" />
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="last_antai_updated_date:DESC">{t.antai.sort.recentSync}</SelectItem>
            <SelectItem value="last_antai_updated_date:ASC">{t.antai.sort.oldestSync}</SelectItem>
            <SelectItem value="numberplate:ASC">{t.antai.sort.plateAsc}</SelectItem>
            <SelectItem value="numberplate:DESC">{t.antai.sort.plateDesc}</SelectItem>
            <SelectItem value="created_at:DESC">{t.antai.sort.newest}</SelectItem>
            <SelectItem value="created_at:ASC">{t.antai.sort.oldest}</SelectItem>
          </SelectContent>
        </Select>

        {hasAny && (
          <Button
            variant="ghost"
            size="sm"
            className="h-9 gap-1 text-muted-foreground"
            onClick={onReset}
          >
            <X className="w-3.5 h-3.5" />
            {t.antai.filters.reset}
          </Button>
        )}
      </div>

      <CollapsibleContent>
        <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-3 pt-1">
          {descriptors.map((d) => {
            const current = filters[d.key];
            return (
              <div key={d.key} className="flex flex-col gap-1">
                <span className="text-[11px] font-medium text-muted-foreground">{d.label}</span>
                <Select
                  value={current !== undefined && current !== "" ? String(current) : "all"}
                  onValueChange={(v) => onFilter(d.key, v === "all" ? undefined : v)}
                >
                  <SelectTrigger className="h-8 text-xs">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">{t.common.all}</SelectItem>
                    {d.opts.map((o) => (
                      <SelectItem key={String(o.value)} value={String(o.value)}>
                        {o.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            );
          })}
        </div>
      </CollapsibleContent>
    </Collapsible>
  );
}
