import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { RotateCcw } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
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';
import { Company } from '@/types/database';

export interface DesignerFilterState {
  personType: string;
  countries: string[];
  minRating: number;
  maxRating: number;
  minReviewCount: number;
  maxReviewCount: number;
  foundedDateFrom: Date | null;
  foundedDateTo: Date | null;
  hasRating: boolean;
  hasFoundedDate: boolean;
  isIndividual: boolean;
}

export const defaultDesignerFilters: DesignerFilterState = {
  personType: 'all',
  countries: [],
  minRating: 0,
  maxRating: 5,
  minReviewCount: 0,
  maxReviewCount: 1000,
  foundedDateFrom: null,
  foundedDateTo: null,
  hasRating: false,
  hasFoundedDate: false,
  isIndividual: false,
};

interface DesignerFiltersProps {
  filters: DesignerFilterState;
  onFiltersChange: (filters: DesignerFilterState) => void;
  designers: Company[];
}

export function DesignerFilters({ filters, onFiltersChange, designers }: DesignerFiltersProps) {
  const { data: locations } = useQuery({
    queryKey: ['filter-locations'],
    queryFn: async () => {
      const { data } = await supabase
        .from('locations')
        .select('country')
        .not('country', 'is', null);
      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 maxReviewCount = useMemo(() => {
    return Math.max(...designers.map(d => d.review_count || 0), 1000);
  }, [designers]);

  const resetFilters = () => {
    onFiltersChange({ ...defaultDesignerFilters, maxReviewCount });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold">Filter Designers</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">
          <div className="space-y-2">
            <Label>Entity Type</Label>
            <Select
              value={filters.personType}
              onValueChange={(value) => onFiltersChange({ ...filters, personType: value })}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Types</SelectItem>
                <SelectItem value="company">Companies</SelectItem>
                <SelectItem value="individual">Individuals</SelectItem>
              </SelectContent>
            </Select>
          </div>

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

          <FilterDateRangePicker
            label="Founded Date"
            fromDate={filters.foundedDateFrom}
            toDate={filters.foundedDateTo}
            onFromChange={(date) => onFiltersChange({ ...filters, foundedDateFrom: date || null })}
            onToChange={(date) => onFiltersChange({ ...filters, foundedDateTo: date || 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="Review Count"
            value={[filters.minReviewCount, filters.maxReviewCount]}
            onChange={([min, max]) => onFiltersChange({ ...filters, minReviewCount: min, maxReviewCount: max })}
            min={0}
            max={maxReviewCount}
            step={10}
          />
        </div>
      </FilterSection>

      <Separator />

      <FilterSection title="Other Options">
        <div className="space-y-3">
          <div className="flex items-center space-x-2">
            <Checkbox
              id="hasRating"
              checked={filters.hasRating}
              onCheckedChange={(checked) =>
                onFiltersChange({ ...filters, hasRating: checked as boolean })
              }
            />
            <Label htmlFor="hasRating" className="cursor-pointer">
              Has rating
            </Label>
          </div>
          <div className="flex items-center space-x-2">
            <Checkbox
              id="hasFoundedDate"
              checked={filters.hasFoundedDate}
              onCheckedChange={(checked) =>
                onFiltersChange({ ...filters, hasFoundedDate: checked as boolean })
              }
            />
            <Label htmlFor="hasFoundedDate" className="cursor-pointer">
              Has founded date
            </Label>
          </div>
          <div className="flex items-center space-x-2">
            <Checkbox
              id="isIndividual"
              checked={filters.isIndividual}
              onCheckedChange={(checked) =>
                onFiltersChange({ ...filters, isIndividual: checked as boolean })
              }
            />
            <Label htmlFor="isIndividual" className="cursor-pointer">
              Individual designers only
            </Label>
          </div>
        </div>
      </FilterSection>
    </div>
  );
}
