import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { cn } from '@/lib/utils';
import { Filter, X } from 'lucide-react';
import { Filters, type FiltersProps } from './Filters';
import { Sort, type SortProps } from './Sort';

/**
 * FE-COMP-007: FilterBar component combining filters and sort in a collapsible bar
 */

export interface FilterBarProps {
  filters?: FiltersProps;
  sort?: SortProps;
  className?: string;
  collapsible?: boolean;
  defaultOpen?: boolean;
}

/**
 * FilterBar component that combines Filters and Sort components
 */
export function FilterBar({
  filters,
  sort,
  className,
  collapsible = true,
  defaultOpen = false,
}: FilterBarProps) {
  const [isOpen, setIsOpen] = useState(!collapsible || defaultOpen);

  const hasFilters = filters && filters.filters.length > 0;
  const hasSort = sort !== undefined;

  if (!hasFilters && !hasSort) {
    return null;
  }

  return (
    <Card className={cn('mb-4', className)}>
      <CardContent className="p-4">
        {collapsible && (
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <Filter className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm font-medium">Filtres et tri</span>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsOpen(!isOpen)}
              aria-expanded={isOpen}
            >
              {isOpen ? (
                <>
                  <X className="h-4 w-4 mr-2" />
                  Masquer
                </>
              ) : (
                <>
                  <Filter className="h-4 w-4 mr-2" />
                  Afficher
                </>
              )}
            </Button>
          </div>
        )}

        {(!collapsible || isOpen) && (
          <div className="space-y-4">
            {/* Filters */}
            {hasFilters && (
              <div>
                <Filters {...filters} />
              </div>
            )}

            {/* Sort */}
            {hasSort && (
              <div className="flex items-center justify-between border-t pt-4">
                <span className="text-sm font-medium">Trier par:</span>
                <Sort {...sort} />
              </div>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
