"use client";

import { useMemo, useState } from "react";
import { Filter, RotateCcw, Search, SlidersHorizontal } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";

export type FilterOption = {
  value: string;
  label: string;
};

export type UsersFilterCategory = {
  id: string;
  label: string;
  value: string;
  defaultValue?: string;
  options: FilterOption[];
  onChange: (value: string) => void;
  searchable?: boolean;
};

interface UsersFilterPanelProps {
  categories: UsersFilterCategory[];
  activeCount: number;
  onClearAll: () => void;
}

export function UsersFilterPanel({
  categories,
  activeCount,
  onClearAll,
}: UsersFilterPanelProps) {
  const [open, setOpen] = useState(false);
  const [activeCategoryId, setActiveCategoryId] = useState(
    categories[0]?.id ?? "",
  );
  const [optionSearch, setOptionSearch] = useState("");

  const activeCategory =
    categories.find((c) => c.id === activeCategoryId) ?? categories[0];

  const filteredOptions = useMemo(() => {
    if (!activeCategory) return [];
    const q = optionSearch.trim().toLowerCase();
    if (!q || !activeCategory.searchable) return activeCategory.options;
    return activeCategory.options.filter((opt) =>
      opt.label.toLowerCase().includes(q),
    );
  }, [activeCategory, optionSearch]);

  const handleCategoryChange = (id: string) => {
    setActiveCategoryId(id);
    setOptionSearch("");
  };

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          size="sm"
          className={cn(
            "h-9 gap-1.5 px-3 text-sm font-medium",
            activeCount > 0 && "border-primary/40 bg-primary/5 text-primary",
          )}
        >
          <SlidersHorizontal className="h-4 w-4" />
          Filter & sort
          {activeCount > 0 && (
            <span className="inline-flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold text-primary-foreground">
              {activeCount}
            </span>
          )}
        </Button>
      </PopoverTrigger>
      <PopoverContent
        align="end"
        side="bottom"
        sideOffset={8}
        collisionPadding={16}
        className="w-[min(92vw,520px)] overflow-hidden p-0"
      >
        <div className="flex items-center gap-3 border-b border-border px-4 py-3">
          <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border bg-primary/5">
            <Filter className="h-3.5 w-3.5 text-primary" />
          </div>
          <div className="min-w-0 flex-1">
            <p className="text-sm font-semibold text-foreground">
              Filter & sort
            </p>
            <p className="text-xs text-muted-foreground">
              Refine the users view
            </p>
          </div>
          <Button
            variant="ghost"
            size="sm"
            className={cn(
              "h-8 shrink-0 gap-1.5 px-2.5 text-xs",
              activeCount > 0
                ? "text-primary hover:text-primary"
                : "text-muted-foreground",
            )}
            disabled={activeCount === 0}
            onClick={onClearAll}
          >
            <RotateCcw className="h-3.5 w-3.5" />
            Reset
          </Button>
        </div>

        <div className="flex min-h-[260px] max-h-[380px]">
          <aside className="w-[156px] shrink-0 overflow-y-auto border-r border-border bg-muted/20 p-1.5">
            <nav className="space-y-0.5">
              {categories.map((category) => {
                const isSelected = category.id === activeCategory?.id;
                const isFiltered =
                  category.value !== (category.defaultValue ?? "all");
                return (
                  <button
                    key={category.id}
                    type="button"
                    onClick={() => handleCategoryChange(category.id)}
                    className={cn(
                      "flex w-full items-center justify-between rounded-md px-2.5 py-1.5 text-left text-[13px] transition-colors",
                      isSelected
                        ? "bg-primary/10 font-medium text-primary"
                        : "text-muted-foreground hover:bg-muted/60 hover:text-foreground",
                    )}
                  >
                    <span className="truncate">{category.label}</span>
                    {isFiltered && (
                      <span className="ml-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-primary" />
                    )}
                  </button>
                );
              })}
            </nav>
          </aside>

          <div className="flex min-w-0 flex-1 flex-col">
            {activeCategory && (
              <>
                <div className="border-b border-border px-3 py-2.5">
                  <h3 className="text-[13px] font-semibold text-foreground">
                    {activeCategory.label}
                  </h3>
                  {activeCategory.searchable &&
                    activeCategory.options.length > 8 && (
                      <div className="relative mt-2">
                        <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
                        <Input
                          value={optionSearch}
                          onChange={(e) => setOptionSearch(e.target.value)}
                          placeholder={`Search ${activeCategory.label.toLowerCase()}…`}
                          className="h-8 max-w-full pl-8 text-sm"
                        />
                      </div>
                    )}
                </div>

                <div className="flex-1 overflow-y-auto p-1.5">
                  <div className="space-y-0.5">
                    {filteredOptions.map((option) => {
                      const checked = activeCategory.value === option.value;
                      return (
                        <label
                          key={option.value}
                          className={cn(
                            "relative flex w-full cursor-pointer items-center gap-2.5 rounded-md px-3 py-2 text-left text-[13px] transition-colors",
                            checked
                              ? "bg-primary/10 text-foreground"
                              : "text-foreground/90 hover:bg-muted/50",
                          )}
                        >
                          {checked && (
                            <span className="absolute inset-y-1.5 left-0 w-0.5 rounded-full bg-primary" />
                          )}
                          <Checkbox
                            checked={checked}
                            onCheckedChange={() =>
                              activeCategory.onChange(option.value)
                            }
                            className="h-3.5 w-3.5 rounded-[3px] border-border data-[state=checked]:border-primary data-[state=checked]:bg-primary"
                          />
                          <span className="truncate">{option.label}</span>
                        </label>
                      );
                    })}
                    {filteredOptions.length === 0 && (
                      <p className="px-3 py-6 text-center text-sm text-muted-foreground">
                        No options found
                      </p>
                    )}
                  </div>
                </div>
              </>
            )}
          </div>
        </div>

        <div className="flex items-center justify-between border-t border-border px-4 py-2">
          <span className="text-xs text-muted-foreground">
            {activeCount > 0
              ? `${activeCount} filter${activeCount === 1 ? "" : "s"} applied`
              : "No filters applied"}
          </span>
        </div>
      </PopoverContent>
    </Popover>
  );
}
