'use client';

import { useState } from 'react';
import { Person } from '@prisma/client';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Button } from '@/components/ui/button';
import { Search, X } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

interface PeopleFilterProps {
  people: Person[];
  selected: number[];
  mode: 'any' | 'all';
  onSelectionChange: (selected: number[]) => void;
  onModeChange: (mode: 'any' | 'all') => void;
}

export function PeopleFilter({ people, selected, mode, onSelectionChange, onModeChange }: PeopleFilterProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [open, setOpen] = useState(false);

  const filteredPeople = people.filter((person) => {
    const fullName = `${person.first_name} ${person.last_name}`.toLowerCase();
    return fullName.includes(searchQuery.toLowerCase());
  });

  const togglePerson = (personId: number) => {
    if (selected.includes(personId)) {
      onSelectionChange(selected.filter((id) => id !== personId));
    } else {
      onSelectionChange([...selected, personId]);
    }
  };

  const selectedPeople = people.filter((p) => selected.includes(p.id));

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <label className="text-sm font-medium text-secondary">People</label>
        {selected.length > 1 && (
          <Select value={mode} onValueChange={(value) => onModeChange(value as 'any' | 'all')}>
            <SelectTrigger className="h-7 w-20 text-xs">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="any">Any</SelectItem>
              <SelectItem value="all">All</SelectItem>
            </SelectContent>
          </Select>
        )}
      </div>
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            className="w-full justify-start text-left font-normal"
          >
            <Search className="mr-2 h-4 w-4" />
            {selected.length === 0 ? 'Select people...' : `${selected.length} selected`}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-[300px] p-0" align="start">
          <div className="p-2">
            <Input
              placeholder="Search people..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="mb-2"
            />
            <div className="max-h-[300px] overflow-y-auto">
              {filteredPeople.length === 0 ? (
                <p className="p-2 text-sm text-gray-500">No people found</p>
              ) : (
                <div className="space-y-1">
                  {filteredPeople.map((person) => {
                    const isSelected = selected.includes(person.id);
                    return (
                      <div
                        key={person.id}
                        className="flex items-center space-x-2 rounded-md p-2 hover:bg-gray-100 dark:hover:bg-gray-800 cursor-pointer"
                        onClick={() => togglePerson(person.id)}
                      >
                        <span onClick={(e) => e.stopPropagation()}>
                          <Checkbox
                            checked={isSelected}
                            onCheckedChange={() => togglePerson(person.id)}
                          />
                        </span>
                        <label className="flex-1 cursor-pointer text-sm">
                          {person.first_name} {person.last_name}
                        </label>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </PopoverContent>
      </Popover>
      {selectedPeople.length > 0 && (
        <div className="flex flex-wrap gap-2">
          {selectedPeople.map((person) => (
            <Badge
              key={person.id}
              variant="secondary"
              className="flex items-center gap-1"
            >
               {person.first_name} {person.last_name}
              <button
                onClick={() => togglePerson(person.id)}
                className="ml-1 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700"
              >
                <X className="h-3 w-3" />
              </button>
            </Badge>
          ))}
        </div>
      )}
    </div>
  );
}

