import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Slider } from '@/components/ui/slider';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { MultiSelectCombobox } from '@/components/ui/multi-select-combobox';
import { RideCreditFilters as FilterTypes } from '@/types/ride-credits';
import { UserRideCredit } from '@/types/database';
import { X, ChevronDown, MapPin, Building2, Factory, Calendar, Star, MessageSquare, Image } from 'lucide-react';
import { useEffect, useMemo } from 'react';
import { Checkbox } from '@/components/ui/checkbox';

interface RideCreditFiltersProps {
  filters: FilterTypes;
  onFilterChange: (key: keyof FilterTypes, value: any) => void;
  onClearFilters: () => void;
  credits: UserRideCredit[];
  activeFilterCount: number;
  resultCount: number;
  totalCount: number;
  compact?: boolean;
}

export function RideCreditFilters({
  filters,
  onFilterChange,
  onClearFilters,
  credits,
  activeFilterCount,
  resultCount,
  totalCount,
  compact = false,
}: RideCreditFiltersProps) {
  const spacingClass = compact ? 'space-y-3' : 'space-y-4';
  const sectionSpacing = compact ? 'space-y-2' : 'space-y-3';
  const paddingClass = compact ? 'p-4' : 'pt-6';
  // Extract unique values from credits for filter options
  const filterOptions = useMemo(() => {
    const countries = new Set<string>();
    const states = new Set<string>();
    const cities = new Set<string>();
    const parks = new Map<string, string>();
    const manufacturers = new Map<string, string>();
    const coasterTypes = new Set<string>();
    const seatingTypes = new Set<string>();
    const intensityLevels = new Set<string>();
    const trackMaterials = new Set<string>();
    
    credits.forEach(credit => {
      const location = credit.rides?.parks?.locations;
      if (location?.country) countries.add(location.country);
      if (location?.state_province) states.add(location.state_province);
      if (location?.city) cities.add(location.city);
      
      if (credit.rides?.parks?.id && credit.rides?.parks?.name) {
        parks.set(credit.rides.parks.id, credit.rides.parks.name);
      }
      
      if (credit.rides?.manufacturer?.id && credit.rides?.manufacturer?.name) {
        manufacturers.set(credit.rides.manufacturer.id, credit.rides.manufacturer.name);
      }

      if (credit.rides?.coaster_type) {
        coasterTypes.add(credit.rides.coaster_type);
      }

      if (credit.rides?.seating_type) {
        seatingTypes.add(credit.rides.seating_type);
      }

      if (credit.rides?.intensity_level) {
        intensityLevels.add(credit.rides.intensity_level);
      }

      if (credit.rides?.track_material) {
        trackMaterials.add(credit.rides.track_material);
      }
    });

    return {
      countries: Array.from(countries).sort(),
      states: Array.from(states).sort(),
      cities: Array.from(cities).sort(),
      parks: Array.from(parks.entries()).map(([id, name]) => ({ id, name })).sort((a, b) => a.name.localeCompare(b.name)),
      manufacturers: Array.from(manufacturers.entries()).map(([id, name]) => ({ id, name })).sort((a, b) => a.name.localeCompare(b.name)),
      coasterTypes: Array.from(coasterTypes).sort(),
      seatingTypes: Array.from(seatingTypes).sort(),
      intensityLevels: Array.from(intensityLevels).sort(),
      trackMaterials: Array.from(trackMaterials).sort(),
    };
  }, [credits]);

  const searchOptions = useMemo(() => {
    const rides = new Map<string, { name: string, park: string }>();
    const parks = new Map<string, string>();
    const manufacturers = new Map<string, string>();
    
    credits.forEach(credit => {
      // Rides with their park context
      if (credit.rides?.id && credit.rides?.name) {
        rides.set(credit.rides.id, {
          name: credit.rides.name,
          park: credit.rides.parks?.name || 'Unknown Park'
        });
      }
      
      // Parks
      if (credit.rides?.parks?.id && credit.rides?.parks?.name) {
        parks.set(credit.rides.parks.id, credit.rides.parks.name);
      }
      
      // Manufacturers
      if (credit.rides?.manufacturer?.id && credit.rides?.manufacturer?.name) {
        manufacturers.set(credit.rides.manufacturer.id, credit.rides.manufacturer.name);
      }
    });
    
    // Combine into single options array with type prefixes
    return [
      ...Array.from(rides.entries()).map(([id, data]) => ({
        label: `🎢 ${data.name} (at ${data.park})`,
        value: `ride:${id}`,
      })),
      ...Array.from(parks.entries()).map(([id, name]) => ({
        label: `🏰 ${name}`,
        value: `park:${id}`,
      })),
      ...Array.from(manufacturers.entries()).map(([id, name]) => ({
        label: `🏭 ${name}`,
        value: `manufacturer:${id}`,
      }))
    ].sort((a, b) => a.label.localeCompare(b.label));
  }, [credits]);

  const maxRideCount = useMemo(() => {
    return Math.max(...credits.map(c => c.ride_count), 1);
  }, [credits]);

  const categoryOptions = [
    { value: 'roller_coaster', label: '🎢 Coasters', icon: '🎢' },
    { value: 'flat_ride', label: '🎪 Flat Rides', icon: '🎪' },
    { value: 'water_ride', label: '🌊 Water Rides', icon: '🌊' },
    { value: 'dark_ride', label: '🌑 Dark Rides', icon: '🌑' },
    { value: 'transport_ride', label: '🚂 Transport', icon: '🚂' },
  ];

  const toggleCategory = (category: string) => {
    const current = filters.categories || [];
    const updated = current.includes(category)
      ? current.filter(c => c !== category)
      : [...current, category];
    onFilterChange('categories', updated.length > 0 ? updated : undefined);
  };

  const toggleArrayFilter = (key: keyof FilterTypes, value: string) => {
    const current = (filters[key] as string[]) || [];
    const updated = current.includes(value)
      ? current.filter(v => v !== value)
      : [...current, value];
    onFilterChange(key, updated.length > 0 ? updated : undefined);
  };

  const removeFilter = (key: keyof FilterTypes, value?: string) => {
    if (value && Array.isArray(filters[key])) {
      const updated = (filters[key] as string[]).filter(v => v !== value);
      onFilterChange(key, updated.length > 0 ? updated : undefined);
    } else {
      onFilterChange(key, undefined);
    }
  };

  return (
    <div className={compact ? 'p-4' : ''}>
      <div className={spacingClass}>
        {/* Quick Search - Multi-select Combobox */}
        <div className={sectionSpacing}>
          <Label className="text-sm font-medium">Quick Search</Label>
          <MultiSelectCombobox
            options={searchOptions}
            value={filters.selectedSearchItems || []}
            onValueChange={(values) => 
              onFilterChange('selectedSearchItems', values.length > 0 ? values : undefined)
            }
            placeholder="Search for specific rides, parks, or manufacturers..."
            searchPlaceholder="Type to search..."
            emptyText="No matches found"
            maxDisplay={3}
            className={compact ? "h-9 text-sm" : ""}
          />
        </div>

      {/* Quick Category Chips */}
      <div className="flex flex-wrap gap-2">
        {categoryOptions.map(cat => (
          <Badge
            key={cat.value}
            variant={(filters.categories || []).includes(cat.value) ? 'default' : 'outline'}
            className="cursor-pointer hover:bg-accent transition-colors px-3 py-1.5"
            onClick={() => toggleCategory(cat.value)}
          >
            {cat.label}
          </Badge>
        ))}
        </div>

        {/* Collapsible Filter Sections */}
        <div className={sectionSpacing}>
        {/* Geographic Filters */}
        <Collapsible>
          <CollapsibleTrigger className="flex items-center justify-between w-full p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors">
            <div className="flex items-center gap-2">
              <MapPin className="w-4 h-4" />
              <span className="font-medium">Location Filters</span>
              {((filters.countries?.length || 0) + (filters.statesProvinces?.length || 0) + (filters.cities?.length || 0)) > 0 && (
                <Badge variant="secondary" className="ml-2">
                  {(filters.countries?.length || 0) + (filters.statesProvinces?.length || 0) + (filters.cities?.length || 0)}
                </Badge>
              )}
            </div>
            <ChevronDown className="w-4 h-4" />
          </CollapsibleTrigger>
          <CollapsibleContent className="p-4 space-y-3 bg-card border rounded-lg mt-1">
            {filterOptions.countries.length > 0 && (
              <div className={sectionSpacing}>
                <Label className="text-sm font-medium">Countries</Label>
                <MultiSelectCombobox
                  options={filterOptions.countries.map(c => ({ label: c, value: c }))}
                  value={filters.countries || []}
                  onValueChange={(values) =>
                    onFilterChange('countries', values.length > 0 ? values : undefined)
                  }
                  placeholder="Select countries..."
                  searchPlaceholder="Search countries..."
                  emptyText="No countries found"
                  className={compact ? "h-9 text-sm" : ""}
                />
              </div>
            )}

            {filterOptions.states.length > 0 && (
              <div className={sectionSpacing}>
                <Label className="text-sm font-medium">States/Provinces</Label>
                <MultiSelectCombobox
                  options={filterOptions.states.map(s => ({ label: s, value: s }))}
                  value={filters.statesProvinces || []}
                  onValueChange={(values) =>
                    onFilterChange('statesProvinces', values.length > 0 ? values : undefined)
                  }
                  placeholder="Select states/provinces..."
                  searchPlaceholder="Search states/provinces..."
                  emptyText="No states/provinces found"
                  className={compact ? "h-9 text-sm" : ""}
                />
              </div>
            )}
          </CollapsibleContent>
        </Collapsible>

        {/* Park Filters */}
        <Collapsible>
          <CollapsibleTrigger className="flex items-center justify-between w-full p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors">
            <div className="flex items-center gap-2">
              <Building2 className="w-4 h-4" />
              <span className="font-medium">Park Filters</span>
              {(filters.parks?.length || 0) > 0 && (
                <Badge variant="secondary" className="ml-2">{filters.parks?.length}</Badge>
              )}
            </div>
            <ChevronDown className="w-4 h-4" />
          </CollapsibleTrigger>
          <CollapsibleContent className="p-4 space-y-3 bg-card border rounded-lg mt-1">
            {filterOptions.parks.length > 0 && (
              <div className={sectionSpacing}>
                <Label className="text-sm font-medium">Specific Parks</Label>
                <MultiSelectCombobox
                  options={filterOptions.parks.map(p => ({ label: p.name, value: p.id }))}
                  value={filters.parks || []}
                  onValueChange={(values) =>
                    onFilterChange('parks', values.length > 0 ? values : undefined)
                  }
                  placeholder="Select parks..."
                  searchPlaceholder="Search parks..."
                  emptyText="No parks found"
                  className={compact ? "h-9 text-sm" : ""}
                />
              </div>
            )}
          </CollapsibleContent>
        </Collapsible>

        {/* Ride Detail Filters */}
        <Collapsible>
          <CollapsibleTrigger className="flex items-center justify-between w-full p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors">
            <div className="flex items-center gap-2">
              <Factory className="w-4 h-4" />
              <span className="font-medium">Ride Details</span>
              {(filters.manufacturers?.length || 0) > 0 && (
                <Badge variant="secondary" className="ml-2">{filters.manufacturers?.length}</Badge>
              )}
            </div>
            <ChevronDown className="w-4 h-4" />
          </CollapsibleTrigger>
          <CollapsibleContent className="p-4 space-y-3 bg-card border rounded-lg mt-1">
            {filterOptions.manufacturers.length > 0 && (
              <div className={sectionSpacing}>
                <Label className="text-sm font-medium">Manufacturers</Label>
                <MultiSelectCombobox
                  options={filterOptions.manufacturers.map(m => ({ label: m.name, value: m.id }))}
                  value={filters.manufacturers || []}
                  onValueChange={(values) =>
                    onFilterChange('manufacturers', values.length > 0 ? values : undefined)
                  }
                  placeholder="Select manufacturers..."
                  searchPlaceholder="Search manufacturers..."
                  emptyText="No manufacturers found"
                  className={compact ? "h-9 text-sm" : ""}
                />
              </div>
            )}

            {filterOptions.coasterTypes.length > 0 && (
              <div className={sectionSpacing}>
                <Label className="text-sm font-medium">Coaster Type</Label>
                <MultiSelectCombobox
                  options={filterOptions.coasterTypes.map(type => ({
                    label: type.charAt(0).toUpperCase() + type.slice(1),
                    value: type
                  }))}
                  value={filters.coasterTypes || []}
                  onValueChange={(values) =>
                    onFilterChange('coasterTypes', values.length > 0 ? values : undefined)
                  }
                  placeholder="Select coaster types..."
                  searchPlaceholder="Search types..."
                  emptyText="No coaster types found"
                  className={compact ? "h-9 text-sm" : ""}
                />
              </div>
            )}

            {filterOptions.seatingTypes.length > 0 && (
              <div className={sectionSpacing}>
                <Label className="text-sm font-medium">Seating Type</Label>
                <MultiSelectCombobox
                  options={filterOptions.seatingTypes.map(type => ({
                    label: type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase()),
                    value: type
                  }))}
                  value={filters.seatingTypes || []}
                  onValueChange={(values) =>
                    onFilterChange('seatingTypes', values.length > 0 ? values : undefined)
                  }
                  placeholder="Select seating types..."
                  searchPlaceholder="Search types..."
                  emptyText="No seating types found"
                  className={compact ? "h-9 text-sm" : ""}
                />
              </div>
            )}

            {filterOptions.intensityLevels.length > 0 && (
              <div className={sectionSpacing}>
                <Label className="text-sm font-medium">Intensity Level</Label>
                <MultiSelectCombobox
                  options={filterOptions.intensityLevels.map(level => ({
                    label: level.charAt(0).toUpperCase() + level.slice(1),
                    value: level
                  }))}
                  value={filters.intensityLevels || []}
                  onValueChange={(values) =>
                    onFilterChange('intensityLevels', values.length > 0 ? values : undefined)
                  }
                  placeholder="Select intensity levels..."
                  searchPlaceholder="Search intensity..."
                  emptyText="No intensity levels found"
                  className={compact ? "h-9 text-sm" : ""}
                />
              </div>
            )}

            {filterOptions.trackMaterials.length > 0 && (
              <div className={sectionSpacing}>
                <Label className="text-sm font-medium">Track Material</Label>
                <MultiSelectCombobox
                  options={filterOptions.trackMaterials.map(tm => ({
                    label: tm.charAt(0).toUpperCase() + tm.slice(1),
                    value: tm
                  }))}
                  value={filters.trackMaterial || []}
                  onValueChange={(values) =>
                    onFilterChange('trackMaterial', values.length > 0 ? values : undefined)
                  }
                  placeholder="Select track materials..."
                  searchPlaceholder="Search materials..."
                  emptyText="No track materials found"
                  className={compact ? "h-9 text-sm" : ""}
                />
              </div>
            )}

            <div className="space-y-2">
              <Label>Inversions</Label>
              <div className="flex items-center gap-2">
                <Checkbox
                  checked={filters.hasInversions === true}
                  onCheckedChange={(checked) => onFilterChange('hasInversions', checked ? true : undefined)}
                />
                <span className="text-sm">Has inversions</span>
              </div>
            </div>
          </CollapsibleContent>
        </Collapsible>

        {/* Statistics Filters */}
        <Collapsible>
          <CollapsibleTrigger className="flex items-center justify-between w-full p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors">
            <div className="flex items-center gap-2">
              <Calendar className="w-4 h-4" />
              <span className="font-medium">Statistics</span>
              {((filters.minRideCount !== undefined) || (filters.minSpeed !== undefined) || (filters.minHeight !== undefined)) && (
                <Badge variant="secondary" className="ml-2">Active</Badge>
              )}
            </div>
            <ChevronDown className="w-4 h-4" />
          </CollapsibleTrigger>
          <CollapsibleContent className="p-4 space-y-4 bg-card border rounded-lg mt-1">
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <Label>Ride Count</Label>
                <span className="text-sm text-muted-foreground">
                  {filters.minRideCount || 1} - {filters.maxRideCount || maxRideCount}
                </span>
              </div>
              <Slider
                value={[filters.minRideCount || 1, filters.maxRideCount || maxRideCount]}
                min={1}
                max={maxRideCount}
                step={1}
                onValueChange={([min, max]) => {
                  onFilterChange('minRideCount', min > 1 ? min : undefined);
                  onFilterChange('maxRideCount', max < maxRideCount ? max : undefined);
                }}
                className="w-full"
              />
            </div>
          </CollapsibleContent>
        </Collapsible>

        {/* Experience Filters */}
        <Collapsible>
          <CollapsibleTrigger className="flex items-center justify-between w-full p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors">
            <div className="flex items-center gap-2">
              <Star className="w-4 h-4" />
              <span className="font-medium">My Experience</span>
              {(filters.hasNotes !== undefined || filters.hasPhotos !== undefined || filters.hasRating !== undefined) && (
                <Badge variant="secondary" className="ml-2">Active</Badge>
              )}
            </div>
            <ChevronDown className="w-4 h-4" />
          </CollapsibleTrigger>
          <CollapsibleContent className="p-4 space-y-3 bg-card border rounded-lg mt-1">
            <div className="flex items-center gap-4">
              <div className="flex items-center gap-2">
                <Checkbox
                  checked={filters.hasNotes === true}
                  onCheckedChange={(checked) => onFilterChange('hasNotes', checked ? true : undefined)}
                />
                <MessageSquare className="w-4 h-4" />
                <span className="text-sm">Has notes</span>
              </div>
              <div className="flex items-center gap-2">
                <Checkbox
                  checked={filters.hasPhotos === true}
                  onCheckedChange={(checked) => onFilterChange('hasPhotos', checked ? true : undefined)}
                />
                <Image className="w-4 h-4" />
                <span className="text-sm">Has photos</span>
              </div>
            </div>

            <div className="space-y-2">
              <Label>Personal Rating</Label>
              <div className="flex items-center gap-2">
                <Checkbox
                  checked={filters.hasRating === true}
                  onCheckedChange={(checked) => onFilterChange('hasRating', checked ? true : undefined)}
                />
                <span className="text-sm">Has rating</span>
              </div>
              {filters.hasRating && (
                <Slider
                  value={[filters.minUserRating || 1]}
                  min={1}
                  max={5}
                  step={1}
                  onValueChange={([min]) => onFilterChange('minUserRating', min > 1 ? min : undefined)}
                  className="w-full"
                />
              )}
            </div>
          </CollapsibleContent>
        </Collapsible>
        </div>

        {/* Active Filters Display */}
        {activeFilterCount > 0 && (
          <div className={sectionSpacing}>
          <div className="flex items-center justify-between">
            <span className="text-sm text-muted-foreground">
              Showing <strong>{resultCount}</strong> of <strong>{totalCount}</strong> credits
              {activeFilterCount > 0 && ` (${activeFilterCount} ${activeFilterCount === 1 ? 'filter' : 'filters'} active)`}
            </span>
            <Button variant="ghost" size="sm" onClick={onClearFilters}>
              Clear All
            </Button>
          </div>
          
          <div className="flex flex-wrap gap-2">
            {filters.selectedSearchItems?.map(item => {
              const option = searchOptions.find(opt => opt.value === item);
              return option ? (
                <Badge key={item} variant="secondary" className="gap-1">
                  {option.label}
                  <X 
                    className="w-3 h-3 cursor-pointer" 
                    onClick={() => {
                      const updated = filters.selectedSearchItems!.filter(i => i !== item);
                      onFilterChange('selectedSearchItems', updated.length > 0 ? updated : undefined);
                    }}
                  />
                </Badge>
              ) : null;
            })}
            {filters.categories?.map(cat => (
              <Badge key={cat} variant="secondary" className="gap-1">
                {categoryOptions.find(c => c.value === cat)?.icon} {cat}
                <X className="w-3 h-3 cursor-pointer" onClick={() => removeFilter('categories', cat)} />
              </Badge>
            ))}
            {filters.countries?.map(country => (
              <Badge key={country} variant="secondary" className="gap-1">
                📍 {country}
                <X className="w-3 h-3 cursor-pointer" onClick={() => removeFilter('countries', country)} />
              </Badge>
            ))}
            {filters.manufacturers?.map(mfrId => {
              const mfr = filterOptions.manufacturers.find(m => m.id === mfrId);
              return mfr && (
                <Badge key={mfrId} variant="secondary" className="gap-1">
                  🏭 {mfr.name}
                  <X className="w-3 h-3 cursor-pointer" onClick={() => removeFilter('manufacturers', mfrId)} />
                </Badge>
              );
            })}
            {filters.minRideCount && filters.minRideCount > 1 && (
              <Badge variant="secondary" className="gap-1">
                {filters.minRideCount}+ rides
                <X className="w-3 h-3 cursor-pointer" onClick={() => removeFilter('minRideCount')} />
              </Badge>
            )}
            {filters.hasInversions && (
              <Badge variant="secondary" className="gap-1">
                Has inversions
                <X className="w-3 h-3 cursor-pointer" onClick={() => removeFilter('hasInversions')} />
              </Badge>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
