/**
 * Marketplace Catalog Page
 * Main marketplace page with grid/list view, filters, search, and sorting
 */

import React, { useEffect, useState } from 'react';
import {
  Search,
  Filter,
  X,
  Loader2,
  Grid,
  List,
  SlidersHorizontal,
  ChevronDown,
} from 'lucide-react';
import { useMarketplaceStore } from '../../../stores/marketplaceStore';
import { ProductCard } from '../components';
import type { ProductCategory, MarketplaceFilters } from '../../../types/marketplace.types';

const categoryOptions: { value: ProductCategory | ''; label: string; icon: string }[] = [
  { value: '', label: 'All Products', icon: '📦' },
  { value: 'signals', label: 'Signal Packs', icon: '📊' },
  { value: 'courses', label: 'Courses', icon: '📚' },
  { value: 'advisory', label: 'Advisory Services', icon: '👨‍💼' },
  { value: 'tools', label: 'Trading Tools', icon: '🛠️' },
];

const sortOptions = [
  { 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' },
];

export default function MarketplaceCatalog() {
  const {
    products,
    featuredProducts,
    totalProducts,
    currentPage,
    pageSize,
    loadingProducts,
    fetchProducts,
    fetchFeaturedProducts,
    setFilters,
    filters,
  } = useMarketplaceStore();

  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<ProductCategory | ''>('');
  const [sortBy, setSortBy] = useState<MarketplaceFilters['sortBy']>('popular');
  const [showFilters, setShowFilters] = useState(false);
  const [minRating, setMinRating] = useState<number | undefined>(undefined);
  const [verifiedOnly, setVerifiedOnly] = useState(false);
  const [hasFreeTrial, setHasFreeTrial] = useState(false);

  // Load initial data
  useEffect(() => {
    fetchProducts();
    fetchFeaturedProducts();
  }, [fetchProducts, fetchFeaturedProducts]);

  // Apply filters when they change
  useEffect(() => {
    const newFilters: MarketplaceFilters = {
      search: searchTerm || undefined,
      category: selectedCategory || undefined,
      sortBy,
      minRating,
      verified: verifiedOnly || undefined,
      hasFreeTrial: hasFreeTrial || undefined,
      page: 1,
      pageSize: 12,
    };
    setFilters(newFilters);
    fetchProducts(newFilters);
  }, [searchTerm, selectedCategory, sortBy, minRating, verifiedOnly, hasFreeTrial, setFilters, fetchProducts]);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    fetchProducts({ ...filters, search: searchTerm, page: 1 });
  };

  const handlePageChange = (page: number) => {
    fetchProducts({ ...filters, page });
  };

  const clearFilters = () => {
    setSearchTerm('');
    setSelectedCategory('');
    setSortBy('popular');
    setMinRating(undefined);
    setVerifiedOnly(false);
    setHasFreeTrial(false);
  };

  const hasActiveFilters =
    searchTerm || selectedCategory || minRating || verifiedOnly || hasFreeTrial || sortBy !== 'popular';

  const totalPages = Math.ceil(totalProducts / pageSize);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Marketplace</h1>
          <p className="text-gray-400">
            Discover premium signals, expert advisors, and trading courses
          </p>
        </div>

        {/* View mode toggle */}
        <div className="flex items-center gap-2 bg-gray-800 rounded-lg p-1">
          <button
            onClick={() => setViewMode('grid')}
            className={`p-2 rounded-md transition-colors ${
              viewMode === 'grid'
                ? 'bg-gray-700 text-white'
                : 'text-gray-400 hover:text-white'
            }`}
            title="Grid view"
          >
            <Grid className="w-5 h-5" />
          </button>
          <button
            onClick={() => setViewMode('list')}
            className={`p-2 rounded-md transition-colors ${
              viewMode === 'list'
                ? 'bg-gray-700 text-white'
                : 'text-gray-400 hover:text-white'
            }`}
            title="List view"
          >
            <List className="w-5 h-5" />
          </button>
        </div>
      </div>

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

      {/* Search and Filters */}
      <div className="bg-gray-800 rounded-xl border border-gray-700 p-4">
        <form onSubmit={handleSearch} 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..."
              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"
            />
          </div>

          {/* Sort and Filters */}
          <div className="flex flex-wrap gap-3">
            {/* Sort */}
            <div className="relative">
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value as MarketplaceFilters['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"
              >
                {sortOptions.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>

            {/* Filter toggle */}
            <button
              type="button"
              onClick={() => setShowFilters(!showFilters)}
              className={`px-4 py-2.5 rounded-lg border font-medium transition-colors flex items-center gap-2 ${
                showFilters || hasActiveFilters
                  ? '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
              {hasActiveFilters && (
                <span className="w-2 h-2 rounded-full bg-blue-400" />
              )}
            </button>

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

        {/* Expandable Filters */}
        {showFilters && (
          <div className="mt-4 pt-4 border-t border-gray-700 grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* Min Rating */}
            <div>
              <label className="block text-sm text-gray-400 mb-2">Minimum Rating</label>
              <div className="flex gap-2">
                {[4, 4.5, 5].map((rating) => (
                  <button
                    key={rating}
                    onClick={() => setMinRating(minRating === rating ? undefined : rating)}
                    className={`px-3 py-1.5 rounded-lg text-sm transition-colors ${
                      minRating === rating
                        ? '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'
                    }`}
                  >
                    {rating}+ Stars
                  </button>
                ))}
              </div>
            </div>

            {/* Verified Only */}
            <div>
              <label className="block text-sm text-gray-400 mb-2">Provider Status</label>
              <button
                onClick={() => setVerifiedOnly(!verifiedOnly)}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                  verifiedOnly
                    ? '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'
                }`}
              >
                Verified Only
              </button>
            </div>

            {/* Free Trial */}
            <div>
              <label className="block text-sm text-gray-400 mb-2">Pricing</label>
              <button
                onClick={() => setHasFreeTrial(!hasFreeTrial)}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                  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'
                }`}
              >
                Free Trial Available
              </button>
            </div>
          </div>
        )}

        {/* Results Count */}
        <div className="mt-4 flex items-center justify-between text-sm text-gray-400">
          <span>
            {loadingProducts ? 'Searching...' : `${totalProducts} products found`}
          </span>
          {hasActiveFilters && (
            <span className="flex items-center gap-1">
              <Filter className="w-4 h-4" />
              Filters active
            </span>
          )}
        </div>
      </div>

      {/* Featured Section (only on first page without filters) */}
      {!hasActiveFilters && currentPage === 1 && featuredProducts.length > 0 && (
        <div className="mb-8">
          <h2 className="text-xl font-semibold text-white mb-4">Featured</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {featuredProducts.slice(0, 3).map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </div>
        </div>
      )}

      {/* Product Grid/List */}
      {loadingProducts ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
        </div>
      ) : products.length > 0 ? (
        <>
          <div
            className={
              viewMode === 'grid'
                ? 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6'
                : 'flex flex-col gap-4'
            }
          >
            {products.map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-center gap-2 mt-8">
              <button
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage <= 1}
                className="px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-400 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Previous
              </button>

              <div className="flex items-center gap-1">
                {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                  let pageNum: number;
                  if (totalPages <= 5) {
                    pageNum = i + 1;
                  } else if (currentPage <= 3) {
                    pageNum = i + 1;
                  } else if (currentPage >= totalPages - 2) {
                    pageNum = totalPages - 4 + i;
                  } else {
                    pageNum = currentPage - 2 + i;
                  }

                  return (
                    <button
                      key={pageNum}
                      onClick={() => handlePageChange(pageNum)}
                      className={`w-10 h-10 rounded-lg font-medium transition-colors ${
                        currentPage === pageNum
                          ? 'bg-blue-600 text-white'
                          : 'bg-gray-800 text-gray-400 hover:text-white'
                      }`}
                    >
                      {pageNum}
                    </button>
                  );
                })}
              </div>

              <button
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage >= totalPages}
                className="px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-400 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Next
              </button>
            </div>
          )}
        </>
      ) : (
        <div className="text-center py-12">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-800 mb-4">
            <Search className="w-8 h-8 text-gray-500" />
          </div>
          <h3 className="text-lg font-medium text-white mb-2">No products found</h3>
          <p className="text-gray-400 mb-4">
            Try adjusting your filters or search with different terms
          </p>
          {hasActiveFilters && (
            <button
              onClick={clearFilters}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg transition-colors"
            >
              Clear Filters
            </button>
          )}
        </div>
      )}
    </div>
  );
}
