'use client';

import { useState } from 'react';
import { Person, Tag } from '@prisma/client';
import { FilterPanel, SearchFilters } from './FilterPanel';
import { Button } from '@/components/ui/button';
import { Search, ChevronLeft, ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';

interface CollapsibleSearchProps {
  people: Person[];
  tags: Tag[];
  filters: SearchFilters;
  onFiltersChange: (filters: SearchFilters) => void;
}

export function CollapsibleSearch({ people, tags, filters, onFiltersChange }: CollapsibleSearchProps) {
  const [isExpanded, setIsExpanded] = useState(true);

  const hasActiveFilters =
    filters.people.length > 0 ||
    filters.tags.length > 0 ||
    filters.dateFrom ||
    filters.dateTo;

  return (
    <div
      className={cn(
        'flex flex-col border-r bg-card transition-all duration-300 sticky top-0 self-start',
        isExpanded ? 'w-80' : 'w-16',
        'h-[calc(100vh-8rem)]'
      )}
    >
      {/* Collapse/Expand Button */}
      <div className="flex items-center justify-between border-b p-4 flex-shrink-0">
        {isExpanded ? (
          <>
            <div className="flex items-center gap-2">
              <Search className="h-4 w-4" />
              <span className="font-medium text-secondary">Search & Filter</span>
              {hasActiveFilters && (
                <span className="ml-2 rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground">
                  {[
                    filters.people.length,
                    filters.tags.length,
                    filters.dateFrom || filters.dateTo ? 1 : 0,
                  ].reduce((a, b) => a + b, 0)}
                </span>
              )}
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsExpanded(false)}
              className="h-8 w-8 p-0"
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
          </>
        ) : (
          <div className="flex items-center justify-center w-full">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsExpanded(true)}
              className="h-8 w-8 p-0 relative"
              title="Expand search"
            >
              <ChevronRight className="h-4 w-4" />
              {hasActiveFilters && (
                <span className="absolute -right-1 -top-1 h-3 w-3 rounded-full bg-primary border-2 border-card" />
              )}
            </Button>
          </div>
        )}
      </div>

      {/* Expanded Filter Panel */}
      {isExpanded && (
        <div className="flex-1 overflow-y-auto min-h-0">
          <FilterPanel
            people={people}
            tags={tags}
            filters={filters}
            onFiltersChange={onFiltersChange}
          />
        </div>
      )}
    </div>
  );
}

