/**
 * Dashboard Filters Bar Component
 * Handles date range filtering and refresh functionality
 */

import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Label } from '@/components/ui/label';
import { Filter, Calendar as CalendarIcon, RefreshCw } from 'lucide-react';
import { format } from 'date-fns';
import { DateRange } from '@/services/dashboard.service';
import { CustomDatePicker } from '@/components/ui/date-picker';

interface DashboardFiltersBarProps {
  isAdmin: boolean;
  dateRange: DateRange;
  customStartDate?: Date;
  customEndDate?: Date;
  showCustomDatePicker: boolean;
  refreshing: boolean;
  onDateRangeChange: (value: string) => void;
  onCustomStartDateChange: (date: Date | undefined) => void;
  onCustomEndDateChange: (date: Date | undefined) => void;
  onShowCustomDatePickerChange: (show: boolean) => void;
  onApplyCustomDate: () => void;
  onResetCustomDates: () => void;
  onRefresh: () => void;
}

export function DashboardFiltersBar({
  isAdmin,
  dateRange,
  customStartDate,
  customEndDate,
  showCustomDatePicker,
  refreshing,
  onDateRangeChange,
  onCustomStartDateChange,
  onCustomEndDateChange,
  onShowCustomDatePickerChange,
  onApplyCustomDate,
  onResetCustomDates,
  onRefresh,
}: DashboardFiltersBarProps) {
  return (
    <Card className="shadow-md" data-testid="dashboard-filters-bar">
      <CardContent className="p-4">
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
          <div className="flex items-center gap-2">
            <Filter className="w-5 h-5 text-muted-foreground" />
            <h3 className="font-semibold text-gray-900">Filters</h3>
            {isAdmin && (
              <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200" data-testid="management-badge">
                Management View
              </Badge>
            )}
          </div>

          <div className="flex flex-wrap items-center gap-3 w-full sm:w-auto">
            {/* Date Range Filter */}
            {isAdmin ? (
              <div className="flex items-center gap-2">
                <CalendarIcon className="w-4 h-4 text-muted-foreground" />
                <Select value={dateRange} onValueChange={onDateRangeChange} data-testid="date-range-select">
                  <SelectTrigger className="w-[140px]">
                    <SelectValue placeholder="Select period" />
                  </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="last7days">Last 7 Days</SelectItem>
                    <SelectItem value="last30days">Last 30 Days</SelectItem>
                    <SelectItem value="custom">Custom Range</SelectItem>
                  </SelectContent>
                </Select>
                
                {/* Custom Date Range Picker */}
                {dateRange === 'custom' && (
                  <Popover open={showCustomDatePicker} onOpenChange={onShowCustomDatePickerChange}>
                    <PopoverTrigger asChild>
                      <Button variant="outline" size="sm" className="gap-2" data-testid="custom-date-trigger">
                        <CalendarIcon className="w-4 h-4" />
                        {customStartDate && customEndDate 
                          ? `${format(customStartDate, 'MMM d, yyyy')} - ${format(customEndDate, 'MMM d, yyyy')}`
                          : 'Select dates'}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto p-4" align="start" sideOffset={8} data-testid="custom-date-picker">
                      <div className="space-y-4">
                        <div className="space-y-3">
                          <div className="space-y-2">
                            <Label htmlFor="start-date" className="text-sm font-medium">Start Date</Label>
                            <CustomDatePicker
                              value={customStartDate || null}
                              onChange={(dateStr: string | null) => {
                                const date = dateStr ? new Date(dateStr) : undefined;
                                if (date) {
                                  onCustomStartDateChange(date);
                                  if (customEndDate && date > customEndDate) {
                                    onCustomEndDateChange(date);
                                  }
                                } else {
                                  onCustomStartDateChange(undefined);
                                }
                              }}
                              maxDate={new Date()}
                              placeholderText="dd/mm/yyyy"
                              className="w-full"
                              data-testid="start-date-input"
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="end-date" className="text-sm font-medium">End Date</Label>
                            <CustomDatePicker
                              value={customEndDate || null}
                              onChange={(dateStr: string | null) => {
                                const date = dateStr ? new Date(dateStr) : undefined;
                                if (date) {
                                  onCustomEndDateChange(date);
                                  if (customStartDate && date < customStartDate) {
                                    onCustomStartDateChange(date);
                                  }
                                } else {
                                  onCustomEndDateChange(undefined);
                                }
                              }}
                              minDate={customStartDate || undefined}
                              maxDate={new Date()}
                              placeholderText="dd/mm/yyyy"
                              className="w-full"
                              data-testid="end-date-input"
                            />
                          </div>
                        </div>
                        <div className="flex gap-2 pt-2 border-t">
                          <Button 
                            size="sm" 
                            onClick={onApplyCustomDate}
                            disabled={!customStartDate || !customEndDate}
                            className="flex-1 bg-re-green hover:bg-re-green/90"
                            data-testid="apply-custom-date"
                          >
                            Apply
                          </Button>
                          <Button 
                            size="sm" 
                            variant="outline"
                            onClick={onResetCustomDates}
                            data-testid="cancel-custom-date"
                          >
                            Cancel
                          </Button>
                        </div>
                      </div>
                    </PopoverContent>
                  </Popover>
                )}
              </div>
            ) : (
              <div className="flex items-center gap-2">
                <CalendarIcon className="w-4 h-4 text-muted-foreground" />
                <Select value={dateRange} onValueChange={(value) => onDateRangeChange(value)} data-testid="date-range-select-user">
                  <SelectTrigger className="w-[140px]">
                    <SelectValue placeholder="Select period" />
                  </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="last7days">Last 7 Days</SelectItem>
                    <SelectItem value="last30days">Last 30 Days</SelectItem>
                    <SelectItem value="custom">Custom Range</SelectItem>
                  </SelectContent>
                </Select>

                {/* Custom Date Range Picker for Normal Users */}
                {dateRange === 'custom' && (
                  <Popover open={showCustomDatePicker} onOpenChange={onShowCustomDatePickerChange}>
                    <PopoverTrigger asChild>
                      <Button variant="outline" size="sm" className="gap-2" data-testid="custom-date-trigger">
                        <CalendarIcon className="w-4 h-4" />
                        {customStartDate && customEndDate 
                          ? `${format(customStartDate, 'MMM d, yyyy')} - ${format(customEndDate, 'MMM d, yyyy')}`
                          : 'Select dates'}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto p-4" align="start" sideOffset={8} data-testid="custom-date-picker">
                      <div className="space-y-4">
                        <div className="space-y-3">
                          <div className="space-y-2">
                            <Label htmlFor="start-date-user" className="text-sm font-medium">Start Date</Label>
                            <CustomDatePicker
                              value={customStartDate || null}
                              onChange={(dateStr: string | null) => {
                                const date = dateStr ? new Date(dateStr) : undefined;
                                if (date) {
                                  onCustomStartDateChange(date);
                                  if (customEndDate && date > customEndDate) {
                                    onCustomEndDateChange(date);
                                  }
                                } else {
                                  onCustomStartDateChange(undefined);
                                }
                              }}
                              maxDate={new Date()}
                              placeholderText="dd/mm/yyyy"
                              className="w-full"
                              data-testid="start-date-input-user"
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="end-date-user" className="text-sm font-medium">End Date</Label>
                            <CustomDatePicker
                              value={customEndDate || null}
                              onChange={(dateStr: string | null) => {
                                const date = dateStr ? new Date(dateStr) : undefined;
                                if (date) {
                                  onCustomEndDateChange(date);
                                  if (customStartDate && date < customStartDate) {
                                    onCustomStartDateChange(date);
                                  }
                                } else {
                                  onCustomEndDateChange(undefined);
                                }
                              }}
                              minDate={customStartDate || undefined}
                              maxDate={new Date()}
                              placeholderText="dd/mm/yyyy"
                              className="w-full"
                              data-testid="end-date-input-user"
                            />
                          </div>
                        </div>
                        <div className="flex gap-2 pt-2 border-t">
                          <Button 
                            size="sm" 
                            onClick={onApplyCustomDate}
                            disabled={!customStartDate || !customEndDate}
                            className="flex-1 bg-re-green hover:bg-re-green/90"
                            data-testid="apply-custom-date-user"
                          >
                            Apply
                          </Button>
                          <Button 
                            size="sm" 
                            variant="outline"
                            onClick={onResetCustomDates}
                            data-testid="cancel-custom-date-user"
                          >
                            Cancel
                          </Button>
                        </div>
                      </div>
                    </PopoverContent>
                  </Popover>
                )}
              </div>
            )}

            <Separator orientation="vertical" className="h-6 hidden sm:block" />

            {/* Refresh Button */}
            <Button
              variant="outline"
              size="sm"
              onClick={onRefresh}
              disabled={refreshing}
              className="gap-2 min-w-[110px]"
              data-testid="refresh-button"
            >
              <RefreshCw className={`w-4 h-4 ${refreshing ? 'animate-spin' : ''}`} />
              <span className="inline-block w-[60px] text-center">
                {refreshing ? 'Refreshing...' : 'Refresh'}
              </span>
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
