import React, { useState } from 'react';
import { format } from 'date-fns';
import { Search, Calendar as CalendarIcon, Filter, X, Check, ChevronsUpDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Calendar } from '@/components/ui/calendar';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
import { cn } from '@/lib/utils';

export function OwnerUpdatesFilterBar({
  searchTerm, onSearchChange, timeframe, onTimeframeChange, dateRange, onDateRangeChange,
  selectedTags, onTagsChange, availableTags = [], onClearFilters, totalCount, filteredCount
}) {
  const [tagOpen, setTagOpen] = useState(false);
  const [calendarOpen, setCalendarOpen] = useState(false);

  const toggleTag = (tagName) => {
    const newTags = selectedTags.includes(tagName) ? selectedTags.filter(t => t !== tagName) : [...selectedTags, tagName];
    onTagsChange(newTags);
  };

  const handleTimeframeSelect = (val) => {
    onTimeframeChange(val);
    if (val === 'custom') setCalendarOpen(true);
  };

  const activeFilterCount = (timeframe !== 'all' ? 1 : 0) + selectedTags.length + (searchTerm ? 1 : 0);
  const isFiltered = activeFilterCount > 0;

  return (
    <div className="space-y-4 bg-background z-20 pb-2 relative">
      <div className="flex flex-col lg:flex-row gap-4 items-start lg:items-center justify-between">
        <div className="relative w-full lg:w-96">
          <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input placeholder="Search update content..." className="pl-9 h-9" value={searchTerm} onChange={(e) => onSearchChange(e.target.value)} />
        </div>

        <div className="flex flex-col sm:flex-row gap-2 w-full lg:w-auto">
          <div className="flex gap-2 w-full sm:w-auto">
            <Select value={timeframe} onValueChange={handleTimeframeSelect}>
              <SelectTrigger className="w-full sm:w-[160px] h-9 text-sm">
                <CalendarIcon className="mr-2 h-3.5 w-3.5 text-muted-foreground" />
                <SelectValue placeholder="Timeframe" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Time</SelectItem>
                <SelectItem value="today">Today</SelectItem>
                <SelectItem value="week">This Week</SelectItem>
                <SelectItem value="month">This Month</SelectItem>
                <SelectItem value="last30">Last 30 Days</SelectItem>
                <SelectItem value="custom">Custom Range</SelectItem>
              </SelectContent>
            </Select>

            {timeframe === 'custom' && (
              <Popover open={calendarOpen} onOpenChange={setCalendarOpen}>
                <PopoverTrigger asChild>
                  <Button variant="outline" className={cn("w-full sm:w-[240px] justify-start text-left font-normal border-dashed h-9 text-sm", !dateRange?.from && "text-muted-foreground")}>
                    <CalendarIcon className="mr-2 h-3.5 w-3.5" />
                    {dateRange?.from ? (dateRange.to ? <>{format(dateRange.from, "LLL dd, y")} - {format(dateRange.to, "LLL dd, y")}</> : format(dateRange.from, "LLL dd, y")) : <span>Pick a date</span>}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <Calendar initialFocus mode="range" defaultMonth={dateRange?.from} selected={dateRange} onSelect={onDateRangeChange} numberOfMonths={2} />
                </PopoverContent>
              </Popover>
            )}
          </div>

          <Popover open={tagOpen} onOpenChange={setTagOpen}>
            <PopoverTrigger asChild>
              <Button variant="outline" role="combobox" className="w-full sm:w-[200px] justify-between h-9 text-sm">
                <div className="flex items-center gap-2 truncate">
                  <Filter className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
                  {selectedTags.length > 0 ? <><Badge variant="secondary" className="rounded-sm px-1 font-normal text-xs">{selectedTags.length}</Badge><span>Selected</span></> : "Filter by Tags"}
                </div>
                <ChevronsUpDown className="ml-2 h-3.5 w-3.5 shrink-0 opacity-50" />
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-[200px] p-0">
              <Command><CommandInput placeholder="Search tags..." /><CommandList><CommandEmpty>No tags found.</CommandEmpty>
                <CommandGroup className="max-h-64 overflow-y-auto">
                  {availableTags.map(tag => (
                    <CommandItem key={tag.name} value={tag.name} onSelect={() => toggleTag(tag.name)}>
                      <div className={cn("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary", selectedTags.includes(tag.name) ? "bg-primary text-primary-foreground" : "opacity-50 [&_svg]:invisible")}><Check className="h-4 w-4" /></div>
                      <span className="flex-1 truncate">{tag.name}</span>
                    </CommandItem>
                  ))}
                </CommandGroup>
              </CommandList></Command>
            </PopoverContent>
          </Popover>

          {isFiltered && (
            <Button variant="ghost" onClick={onClearFilters} size="sm" className="px-3 text-destructive hover:text-destructive hover:bg-destructive/10 h-9 shrink-0">Clear</Button>
          )}
        </div>
      </div>

      {isFiltered && (
        <div className="flex flex-wrap items-center gap-2 animate-in fade-in slide-in-from-top-1 duration-200">
          <span className="text-xs text-muted-foreground font-medium mr-1">Active Filters:</span>
          {searchTerm && (
            <Badge variant="secondary" className="pl-2 pr-1 py-0.5 gap-1 text-xs">Text: "{searchTerm}" <X className="h-3 w-3 cursor-pointer hover:text-destructive" onClick={() => onSearchChange('')} /></Badge>
          )}
          {timeframe !== 'all' && (
            <Badge variant="secondary" className="pl-2 pr-1 py-0.5 gap-1 text-xs">Date: {timeframe === 'custom' && dateRange?.from ? 'Custom' : timeframe} <X className="h-3 w-3 cursor-pointer hover:text-destructive" onClick={() => { onTimeframeChange('all'); onDateRangeChange(undefined); }} /></Badge>
          )}
          {selectedTags.map(tag => (
            <Badge key={tag} variant="secondary" className="pl-2 pr-1 py-0.5 gap-1 text-xs">Tag: {tag} <X className="h-3 w-3 cursor-pointer hover:text-destructive" onClick={() => toggleTag(tag)} /></Badge>
          ))}
          <div className="ml-auto text-xs text-muted-foreground">Showing <span className="font-semibold text-foreground">{filteredCount}</span> records</div>
        </div>
      )}
    </div>
  );
}
