import { useState, useRef, useEffect } from 'react';
import { Check, Columns, RotateCcw } from 'lucide-react';
import { cn } from '@/lib/utils';

export interface ColumnConfig {
  key: string;
  label: string;
  visible: boolean;
  locked?: boolean; // Colonnes qui ne peuvent pas être masquées
}

interface ColumnSelectorProps {
  columns: ColumnConfig[];
  onChange: (columns: ColumnConfig[]) => void;
  className?: string;
}

export function ColumnSelector({ columns, onChange, className }: ColumnSelectorProps) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Fermer le dropdown si clic en dehors
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const toggleColumn = (key: string) => {
    const updated = columns.map(col =>
      col.key === key && !col.locked ? { ...col, visible: !col.visible } : col
    );
    onChange(updated);
  };

  const resetColumns = () => {
    const updated = columns.map(col => ({ ...col, visible: true }));
    onChange(updated);
  };

  const visibleCount = columns.filter(c => c.visible).length;
  const totalCount = columns.length;

  return (
    <div className={cn("relative", className)} ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className={cn(
          "inline-flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-xl border transition-all",
          isOpen
            ? "bg-gray-100 dark:bg-gray-800 border-gray-300 dark:border-gray-600"
            : "bg-white dark:bg-gray-900 border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800"
        )}
      >
        <Columns className="w-4 h-4 text-gray-500" />
        <span className="hidden sm:inline text-gray-700 dark:text-gray-300">Colonnes</span>
        <span className="text-xs bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 px-1.5 py-0.5 rounded-md">
          {visibleCount}/{totalCount}
        </span>
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-64 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-xl shadow-lg z-50 overflow-hidden">
          {/* Header */}
          <div className="flex items-center justify-between px-4 py-3 border-b border-gray-100 dark:border-gray-800">
            <span className="text-sm font-medium text-gray-900 dark:text-white">
              Afficher les colonnes
            </span>
            <button
              onClick={resetColumns}
              className="text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 flex items-center gap-1 transition-colors"
            >
              <RotateCcw className="w-3 h-3" />
              Réinitialiser
            </button>
          </div>

          {/* Liste des colonnes */}
          <div className="max-h-64 overflow-y-auto py-2">
            {columns.map((column) => (
              <button
                key={column.key}
                onClick={() => toggleColumn(column.key)}
                disabled={column.locked}
                className={cn(
                  "w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors",
                  column.locked
                    ? "opacity-50 cursor-not-allowed"
                    : "hover:bg-gray-50 dark:hover:bg-gray-800 cursor-pointer"
                )}
              >
                <div
                  className={cn(
                    "w-5 h-5 rounded-md border-2 flex items-center justify-center transition-all",
                    column.visible
                      ? "bg-[#338660] border-[#338660]"
                      : "border-gray-300 dark:border-gray-600"
                  )}
                >
                  {column.visible && <Check className="w-3 h-3 text-white" />}
                </div>
                <span
                  className={cn(
                    "text-sm",
                    column.visible
                      ? "text-gray-900 dark:text-white"
                      : "text-gray-500 dark:text-gray-400"
                  )}
                >
                  {column.label}
                </span>
                {column.locked && (
                  <span className="ml-auto text-xs text-gray-400">Requis</span>
                )}
              </button>
            ))}
          </div>

          {/* Footer */}
          <div className="px-4 py-3 border-t border-gray-100 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50">
            <p className="text-xs text-gray-500">
              {visibleCount} colonne{visibleCount > 1 ? 's' : ''} visible{visibleCount > 1 ? 's' : ''}
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

export default ColumnSelector;