import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Slider } from '@/components/ui/slider';
import { Badge } from '@/components/ui/badge';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { ChevronDown, Filter, X } from 'lucide-react';
import { Combobox } from '@/components/ui/combobox';
import { useCountries, useStatesProvinces, useManufacturers, useCompanyHeadquarters } from '@/hooks/useAutocompleteData';
import { DateRangePicker, DateRange } from '@/components/ui/date-range-picker';
import { AdvancedRideFilters, TechnicalSpecFilter, CoasterStatFilter } from './AdvancedRideFilters';

export interface SearchFilters {
  // Park filters
  parkType?: string;
  country?: string;
  stateProvince?: string;
  status?: string;
  openingYearMin?: number;
  openingYearMax?: number;
  openingDateRange?: DateRange;
  ratingMin?: number;
  ratingMax?: number;
  rideCountMin?: number;
  rideCountMax?: number;
  
  // Ride filters
  rideCategory?: string;
  rideType?: string;
  manufacturer?: string;
  heightMin?: number;
  heightMax?: number;
  speedMin?: number;
  speedMax?: number;
  intensityLevel?: string;
  rideDateRange?: DateRange;
  technicalSpecFilters?: TechnicalSpecFilter[];
  coasterStatFilters?: CoasterStatFilter[];
  
  // Company filters
  companyType?: string;
  foundedYearMin?: number;
  foundedYearMax?: number;
  companyDateRange?: DateRange;
  headquarters?: string;
}

interface SearchFiltersProps {
  filters: SearchFilters;
  onFiltersChange: (filters: SearchFilters) => void;
  activeTab: string;
}

export function SearchFiltersComponent({ filters, onFiltersChange, activeTab }: SearchFiltersProps) {
  const [isOpen, setIsOpen] = useState(false);

  // Fetch autocomplete data
  const { countries, loading: countriesLoading } = useCountries();
  const { statesProvinces, loading: statesLoading } = useStatesProvinces(filters.country);
  const { manufacturers, loading: manufacturersLoading } = useManufacturers();
  const { headquarters, loading: headquartersLoading } = useCompanyHeadquarters();

  const updateFilter = (key: keyof SearchFilters, value: any) => {
    onFiltersChange({ ...filters, [key]: value });
  };

  const clearFilters = () => {
    onFiltersChange({});
  };

  const hasActiveFilters = Object.values(filters).some(value => value !== undefined && value !== '');

  const currentYear = new Date().getFullYear();

  return (
    <Collapsible open={isOpen} onOpenChange={setIsOpen}>
      <Card className="w-full">
        <CollapsibleTrigger asChild>
          <CardHeader className="cursor-pointer hover:bg-muted/50 transition-colors">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Filter className="w-5 h-5" />
                <CardTitle className="text-lg">Filters</CardTitle>
                {hasActiveFilters && (
                  <Badge variant="secondary" className="ml-2">
                    Active
                  </Badge>
                )}
              </div>
              <div className="flex items-center gap-2">
                {hasActiveFilters && (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={(e) => {
                      e.stopPropagation();
                      clearFilters();
                    }}
                    className="text-xs"
                  >
                    <X className="w-4 h-4 mr-1" />
                    Clear
                  </Button>
                )}
                <ChevronDown className={`w-4 h-4 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
              </div>
            </div>
          </CardHeader>
        </CollapsibleTrigger>
        
        <CollapsibleContent>
          <CardContent className="space-y-6">
            {/* Park Filters */}
            {(activeTab === 'all' || activeTab === 'park') && (
              <div className="space-y-4">
                <h4 className="font-semibold text-primary">Park Filters</h4>
                
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="parkType">Park Type</Label>
                    <Select
                      value={filters.parkType || ''}
                      onValueChange={(value) => updateFilter('parkType', value || undefined)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="All types" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="theme_park">Theme Park</SelectItem>
                        <SelectItem value="amusement_park">Amusement Park</SelectItem>
                        <SelectItem value="water_park">Water Park</SelectItem>
                        <SelectItem value="family_entertainment_center">Family Entertainment Center</SelectItem>
                        <SelectItem value="indoor_park">Indoor Park</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="status">Status</Label>
                    <Select
                      value={filters.status || ''}
                      onValueChange={(value) => updateFilter('status', value || undefined)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="All statuses" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="operating">Operating</SelectItem>
                        <SelectItem value="closed">Closed</SelectItem>
                        <SelectItem value="under_construction">Under Construction</SelectItem>
                        <SelectItem value="seasonal">Seasonal</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Country</Label>
                    <Combobox
                      options={countries}
                      value={filters.country}
                      onValueChange={(value) => updateFilter('country', value || undefined)}
                      placeholder="Select country"
                      searchPlaceholder="Search countries..."
                      loading={countriesLoading}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label>State/Province</Label>
                    <Combobox
                      options={statesProvinces}
                      value={filters.stateProvince}
                      onValueChange={(value) => updateFilter('stateProvince', value || undefined)}
                      placeholder="Select state/province"
                      searchPlaceholder="Search states/provinces..."
                      loading={statesLoading}
                      disabled={!filters.country}
                    />
                  </div>
                </div>

                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label>Opening Date Range</Label>
                    <DateRangePicker
                      value={filters.openingDateRange}
                      onChange={(range) => updateFilter('openingDateRange', range)}
                      placeholder="Select opening date range"
                      disableFuture={true}
                      fromYear={1800}
                      presets={[
                        {
                          label: "Last 10 years",
                          range: {
                            from: new Date(new Date().getFullYear() - 10, 0, 1),
                            to: new Date(),
                          },
                        },
                        {
                          label: "Last 25 years", 
                          range: {
                            from: new Date(new Date().getFullYear() - 25, 0, 1),
                            to: new Date(),
                          },
                        },
                        {
                          label: "Before 2000",
                          range: {
                            from: new Date(1800, 0, 1),
                            to: new Date(1999, 11, 31),
                          },
                        },
                      ]}
                    />
                  </div>

                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label>Rating Range</Label>
                      <Badge variant="outline">
                        {filters.ratingMin || 0} - {filters.ratingMax || 5}
                      </Badge>
                    </div>
                    <Slider
                      value={[filters.ratingMin || 0, filters.ratingMax || 5]}
                      onValueChange={([min, max]) => {
                        updateFilter('ratingMin', min);
                        updateFilter('ratingMax', max);
                      }}
                      min={0}
                      max={5}
                      step={0.1}
                      className="w-full"
                    />
                  </div>

                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label>Number of Rides</Label>
                      <Badge variant="outline">
                        {filters.rideCountMin || 0} - {filters.rideCountMax || 100}+
                      </Badge>
                    </div>
                    <Slider
                      value={[filters.rideCountMin || 0, filters.rideCountMax || 100]}
                      onValueChange={([min, max]) => {
                        updateFilter('rideCountMin', min);
                        updateFilter('rideCountMax', max);
                      }}
                      min={0}
                      max={100}
                      step={1}
                      className="w-full"
                    />
                  </div>
                </div>
              </div>
            )}

            {/* Ride Filters */}
            {(activeTab === 'all' || activeTab === 'ride') && (
              <div className="space-y-4">
                <h4 className="font-semibold text-secondary">Ride Filters</h4>
                
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="rideCategory">Category</Label>
                    <Select
                      value={filters.rideCategory || ''}
                      onValueChange={(value) => updateFilter('rideCategory', value || undefined)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="All categories" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="roller_coaster">Roller Coaster</SelectItem>
                        <SelectItem value="flat_ride">Flat Ride</SelectItem>
                        <SelectItem value="water_ride">Water Ride</SelectItem>
                        <SelectItem value="dark_ride">Dark Ride</SelectItem>
                        <SelectItem value="family_ride">Family Ride</SelectItem>
                        <SelectItem value="thrill_ride">Thrill Ride</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="intensityLevel">Intensity Level</Label>
                    <Select
                      value={filters.intensityLevel || ''}
                      onValueChange={(value) => updateFilter('intensityLevel', value || undefined)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="All levels" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="mild">Mild</SelectItem>
                        <SelectItem value="moderate">Moderate</SelectItem>
                        <SelectItem value="intense">Intense</SelectItem>
                        <SelectItem value="extreme">Extreme</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="space-y-2">
                  <Label>Manufacturer</Label>
                  <Combobox
                    options={manufacturers}
                    value={filters.manufacturer}
                    onValueChange={(value) => updateFilter('manufacturer', value || undefined)}
                    placeholder="Select manufacturer"
                    searchPlaceholder="Search manufacturers..."
                    loading={manufacturersLoading}
                  />
                </div>

                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label>Opening Date Range</Label>
                    <DateRangePicker
                      value={filters.rideDateRange}
                      onChange={(range) => updateFilter('rideDateRange', range)}
                      placeholder="Select ride opening date range"
                      disableFuture={true}
                      fromYear={1800}
                      presets={[
                        {
                          label: "Recent (last 5 years)",
                          range: {
                            from: new Date(new Date().getFullYear() - 5, 0, 1),
                            to: new Date(),
                          },
                        },
                        {
                          label: "Modern era (2000+)",
                          range: {
                            from: new Date(2000, 0, 1),
                            to: new Date(),
                          },
                        },
                        {
                          label: "Classic era (before 2000)",
                          range: {
                            from: new Date(1800, 0, 1),
                            to: new Date(1999, 11, 31),
                          },
                        },
                      ]}
                    />
                  </div>
                  
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label>Height Range (meters)</Label>
                      <Badge variant="outline">
                        {filters.heightMin || 0}m - {filters.heightMax || 200}m
                      </Badge>
                    </div>
                    <Slider
                      value={[filters.heightMin || 0, filters.heightMax || 200]}
                      onValueChange={([min, max]) => {
                        updateFilter('heightMin', min);
                        updateFilter('heightMax', max);
                      }}
                      min={0}
                      max={200}
                      step={1}
                      className="w-full"
                    />
                  </div>

                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label>Speed Range (km/h)</Label>
                      <Badge variant="outline">
                        {filters.speedMin || 0} - {filters.speedMax || 200}+ km/h
                      </Badge>
                    </div>
                    <Slider
                      value={[filters.speedMin || 0, filters.speedMax || 200]}
                      onValueChange={([min, max]) => {
                        updateFilter('speedMin', min);
                        updateFilter('speedMax', max);
                      }}
                      min={0}
                      max={200}
                      step={5}
                      className="w-full"
                    />
                  </div>
                </div>

                {/* Advanced Ride Filters */}
                <div className="pt-4 border-t">
                  <AdvancedRideFilters
                    technicalSpecFilters={filters.technicalSpecFilters || []}
                    coasterStatFilters={filters.coasterStatFilters || []}
                    onTechnicalSpecFiltersChange={(filters) => updateFilter('technicalSpecFilters', filters)}
                    onCoasterStatFiltersChange={(filters) => updateFilter('coasterStatFilters', filters)}
                  />
                </div>
              </div>
            )}

            {/* Company Filters */}
            {(activeTab === 'all' || activeTab === 'company') && (
              <div className="space-y-4">
                <h4 className="font-semibold text-accent">Company Filters</h4>
                
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="companyType">Company Type</Label>
                    <Select
                      value={filters.companyType || ''}
                      onValueChange={(value) => updateFilter('companyType', value || undefined)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="All types" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="manufacturer">Manufacturer</SelectItem>
                        <SelectItem value="operator">Operator</SelectItem>
                        <SelectItem value="designer">Designer</SelectItem>
                        <SelectItem value="contractor">Contractor</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label>Headquarters</Label>
                    <Combobox
                      options={headquarters}
                      value={filters.headquarters}
                      onValueChange={(value) => updateFilter('headquarters', value || undefined)}
                      placeholder="Select headquarters"
                      searchPlaceholder="Search headquarters..."
                      loading={headquartersLoading}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label>Founded Date Range</Label>
                  <DateRangePicker
                    value={filters.companyDateRange}
                    onChange={(range) => updateFilter('companyDateRange', range)}
                    placeholder="Select founding date range"
                    disableFuture={true}
                    fromYear={1800}
                    presets={[
                      {
                        label: "Founded after 2000",
                        range: {
                          from: new Date(2000, 0, 1),
                          to: new Date(),
                        },
                      },
                      {
                        label: "Founded 1950-2000",
                        range: {
                          from: new Date(1950, 0, 1),
                          to: new Date(1999, 11, 31),
                        },
                      },
                      {
                        label: "Founded before 1950",
                        range: {
                          from: new Date(1800, 0, 1),
                          to: new Date(1949, 11, 31),
                        },
                      },
                    ]}
                  />
                </div>
              </div>
            )}
          </CardContent>
        </CollapsibleContent>
      </Card>
    </Collapsible>
  );
}