/**
 * Marketplace Filters Component
 * Advanced filtering for marketplace products with category, price, rating, and sorting
 */

import React, { useState, useCallback, useMemo } from 'react';
import {
  Search,
  SlidersHorizontal,
  X,
  ChevronDown,
  ChevronUp,
  Star,
  Check,
} from 'lucide-react';
import type { ProductCategory, MarketplaceFilters as FilterTypes } from '../../../types/marketplace.types';

// ============================================================================
// Types
// ============================================================================

interface MarketplaceFiltersProps {
  filters: FilterTypes;
  onFiltersChange: (filters: FilterTypes) => void;
  onSearch: (term: string) => void;
  totalResults?: number;
  isLoading?: boolean;
  compact?: boolean;
}

interface CategoryOption {
  value: ProductCategory | '';
  label: string;
  icon: string;
  color: string;
}

interface SortOption {
  value: FilterTypes['sortBy'];
  label: string;
}

// ============================================================================
// Constants
// ============================================================================

const CATEGORY_OPTIONS: CategoryOption[] = [
  { value: '', label: 'All Products', icon: '📦', color: 'bg-gray-500/20 text-gray-400' },
  { value: 'signals', label: 'Signal Packs', icon: '📊', color: 'bg-blue-500/20 text-blue-400' },
  { value: 'courses', label: 'Courses', icon: '📚', color: 'bg-green-500/20 text-green-400' },
  { value: 'advisory', label: 'Advisory', icon: '👨‍💼', color: 'bg-purple-500/20 text-purple-400' },
  { value: 'tools', label: 'Tools', icon: '🛠️', color: 'bg-orange-500/20 text-orange-400' },
];

const SORT_OPTIONS: SortOption[] = [
  { value: 'newest', label: 'Newest' },
  { value: 'popular', label: 'Most Popular' },
  { value: 'rating', label: 'Top Rated' },
  { value: 'price_asc', label: 'Price: Low to High' },
  { value: 'price_desc', label: 'Price: High to Low' },
];

const RATING_OPTIONS = [
  { value: 4.5, label: '4.5+' },
  { value: 4.0, label: '4.0+' },
  { value: 3.5, label: '3.5+' },
  { value: 3.0, label: '3.0+' },
];

const PRICE_RANGES = [
  { min: 0, max: 50, label: 'Under $50' },
  { min: 50, max: 100, label: '$50 - $100' },
  { min: 100, max: 200, label: '$100 - $200' },
  { min: 200, max: undefined, label: '$200+' },
];

// ============================================================================
// Component
// ============================================================================

export const MarketplaceFilters: React.FC<MarketplaceFiltersProps> = ({
  filters,
  onFiltersChange,
  onSearch,
  totalResults,
  isLoading = false,
  compact = false,
}) => {
  const [searchTerm, setSearchTerm] = useState(filters.search || '');
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [priceRange, setPriceRange] = useState<{ min?: number; max?: number }>({
    min: filters.minPrice,
    max: filters.maxPrice,
  });

  // Handle search submit
  const handleSearchSubmit = useCallback(
    (e: React.FormEvent) => {
      e.preventDefault();
      onSearch(searchTerm);
      onFiltersChange({ ...filters, search: searchTerm || undefined, page: 1 });
    },
    [searchTerm, filters, onSearch, onFiltersChange]
  );

  // Handle category change
  const handleCategoryChange = useCallback(
    (category: ProductCategory | '') => {
      onFiltersChange({
        ...filters,
        category: category || undefined,
        page: 1,
      });
    },
    [filters, onFiltersChange]
  );

  // Handle sort change
  const handleSortChange = useCallback(
    (sortBy: FilterTypes['sortBy']) => {
      onFiltersChange({ ...filters, sortBy, page: 1 });
    },
    [filters, onFiltersChange]
  );

  // Handle rating change
  const handleRatingChange = useCallback(
    (rating: number | undefined) => {
      onFiltersChange({
        ...filters,
        minRating: filters.minRating === rating ? undefined : rating,
        page: 1,
      });
    },
    [filters, onFiltersChange]
  );

  // Handle price range change
  const handlePriceRangeSelect = useCallback(
    (min: number, max?: number) => {
      const isCurrentRange = filters.minPrice === min && filters.maxPrice === max;
      if (isCurrentRange) {
        setPriceRange({ min: undefined, max: undefined });
        onFiltersChange({ ...filters, minPrice: undefined, maxPrice: undefined, page: 1 });
      } else {
        setPriceRange({ min, max });
        onFiltersChange({ ...filters, minPrice: min, maxPrice: max, page: 1 });
      }
    },
    [filters, onFiltersChange]
  );

  // Handle verified toggle
  const handleVerifiedToggle = useCallback(() => {
    onFiltersChange({
      ...filters,
      verified: filters.verified ? undefined : true,
      page: 1,
    });
  }, [filters, onFiltersChange]);

  // Handle free trial toggle
  const handleFreeTrialToggle = useCallback(() => {
    onFiltersChange({
      ...filters,
      hasFreeTrial: filters.hasFreeTrial ? undefined : true,
      page: 1,
    });
  }, [filters, onFiltersChange]);

  // Clear all filters
  const handleClearFilters = useCallback(() => {
    setSearchTerm('');
    setPriceRange({ min: undefined, max: undefined });
    onFiltersChange({
      page: 1,
      pageSize: filters.pageSize,
      sortBy: 'popular',
    });
    onSearch('');
  }, [filters.pageSize, onFiltersChange, onSearch]);

  // Check if any filters are active
  const hasActiveFilters = useMemo(() => {
    return !!(
      filters.search ||
      filters.category ||
      filters.minRating ||
      filters.minPrice !== undefined ||
      filters.maxPrice !== undefined ||
      filters.verified ||
      filters.hasFreeTrial ||
      (filters.sortBy && filters.sortBy !== 'popular')
    );
  }, [filters]);

  // Count active filters
  const activeFilterCount = useMemo(() => {
    let count = 0;
    if (filters.category) count++;
    if (filters.minRating) count++;
    if (filters.minPrice !== undefined || filters.maxPrice !== undefined) count++;
    if (filters.verified) count++;
    if (filters.hasFreeTrial) count++;
    return count;
  }, [filters]);

  return (
    <div className="space-y-4">
      {/* Search and Sort Bar */}
      <div className="bg-gray-800 rounded-xl border border-gray-700 p-4">
        <form onSubmit={handleSearchSubmit} className="flex flex-col lg:flex-row gap-4">
          {/* Search Input */}
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Search products, providers, topics..."
              className="w-full pl-10 pr-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-blue-500 focus:outline-none"
            />
            {searchTerm && (
              <button
                type="button"
                onClick={() => {
                  setSearchTerm('');
                  onSearch('');
                  onFiltersChange({ ...filters, search: undefined, page: 1 });
                }}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"
              >
                <X className="w-4 h-4" />
              </button>
            )}
          </div>

          <div className="flex flex-wrap gap-3">
            {/* Sort Dropdown */}
            <div className="relative">
              <select
                value={filters.sortBy || 'popular'}
                onChange={(e) => handleSortChange(e.target.value as FilterTypes['sortBy'])}
                className="appearance-none px-4 py-2.5 pr-10 bg-gray-900 border border-gray-700 rounded-lg text-white focus:border-blue-500 focus:outline-none cursor-pointer min-w-[160px]"
              >
                {SORT_OPTIONS.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
              <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
            </div>

            {/* Advanced Filters Toggle */}
            <button
              type="button"
              onClick={() => setShowAdvanced(!showAdvanced)}
              className={`px-4 py-2.5 rounded-lg border font-medium transition-colors flex items-center gap-2 ${
                showAdvanced || activeFilterCount > 0
                  ? 'bg-blue-500/20 border-blue-500/50 text-blue-400'
                  : 'bg-gray-900 border-gray-700 text-gray-400 hover:text-white'
              }`}
            >
              <SlidersHorizontal className="w-4 h-4" />
              Filters
              {activeFilterCount > 0 && (
                <span className="px-1.5 py-0.5 bg-blue-500 text-white text-xs rounded-full">
                  {activeFilterCount}
                </span>
              )}
              {showAdvanced ? (
                <ChevronUp className="w-4 h-4" />
              ) : (
                <ChevronDown className="w-4 h-4" />
              )}
            </button>

            {/* Clear Filters */}
            {hasActiveFilters && (
              <button
                type="button"
                onClick={handleClearFilters}
                className="px-4 py-2.5 text-gray-400 hover:text-white flex items-center gap-2 transition-colors"
              >
                <X className="w-4 h-4" />
                Clear All
              </button>
            )}
          </div>
        </form>

        {/* Category Pills */}
        {!compact && (
          <div className="mt-4 flex flex-wrap gap-2">
            {CATEGORY_OPTIONS.map((cat) => (
              <button
                key={cat.value}
                onClick={() => handleCategoryChange(cat.value as ProductCategory | '')}
                className={`px-4 py-2 rounded-full font-medium transition-colors flex items-center gap-2 ${
                  (filters.category || '') === cat.value
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-700 text-gray-400 hover:text-white hover:bg-gray-600'
                }`}
              >
                <span>{cat.icon}</span>
                <span>{cat.label}</span>
              </button>
            ))}
          </div>
        )}

        {/* Advanced Filters Panel */}
        {showAdvanced && (
          <div className="mt-4 pt-4 border-t border-gray-700">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              {/* Price Range */}
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-3">
                  Price Range
                </label>
                <div className="space-y-2">
                  {PRICE_RANGES.map((range) => {
                    const isSelected =
                      filters.minPrice === range.min &&
                      filters.maxPrice === range.max;
                    return (
                      <button
                        key={range.label}
                        onClick={() => handlePriceRangeSelect(range.min, range.max)}
                        className={`w-full px-3 py-2 rounded-lg text-sm text-left transition-colors flex items-center justify-between ${
                          isSelected
                            ? 'bg-blue-500/20 text-blue-400 border border-blue-500/50'
                            : 'bg-gray-900 text-gray-400 border border-gray-700 hover:text-white hover:border-gray-600'
                        }`}
                      >
                        {range.label}
                        {isSelected && <Check className="w-4 h-4" />}
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Rating Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-3">
                  Minimum Rating
                </label>
                <div className="space-y-2">
                  {RATING_OPTIONS.map((rating) => (
                    <button
                      key={rating.value}
                      onClick={() => handleRatingChange(rating.value)}
                      className={`w-full px-3 py-2 rounded-lg text-sm text-left transition-colors flex items-center gap-2 ${
                        filters.minRating === rating.value
                          ? 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/50'
                          : 'bg-gray-900 text-gray-400 border border-gray-700 hover:text-white hover:border-gray-600'
                      }`}
                    >
                      <Star
                        className={`w-4 h-4 ${
                          filters.minRating === rating.value
                            ? 'text-yellow-400 fill-yellow-400'
                            : 'text-gray-500'
                        }`}
                      />
                      {rating.label} Stars
                      {filters.minRating === rating.value && (
                        <Check className="w-4 h-4 ml-auto" />
                      )}
                    </button>
                  ))}
                </div>
              </div>

              {/* Quick Filters */}
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-3">
                  Quick Filters
                </label>
                <div className="space-y-2">
                  <button
                    onClick={handleVerifiedToggle}
                    className={`w-full px-3 py-2 rounded-lg text-sm text-left transition-colors flex items-center gap-2 ${
                      filters.verified
                        ? 'bg-blue-500/20 text-blue-400 border border-blue-500/50'
                        : 'bg-gray-900 text-gray-400 border border-gray-700 hover:text-white hover:border-gray-600'
                    }`}
                  >
                    <div
                      className={`w-4 h-4 rounded border flex items-center justify-center ${
                        filters.verified
                          ? 'bg-blue-500 border-blue-500'
                          : 'border-gray-600'
                      }`}
                    >
                      {filters.verified && <Check className="w-3 h-3 text-white" />}
                    </div>
                    Verified Providers Only
                  </button>

                  <button
                    onClick={handleFreeTrialToggle}
                    className={`w-full px-3 py-2 rounded-lg text-sm text-left transition-colors flex items-center gap-2 ${
                      filters.hasFreeTrial
                        ? 'bg-green-500/20 text-green-400 border border-green-500/50'
                        : 'bg-gray-900 text-gray-400 border border-gray-700 hover:text-white hover:border-gray-600'
                    }`}
                  >
                    <div
                      className={`w-4 h-4 rounded border flex items-center justify-center ${
                        filters.hasFreeTrial
                          ? 'bg-green-500 border-green-500'
                          : 'border-gray-600'
                      }`}
                    >
                      {filters.hasFreeTrial && <Check className="w-3 h-3 text-white" />}
                    </div>
                    Free Trial Available
                  </button>
                </div>
              </div>

              {/* Active Filters Summary */}
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-3">
                  Active Filters
                </label>
                <div className="bg-gray-900 rounded-lg p-3 border border-gray-700">
                  {hasActiveFilters ? (
                    <div className="flex flex-wrap gap-2">
                      {filters.category && (
                        <span className="px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded-full flex items-center gap-1">
                          {CATEGORY_OPTIONS.find((c) => c.value === filters.category)?.label}
                          <button
                            onClick={() => handleCategoryChange('')}
                            className="hover:text-white"
                          >
                            <X className="w-3 h-3" />
                          </button>
                        </span>
                      )}
                      {filters.minRating && (
                        <span className="px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded-full flex items-center gap-1">
                          {filters.minRating}+ Stars
                          <button
                            onClick={() => handleRatingChange(undefined)}
                            className="hover:text-white"
                          >
                            <X className="w-3 h-3" />
                          </button>
                        </span>
                      )}
                      {(filters.minPrice !== undefined || filters.maxPrice !== undefined) && (
                        <span className="px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded-full flex items-center gap-1">
                          ${filters.minPrice || 0}
                          {filters.maxPrice ? ` - $${filters.maxPrice}` : '+'}
                          <button
                            onClick={() => handlePriceRangeSelect(0, undefined)}
                            className="hover:text-white"
                          >
                            <X className="w-3 h-3" />
                          </button>
                        </span>
                      )}
                      {filters.verified && (
                        <span className="px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded-full flex items-center gap-1">
                          Verified
                          <button onClick={handleVerifiedToggle} className="hover:text-white">
                            <X className="w-3 h-3" />
                          </button>
                        </span>
                      )}
                      {filters.hasFreeTrial && (
                        <span className="px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded-full flex items-center gap-1">
                          Free Trial
                          <button onClick={handleFreeTrialToggle} className="hover:text-white">
                            <X className="w-3 h-3" />
                          </button>
                        </span>
                      )}
                    </div>
                  ) : (
                    <p className="text-gray-500 text-sm">No filters applied</p>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Results Count */}
        <div className="mt-4 flex items-center justify-between text-sm text-gray-400">
          <span>
            {isLoading
              ? 'Searching...'
              : totalResults !== undefined
              ? `${totalResults.toLocaleString()} products found`
              : 'Loading...'}
          </span>
        </div>
      </div>
    </div>
  );
};

export default MarketplaceFilters;
