/**
 * Standard User All Requests Filters Component
 * 
 * Full filters for regular users (non-dealers).
 * Includes: Search, Status, Priority, Template Type, Department, SLA Compliance,
 * Initiator, Approver, and Date Range filters.
 */

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

interface StandardUserAllRequestsFiltersProps {
  // Dealer-only (optional for standard users – ignored)
  requestTypeFilter?: string;
  onRequestTypeChange?: (value: string) => void;
  /** When true, show Form 16 in template dropdown and FY/Quarter filters (for RE users with Form 16 access) */
  showForm16Filter?: boolean;
  form16FinancialYear?: string;
  form16Quarter?: string;
  onForm16FinancialYearChange?: (value: string) => void;
  onForm16QuarterChange?: (value: string) => void;
  // Filters
  searchTerm: string;
  statusFilter: string;
  priorityFilter: string;
  templateTypeFilter: string;
  departmentFilter: string;
  slaComplianceFilter: string;
  initiatorFilter: string;
  approverFilter: string;
  approverFilterType: 'current' | 'any';
  dateRange: DateRange;
  customStartDate?: Date;
  customEndDate?: Date;
  showCustomDatePicker: boolean;

  // Departments
  departments: string[];
  loadingDepartments: boolean;

  // State for user search
  initiatorSearch: {
    selectedUser: { userId: string; email: string; displayName?: string } | null;
    searchQuery: string;
    searchResults: Array<{ userId: string; email: string; displayName?: string }>;
    showResults: boolean;
    handleSearch: (query: string) => void;
    handleSelect: (user: { userId: string; email: string; displayName?: string }) => void;
    handleClear: () => void;
    setShowResults: (show: boolean) => void;
  };

  approverSearch: {
    selectedUser: { userId: string; email: string; displayName?: string } | null;
    searchQuery: string;
    searchResults: Array<{ userId: string; email: string; displayName?: string }>;
    showResults: boolean;
    handleSearch: (query: string) => void;
    handleSelect: (user: { userId: string; email: string; displayName?: string }) => void;
    handleClear: () => void;
    setShowResults: (show: boolean) => void;
  };

  // Actions
  onSearchChange: (value: string) => void;
  onStatusChange: (value: string) => void;
  onPriorityChange: (value: string) => void;
  onTemplateTypeChange: (value: string) => void;
  onDepartmentChange: (value: string) => void;
  onSlaComplianceChange: (value: string) => void;
  onInitiatorChange?: (value: string) => void;
  onApproverChange?: (value: string) => void;
  onApproverTypeChange?: (value: 'current' | 'any') => void;
  onDateRangeChange: (value: DateRange) => void;
  onCustomStartDateChange?: (date: Date | undefined) => void;
  onCustomEndDateChange?: (date: Date | undefined) => void;
  onShowCustomDatePickerChange?: (show: boolean) => void;
  onApplyCustomDate?: () => void;
  onClearFilters: () => void;

  // Computed
  hasActiveFilters: boolean;
}

export function StandardUserAllRequestsFilters({
  searchTerm,
  statusFilter,
  priorityFilter,
  templateTypeFilter,
  departmentFilter,
  slaComplianceFilter,
  initiatorFilter: _initiatorFilter,
  approverFilter,
  approverFilterType,
  dateRange,
  customStartDate,
  customEndDate,
  showCustomDatePicker,
  departments,
  loadingDepartments,
  initiatorSearch,
  approverSearch,
  showForm16Filter = false,
  form16FinancialYear = 'all',
  form16Quarter = 'all',
  onForm16FinancialYearChange,
  onForm16QuarterChange,
  onSearchChange,
  onStatusChange,
  onPriorityChange,
  onTemplateTypeChange,
  onDepartmentChange,
  onSlaComplianceChange,
  onInitiatorChange: _onInitiatorChange,
  onApproverChange: _onApproverChange,
  onApproverTypeChange,
  onDateRangeChange,
  onCustomStartDateChange,
  onCustomEndDateChange,
  onShowCustomDatePickerChange,
  onApplyCustomDate,
  onClearFilters,
  hasActiveFilters,
}: StandardUserAllRequestsFiltersProps) {
  return (
    <Card className="border-gray-200 shadow-md" data-testid="user-all-requests-filters">
      <CardContent className="p-4 sm:p-6">
        <div className="flex flex-col gap-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Filter className="w-5 h-5 text-muted-foreground" />
              <h3 className="font-semibold text-gray-900">Advanced Filters</h3>
              {hasActiveFilters && (
                <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">
                  Active
                </Badge>
              )}
            </div>
            {hasActiveFilters && (
              <Button variant="ghost" size="sm" onClick={onClearFilters} className="gap-2">
                <RefreshCw className="w-4 h-4" />
                Clear All
              </Button>
            )}
          </div>

          <Separator />

          {/* Primary Filters */}
          <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4">
            <div className="relative md:col-span-3 lg:col-span-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <Input
                placeholder="Search requests..."
                value={searchTerm}
                onChange={(e) => onSearchChange(e.target.value)}
                className="pl-10 h-10"
                data-testid="search-input"
              />
            </div>

            <Select value={statusFilter} onValueChange={onStatusChange}>
              <SelectTrigger className="h-10" data-testid="status-filter">
                <SelectValue placeholder="All Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Status</SelectItem>
                <SelectItem value="pending">Pending</SelectItem>
                <SelectItem value="paused">Paused</SelectItem>
                <SelectItem value="approved">Approved</SelectItem>
                <SelectItem value="rejected">Rejected</SelectItem>
                <SelectItem value="closed">Closed</SelectItem>
              </SelectContent>
            </Select>

            <Select value={priorityFilter} onValueChange={onPriorityChange}>
              <SelectTrigger className="h-10" data-testid="priority-filter">
                <SelectValue placeholder="All Priority" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Priority</SelectItem>
                <SelectItem value="express">Express</SelectItem>
                <SelectItem value="standard">Standard</SelectItem>
              </SelectContent>
            </Select>

            <Select value={templateTypeFilter} onValueChange={onTemplateTypeChange}>
              <SelectTrigger className="h-10" data-testid="template-type-filter">
                <SelectValue placeholder="All Templates" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Templates</SelectItem>
                <SelectItem value="CUSTOM">Custom</SelectItem>
                <SelectItem value="DEALER CLAIM">Dealer Claim</SelectItem>
                {showForm16Filter && <SelectItem value="FORM_16">Form 16</SelectItem>}
              </SelectContent>
            </Select>

            {showForm16Filter && templateTypeFilter === 'FORM_16' && (
              <>
                <Select value={form16FinancialYear} onValueChange={onForm16FinancialYearChange ?? (() => {})}>
                  <SelectTrigger className="h-10" data-testid="form16-financial-year-filter">
                    <SelectValue placeholder="Financial Year" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Years</SelectItem>
                    <SelectItem value="2024-25">2024-25</SelectItem>
                    <SelectItem value="2023-24">2023-24</SelectItem>
                    <SelectItem value="2022-23">2022-23</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={form16Quarter} onValueChange={onForm16QuarterChange ?? (() => {})}>
                  <SelectTrigger className="h-10" data-testid="form16-quarter-filter">
                    <SelectValue placeholder="Quarter" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Quarters</SelectItem>
                    <SelectItem value="Q1">Q1</SelectItem>
                    <SelectItem value="Q2">Q2</SelectItem>
                    <SelectItem value="Q3">Q3</SelectItem>
                    <SelectItem value="Q4">Q4</SelectItem>
                  </SelectContent>
                </Select>
              </>
            )}

            <Select
              value={departmentFilter}
              onValueChange={onDepartmentChange}
              disabled={loadingDepartments || departments.length === 0}
            >
              <SelectTrigger className="h-10" data-testid="department-filter">
                <SelectValue placeholder={loadingDepartments ? "Loading..." : "All Departments"} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Departments</SelectItem>
                {departments.map((dept) => (
                  <SelectItem key={dept} value={dept}>{dept}</SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select value={slaComplianceFilter} onValueChange={onSlaComplianceChange}>
              <SelectTrigger className="h-10" data-testid="sla-compliance-filter">
                <SelectValue placeholder="All SLA Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All SLA Status</SelectItem>
                <SelectItem value="compliant">Compliant</SelectItem>
                <SelectItem value="on-track">On Track</SelectItem>
                <SelectItem value="approaching">Approaching</SelectItem>
                <SelectItem value="critical">Critical</SelectItem>
                <SelectItem value="breached">Breached</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* User Filters - Initiator and Approver */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4">
            {/* Initiator Filter */}
            <div className="flex flex-col">
              <Label className="text-sm font-medium text-gray-700 mb-2">Initiator</Label>
              <div className="relative">
                {initiatorSearch.selectedUser ? (
                  <div className="flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md">
                    <span className="flex-1 text-sm text-gray-900 truncate">
                      {initiatorSearch.selectedUser.displayName || initiatorSearch.selectedUser.email}
                    </span>
                    <Button variant="ghost" size="sm" className="h-6 w-6 p-0" onClick={initiatorSearch.handleClear}>
                      <X className="h-3 w-3" />
                    </Button>
                  </div>
                ) : (
                  <>
                    <Input
                      placeholder="Search initiator..."
                      value={initiatorSearch.searchQuery}
                      onChange={(e) => initiatorSearch.handleSearch(e.target.value)}
                      onFocus={() => {
                        if (initiatorSearch.searchResults.length > 0) {
                          initiatorSearch.setShowResults(true);
                        }
                      }}
                      onBlur={() => setTimeout(() => initiatorSearch.setShowResults(false), 200)}
                      className="h-10"
                      data-testid="initiator-search-input"
                    />
                    {initiatorSearch.showResults && initiatorSearch.searchResults.length > 0 && (
                      <div className="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto">
                        {initiatorSearch.searchResults.map((user) => (
                          <button
                            key={user.userId}
                            type="button"
                            onClick={() => initiatorSearch.handleSelect(user)}
                            className="w-full px-4 py-2 text-left hover:bg-gray-50"
                          >
                            <div className="flex flex-col">
                              <span className="text-sm font-medium text-gray-900">
                                {user.displayName || user.email}
                              </span>
                              {user.displayName && (
                                <span className="text-xs text-gray-500">{user.email}</span>
                              )}
                            </div>
                          </button>
                        ))}
                      </div>
                    )}
                  </>
                )}
              </div>
            </div>

            {/* Approver Filter */}
            <div className="flex flex-col">
              <div className="flex items-center justify-between mb-2">
                <Label className="text-sm font-medium text-gray-700">Approver</Label>
                {approverFilter !== 'all' && onApproverTypeChange && (
                  <Select
                    value={approverFilterType}
                    onValueChange={(value: 'current' | 'any') => onApproverTypeChange(value)}
                  >
                    <SelectTrigger className="h-7 w-32 text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="current">Current Only</SelectItem>
                      <SelectItem value="any">Any Approver</SelectItem>
                    </SelectContent>
                  </Select>
                )}
              </div>
              <div className="relative">
                {approverSearch.selectedUser ? (
                  <div className="flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md">
                    <span className="flex-1 text-sm text-gray-900 truncate">
                      {approverSearch.selectedUser.displayName || approverSearch.selectedUser.email}
                    </span>
                    <Button variant="ghost" size="sm" className="h-6 w-6 p-0" onClick={approverSearch.handleClear}>
                      <X className="h-3 w-3" />
                    </Button>
                  </div>
                ) : (
                  <>
                    <Input
                      placeholder="Search approver..."
                      value={approverSearch.searchQuery}
                      onChange={(e) => approverSearch.handleSearch(e.target.value)}
                      onFocus={() => {
                        if (approverSearch.searchResults.length > 0) {
                          approverSearch.setShowResults(true);
                        }
                      }}
                      onBlur={() => setTimeout(() => approverSearch.setShowResults(false), 200)}
                      className="h-10"
                      data-testid="approver-search-input"
                    />
                    {approverSearch.showResults && approverSearch.searchResults.length > 0 && (
                      <div className="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto">
                        {approverSearch.searchResults.map((user) => (
                          <button
                            key={user.userId}
                            type="button"
                            onClick={() => approverSearch.handleSelect(user)}
                            className="w-full px-4 py-2 text-left hover:bg-gray-50"
                          >
                            <div className="flex flex-col">
                              <span className="text-sm font-medium text-gray-900">
                                {user.displayName || user.email}
                              </span>
                              {user.displayName && (
                                <span className="text-xs text-gray-500">{user.email}</span>
                              )}
                            </div>
                          </button>
                        ))}
                      </div>
                    )}
                  </>
                )}
              </div>
            </div>
          </div>

          {/* Date Range Filter */}
          <div className="flex items-center gap-3 flex-wrap">
            <CalendarIcon className="w-4 h-4 text-muted-foreground" />
            <Select value={dateRange} onValueChange={(value) => onDateRangeChange(value as DateRange)}>
              <SelectTrigger className="w-[160px] h-10">
                <SelectValue placeholder="Date Range" />
              </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>

            {dateRange === 'custom' && (
              <Popover open={showCustomDatePicker} onOpenChange={onShowCustomDatePickerChange}>
                <PopoverTrigger asChild>
                  <Button variant="outline" size="sm" className="gap-2">
                    <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">
                  <div className="space-y-4">
                    <div className="space-y-3">
                      <div className="space-y-2">
                        <Label htmlFor="start-date">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"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="end-date">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"
                        />
                      </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"
                      >
                        Apply Range
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => {
                          onShowCustomDatePickerChange?.(false);
                          onCustomStartDateChange?.(undefined);
                          onCustomEndDateChange?.(undefined);
                          onDateRangeChange('month');
                        }}
                      >
                        Cancel
                      </Button>
                    </div>
                  </div>
                </PopoverContent>
              </Popover>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

