import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { RotateCcw } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { Park } from '@/types/database';
import { FilterState } from '@/pages/Parks';
import { FilterRangeSlider } from '@/components/filters/FilterRangeSlider';
import { FilterDateRangePicker } from '@/components/filters/FilterDateRangePicker';
import { FilterSection } from '@/components/filters/FilterSection';
import { FilterMultiSelectCombobox } from '@/components/filters/FilterMultiSelectCombobox';
import { MultiSelectOption } from '@/components/ui/multi-select-combobox';

interface ParkFiltersProps {
  filters: FilterState;
  onFiltersChange: (filters: FilterState) => void;
  parks: Park[];
}

export function ParkFilters({ filters, onFiltersChange, parks }: ParkFiltersProps) {
  const { data: locations } = useQuery({
    queryKey: ['filter-locations'],
    queryFn: async () => {
      const { data } = await supabase
        .from('locations')
        .select('country, state_province, city')
        .not('country', 'is', null);
      return data || [];
    },
    staleTime: 5 * 60 * 1000,
  });

  const { data: operators } = useQuery({
    queryKey: ['filter-operators'],
    queryFn: async () => {
      const { data } = await supabase
        .from('companies')
        .select('id, name')
        .eq('company_type', 'operator')
        .order('name');
      return data || [];
    },
    staleTime: 5 * 60 * 1000,
  });

  const { data: propertyOwners } = useQuery({
    queryKey: ['filter-property-owners'],
    queryFn: async () => {
      const { data } = await supabase
        .from('companies')
        .select('id, name')
        .eq('company_type', 'property_owner')
        .order('name');
      return data || [];
    },
    staleTime: 5 * 60 * 1000,
  });

  const countryOptions: MultiSelectOption[] = useMemo(() => {
    const countries = new Set(locations?.map(l => l.country).filter(Boolean) || []);
    return Array.from(countries).sort().map(c => ({ label: c, value: c }));
  }, [locations]);

  const stateOptions: MultiSelectOption[] = useMemo(() => {
    const states = new Set(locations?.map(l => l.state_province).filter((s): s is string => s != null) || []);
    return Array.from(states).sort().map(s => ({ label: s, value: s }));
  }, [locations]);

  const cityOptions: MultiSelectOption[] = useMemo(() => {
    const cities = new Set(locations?.map(l => l.city).filter((c): c is string => c != null) || []);
    return Array.from(cities).sort().map(c => ({ label: c, value: c }));
  }, [locations]);

  const operatorOptions: MultiSelectOption[] = useMemo(() => {
    return (operators || []).map(o => ({ label: o.name, value: o.id }));
  }, [operators]);

  const propertyOwnerOptions: MultiSelectOption[] = useMemo(() => {
    return (propertyOwners || []).map(p => ({ label: p.name, value: p.id }));
  }, [propertyOwners]);

  const parkTypes: MultiSelectOption[] = [
    { value: 'theme_park', label: 'Theme Park' },
    { value: 'amusement_park', label: 'Amusement Park' },
    { value: 'water_park', label: 'Water Park' },
    { value: 'family_entertainment', label: 'Family Entertainment' }
  ];

  const statusOptions: MultiSelectOption[] = [
    { value: 'operating', label: 'Operating' },
    { value: 'seasonal', label: 'Seasonal' },
    { value: 'under_construction', label: 'Under Construction' },
    { value: 'closed', label: 'Closed' }
  ];

  const maxRides = useMemo(() => {
    return Math.max(...parks.map(p => p.ride_count || 0), 100);
  }, [parks]);

  const maxCoasters = useMemo(() => {
    return Math.max(...parks.map(p => p.coaster_count || 0), 50);
  }, [parks]);

  const maxReviews = useMemo(() => {
    return Math.max(...parks.map(p => p.review_count || 0), 1000);
  }, [parks]);

  const resetFilters = () => {
    onFiltersChange({
      search: '',
      parkType: [],
      status: [],
      country: [],
      states: [],
      cities: [],
      operators: [],
      propertyOwners: [],
      minRating: 0,
      maxRating: 5,
      minRides: 0,
      maxRides: maxRides,
      minCoasters: 0,
      maxCoasters: maxCoasters,
      minReviews: 0,
      maxReviews: maxReviews,
      openingYearStart: null,
      openingYearEnd: null,
    });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold">Filter Parks</h3>
        <Button variant="ghost" size="sm" onClick={resetFilters}>
          <RotateCcw className="w-4 h-4 mr-2" />
          Reset
        </Button>
      </div>

      <FilterSection title="Basic Filters">
        <div className="grid grid-cols-1 gap-4">
          <FilterMultiSelectCombobox
            label="Park Type"
            options={parkTypes}
            value={filters.parkType}
            onChange={(value) => onFiltersChange({ ...filters, parkType: value })}
            placeholder="Select park types"
          />

          <FilterMultiSelectCombobox
            label="Status"
            options={statusOptions}
            value={filters.status}
            onChange={(value) => onFiltersChange({ ...filters, status: value })}
            placeholder="Select status"
          />

          <FilterMultiSelectCombobox
            label="Country"
            options={countryOptions}
            value={filters.country}
            onChange={(value) => onFiltersChange({ ...filters, country: value })}
            placeholder="Select countries"
          />

          <FilterMultiSelectCombobox
            label="States/Provinces"
            options={stateOptions}
            value={filters.states || []}
            onChange={(value) => onFiltersChange({ ...filters, states: value })}
            placeholder="Select states"
          />

          <FilterMultiSelectCombobox
            label="Cities"
            options={cityOptions}
            value={filters.cities || []}
            onChange={(value) => onFiltersChange({ ...filters, cities: value })}
            placeholder="Select cities"
          />
        </div>
      </FilterSection>

      <Separator />

      <FilterSection title="Operators & Owners">
        <div className="grid grid-cols-1 gap-4">
          <FilterMultiSelectCombobox
            label="Operators"
            options={operatorOptions}
            value={filters.operators || []}
            onChange={(value) => onFiltersChange({ ...filters, operators: value })}
            placeholder="Select operators"
          />
          <FilterMultiSelectCombobox
            label="Property Owners"
            options={propertyOwnerOptions}
            value={filters.propertyOwners || []}
            onChange={(value) => onFiltersChange({ ...filters, propertyOwners: value })}
            placeholder="Select owners"
          />
        </div>
      </FilterSection>

      <Separator />

      <FilterSection title="Opening Dates">
        <div className="grid grid-cols-1 gap-4">
          <FilterDateRangePicker
            label="Opening Year"
            fromDate={filters.openingYearStart ? new Date(filters.openingYearStart, 0, 1) : null}
            toDate={filters.openingYearEnd ? new Date(filters.openingYearEnd, 0, 1) : null}
            onFromChange={(date) => onFiltersChange({ 
              ...filters, 
              openingYearStart: date ? date.getFullYear() : null 
            })}
            onToChange={(date) => onFiltersChange({ 
              ...filters, 
              openingYearEnd: date ? date.getFullYear() : null 
            })}
            fromPlaceholder="From year"
            toPlaceholder="To year"
          />
        </div>
      </FilterSection>

      <Separator />

      <FilterSection title="Statistics">
        <div className="grid grid-cols-1 gap-4">
          <FilterRangeSlider
            label="Rating"
            value={[filters.minRating, filters.maxRating]}
            onChange={([min, max]) => onFiltersChange({ ...filters, minRating: min, maxRating: max })}
            min={0}
            max={5}
            step={0.1}
            formatValue={(v) => `${v.toFixed(1)} stars`}
          />
          <FilterRangeSlider
            label="Ride Count"
            value={[filters.minRides, filters.maxRides]}
            onChange={([min, max]) => onFiltersChange({ ...filters, minRides: min, maxRides: max })}
            min={0}
            max={maxRides}
            step={1}
          />
          <FilterRangeSlider
            label="Coaster Count"
            value={[filters.minCoasters || 0, filters.maxCoasters || maxCoasters]}
            onChange={([min, max]) => onFiltersChange({ ...filters, minCoasters: min, maxCoasters: max })}
            min={0}
            max={maxCoasters}
            step={1}
          />
          <FilterRangeSlider
            label="Review Count"
            value={[filters.minReviews || 0, filters.maxReviews || maxReviews]}
            onChange={([min, max]) => onFiltersChange({ ...filters, minReviews: min, maxReviews: max })}
            min={0}
            max={maxReviews}
            step={10}
          />
        </div>
      </FilterSection>
    </div>
  );
}