"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Filter, X, ChevronDown } from "lucide-react";

interface FilterOption {
  id: string;
  label: string;
  count?: number;
}

interface MultiSelectFilterProps {
  title: string;
  options: FilterOption[];
  selectedValues: string[];
  onChange: (selectedValues: string[]) => void;
  placeholder?: string;
  icon?: React.ReactNode;
}

export function MultiSelectFilter({
  title,
  options,
  selectedValues,
  onChange,
  placeholder = "Sélectionner...",
  icon = <Filter className="h-4 w-4" />,
}: MultiSelectFilterProps) {
  const [isOpen, setIsOpen] = useState(false);

  const handleToggle = (value: string) => {
    const newSelected = selectedValues.includes(value)
      ? selectedValues.filter((v) => v !== value)
      : [...selectedValues, value];
    onChange(newSelected);
  };

  const handleSelectAll = () => {
    if (selectedValues.length === options.length) {
      onChange([]);
    } else {
      onChange(options.map((opt) => opt.id));
    }
  };

  const clearSelection = () => {
    onChange([]);
  };

  const getDisplayText = () => {
    if (selectedValues.length === 0) return placeholder;
    if (selectedValues.length === 1) {
      const option = options.find((opt) => opt.id === selectedValues[0]);
      return option?.label || selectedValues[0];
    }
    return `${selectedValues.length} sélectionné(s)`;
  };

  return (
    <div className="space-y-2">
      <Popover open={isOpen} onOpenChange={setIsOpen}>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            className="w-full justify-between h-auto min-h-10 p-3 bg-white/5 border-white/20 text-white hover:bg-white/10 hover:border-white/30"
          >
            <div className="flex items-center gap-2">
              {icon}
              <span className="font-medium text-sm text-slate-300">
                {title}:
              </span>
              <span className="text-sm text-slate-400">{getDisplayText()}</span>
            </div>
            <ChevronDown className="h-4 w-4 text-slate-400" />
          </Button>
        </PopoverTrigger>

        <PopoverContent
          className="w-80 p-0 bg-slate-800 border-white/20"
          align="start"
        >
          <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-xl">
            <div className="p-4 space-y-3">
              {/* Header avec actions */}
              <div className="flex items-center justify-between">
                <span className="font-medium text-sm text-white">{title}</span>
                <div className="flex gap-2">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={handleSelectAll}
                    className="text-xs h-7 text-slate-400 hover:text-white hover:bg-white/10"
                  >
                    {selectedValues.length === options.length
                      ? "Tout déselectionner"
                      : "Tout sélectionner"}
                  </Button>
                  {selectedValues.length > 0 && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={clearSelection}
                      className="text-xs h-7 text-slate-400 hover:text-white hover:bg-white/10"
                    >
                      <X className="h-3 w-3" />
                    </Button>
                  )}
                </div>
              </div>

              {/* Options */}
              <div className="space-y-2 max-h-60 overflow-y-auto">
                {options.map((option) => (
                  <div
                    key={option.id}
                    className="flex items-center space-x-2 p-2 rounded-lg hover:bg-white/10 cursor-pointer transition-colors"
                    onClick={() => handleToggle(option.id)}
                  >
                    <Checkbox
                      id={option.id}
                      checked={selectedValues.includes(option.id)}
                      onChange={() => {}} // Géré par le onClick du div parent
                    />
                    <label
                      htmlFor={option.id}
                      className="text-sm flex-1 cursor-pointer flex items-center justify-between text-white"
                    >
                      <span>{option.label}</span>
                      {option.count !== undefined && (
                        <div className="px-2 py-1 bg-blue-500/20 border border-blue-500/30 rounded">
                          <span className="text-xs text-blue-300 font-medium">
                            {option.count}
                          </span>
                        </div>
                      )}
                    </label>
                  </div>
                ))}
              </div>

              {/* Résumé de la sélection */}
              {selectedValues.length > 0 && (
                <div className="pt-3 border-t border-white/10">
                  <div className="flex flex-wrap gap-1">
                    {selectedValues.slice(0, 3).map((value) => {
                      const option = options.find((opt) => opt.id === value);
                      return (
                        <div
                          key={value}
                          className="px-2 py-1 bg-green-500/20 border border-green-500/30 rounded"
                        >
                          <span className="text-xs text-green-300 font-medium">
                            {option?.label || value}
                          </span>
                        </div>
                      );
                    })}
                    {selectedValues.length > 3 && (
                      <div className="px-2 py-1 bg-slate-500/20 border border-slate-500/30 rounded">
                        <span className="text-xs text-slate-300 font-medium">
                          +{selectedValues.length - 3}
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </PopoverContent>
      </Popover>
    </div>
  );
}
