import React, { useState, useEffect } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Slider } from '@/components/ui/slider';
import { Checkbox } from '@/components/ui/checkbox';
import { Star, MapPin, Phone, Grid, List, Search, Heart, Filter, X, Map } from 'lucide-react';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import MapView from '@/components/MapView';
import { mockApi } from '@/services/mockApi';

export default function Explore() {
  const navigate = useNavigate();
  const params = useParams();
  const [searchParams] = useSearchParams();
  const [listings, setListings] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedLocation, setSelectedLocation] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('');
  const [viewMode, setViewMode] = useState<'grid' | 'list' | 'map'>('grid');
  const [showFilters, setShowFilters] = useState(false);
  const [priceRange, setPriceRange] = useState([0, 500]);
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [sortBy, setSortBy] = useState('latest');

  const categories = [
    { name: 'hotel', count: 3 },
    { name: 'restaurant', count: 2 },
    { name: 'tour', count: 1 },
    { name: 'apartment', count: 2 },
    { name: 'events/arts', count: 1 },
    { name: 'shops', count: 3 },
    { name: 'museum', count: 2 },
    { name: 'gymnasiums', count: 1 }
  ];

  useEffect(() => {
    // Initialize from URL parameters
    const searchParam = searchParams.get('search');
    const locationParam = searchParams.get('location');
    const categoryParam = params.category;
    
    if (searchParam) setSearchQuery(searchParam);
    if (locationParam) setSelectedLocation(locationParam);
    if (categoryParam) {
      setSelectedCategories([categoryParam]);
      setSelectedCategory(categoryParam);
    }
  }, [searchParams, params]);

  useEffect(() => {
    const fetchListings = async () => {
      try {
        let data = await mockApi.getListings() as any[];
        
        // Filter by location if specified
        if (selectedLocation) {
          data = data.filter((listing: any) => 
            listing.location?.address?.toLowerCase().includes(selectedLocation.toLowerCase())
          );
        }
        
        setListings(data as any[]);
      } catch (error) {
        console.error('Error fetching listings:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchListings();
  }, [selectedLocation]);

  const handleCategoryToggle = (categoryName: string) => {
    setSelectedCategories(prev => 
      prev.includes(categoryName) 
        ? prev.filter(cat => cat !== categoryName)
        : [...prev, categoryName]
    );
  };

  const handleListingClick = (listing: any) => {
    navigate(`/offer/${listing.id}`);
  };

  const filteredListings = listings.filter((listing) => {
    const matchesSearch = !searchQuery || 
                         listing.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         listing.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         listing.location?.address?.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory = selectedCategories.length === 0 || 
                           selectedCategories.includes(listing.category.toLowerCase()) ||
                           selectedCategories.includes(listing.category);
    const matchesPrice = listing.price >= priceRange[0] && listing.price <= priceRange[1];
    const matchesLocation = !selectedLocation ||
                           listing.location?.address?.toLowerCase().includes(selectedLocation.toLowerCase());
    return matchesSearch && matchesCategory && matchesPrice && matchesLocation;
  });

  return (
    <div className="min-h-screen bg-background">
      <Header />
      
      <div className="map-wrapper flex">
        {/* Sidebar Filters */}
        <div className={`sidebar-filters bg-white border-r transition-transform duration-300 ${
          showFilters ? 'translate-x-0' : '-translate-x-full'
        } fixed md:relative md:translate-x-0 w-80 h-screen z-40 overflow-y-auto`}>
          {/* Filter Header - Mobile Only */}
          <div className="border-b flex justify-between items-center p-3 md:hidden">
            <Button 
              variant="ghost" 
              size="icon"
              onClick={() => setShowFilters(false)}
            >
              <X className="h-4 w-4" />
            </Button>
            <span className="text-lg font-semibold">Filters</span>
            <Button variant="ghost" className="text-primary font-medium">
              Clear
            </Button>
          </div>

          <div className="p-4">
            {/* Price Filter */}
            <div className="mb-6 border-b pb-4">
              <div className="mb-3">
                <h4 className="text-lg font-semibold mb-1">Price Filter</h4>
                <p className="text-sm text-muted-foreground">Select min and max price range</p>
              </div>
              <div className="px-2">
                <Slider
                  defaultValue={priceRange}
                  max={500}
                  min={0}
                  step={10}
                  onValueChange={setPriceRange}
                  className="w-full"
                />
                <div className="flex justify-between text-sm text-muted-foreground mt-2">
                  <span>${priceRange[0]}</span>
                  <span>${priceRange[1]}</span>
                </div>
              </div>
            </div>

            {/* Categories */}
            <div className="mb-6 border-b pb-4">
              <div className="mb-3">
                <h4 className="text-lg font-semibold mb-2">Categories</h4>
                <p className="text-sm text-muted-foreground">Select categories to filter listings</p>
              </div>
              <div className="space-y-2">
                {categories.map((category) => (
                  <div key={category.name} className="flex items-center space-x-2">
                    <Checkbox
                      id={category.name}
                      checked={selectedCategories.includes(category.name)}
                      onCheckedChange={() => handleCategoryToggle(category.name)}
                    />
                    <label 
                      htmlFor={category.name} 
                      className="text-sm font-medium cursor-pointer flex-1 capitalize"
                    >
                      {category.name}
                      <span className="text-muted-foreground ml-1">({category.count})</span>
                    </label>
                  </div>
                ))}
              </div>
            </div>

            {/* Sort By */}
            <div className="mb-6 border-b pb-4">
              <div className="mb-3">
                <h4 className="text-lg font-semibold mb-1">Order by</h4>
                <p className="text-sm text-muted-foreground">Sort listings by preference</p>
              </div>
              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="latest">Latest</SelectItem>
                  <SelectItem value="nearby">Nearby</SelectItem>
                  <SelectItem value="top-rated">Top rated</SelectItem>
                  <SelectItem value="random">Random</SelectItem>
                  <SelectItem value="a-z">A-Z</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* Apply Filters Button */}
            <Button className="w-full mb-2">Apply filters</Button>
            <Button variant="ghost" className="w-full text-center">
              <Filter className="h-4 w-4 mr-2" />
              Clear filters
            </Button>
          </div>
        </div>

        {/* Main Content */}
          <div className="items-content flex-1 bg-gray-50 min-h-screen py-3 px-4">
            {/* Search Header */}
            {(searchQuery || selectedLocation || selectedCategory) && (
              <div className="mb-4 p-4 bg-white rounded-lg border">
                <h2 className="text-lg font-semibold mb-2">Search Results</h2>
                <div className="flex flex-wrap gap-2 text-sm text-muted-foreground">
                  {searchQuery && <span>Search: "{searchQuery}"</span>}
                  {selectedLocation && <span>Location: {selectedLocation}</span>}
                  {selectedCategory && <span>Category: {selectedCategory}</span>}
                </div>
              </div>
            )}
            
            <div className="flex flex-wrap items-center mb-3 gap-2">
              <div className="flex-1 text-lg">
                All <span className="font-bold text-primary">{filteredListings.length}</span> listing{filteredListings.length !== 1 ? 's' : ''} found
              </div>
            
            {/* Filter Toggle & View Mode */}
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                className="md:hidden"
                onClick={() => setShowFilters(!showFilters)}
              >
                <Filter className="h-4 w-4" />
              </Button>
              
              <div className="bg-white border rounded-lg p-1 shadow-sm">
                <Button
                  variant={viewMode === 'grid' ? 'default' : 'ghost'}
                  size="sm"
                  onClick={() => setViewMode('grid')}
                  className="px-2 py-1"
                >
                  <Grid className="h-4 w-4" />
                </Button>
                <Button
                  variant={viewMode === 'list' ? 'default' : 'ghost'}
                  size="sm"
                  onClick={() => setViewMode('list')}
                  className="px-2 py-1"
                >
                  <List className="h-4 w-4" />
                </Button>
                <Button
                  variant={viewMode === 'map' ? 'default' : 'ghost'}
                  size="sm"
                  onClick={() => setViewMode('map')}
                  className="px-2 py-1"
                >
                  <Map className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </div>

          {loading ? (
            <div className="text-center py-12">
              <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
              <p className="mt-4 text-muted-foreground">Loading listings...</p>
            </div>
          ) : viewMode === 'map' ? (
            <MapView 
              offers={filteredListings} 
              onOfferClick={handleListingClick}
            />
          ) : (
            <div className={`grid gap-4 mb-5 ${
              viewMode === 'grid' 
                ? 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3' 
                : 'grid-cols-1'
            }`}>
              {filteredListings.map((listing) => (
                <Card 
                  key={listing.id} 
                  className="bg-white rounded-lg border-0 shadow-sm hover:shadow-md transition-shadow cursor-pointer overflow-hidden"
                  onClick={() => handleListingClick(listing)}
                >
                  {/* Card Image */}
                  <div className="relative overflow-hidden">
                    <img 
                      src={listing.images[0]} 
                      alt={listing.title}
                      className="w-full h-48 object-cover hover:scale-105 transition-transform duration-300"
                    />
                    <div className="absolute top-3 left-3 flex flex-col gap-1">
                      <Badge className="bg-black/50 text-white backdrop-blur-sm">
                        <Star className="h-3 w-3 mr-1" />
                        Featured
                      </Badge>
                      <Badge className="bg-black/50 text-white backdrop-blur-sm">
                        <span className="text-xs">${listing.price}</span>
                      </Badge>
                    </div>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="absolute top-3 right-3 bg-black/20 text-white hover:bg-black/30 backdrop-blur-sm"
                      onClick={(e) => {
                        e.stopPropagation();
                        // Handle bookmark
                      }}
                    >
                      <Heart className="h-4 w-4" />
                    </Button>
                  </div>
                  
                  <CardContent className="p-3 relative">
                    {/* Category Icon */}
                    <div className="absolute -top-4 left-3 bg-primary text-white rounded-full w-8 h-8 flex items-center justify-center">
                      <Star className="h-4 w-4" />
                    </div>
                    
                    {/* Rating */}
                    <div className="flex items-center gap-2 text-primary mb-1 mt-2">
                      <div className="flex">
                        {[...Array(5)].map((_, i) => (
                          <Star 
                            key={i} 
                            className={`h-4 w-4 ${
                              i < Math.floor(listing.rating || 4.5) ? 'fill-current' : 'text-muted'
                            }`} 
                          />
                        ))}
                      </div>
                      <span className="font-medium text-primary">
                        <span className="font-semibold">({listing.rating || 4.5})</span>
                        <span className="text-sm ml-1">2,391 reviews</span>
                      </span>
                    </div>
                    
                    {/* Title */}
                    <h4 className="font-semibold text-lg mb-0 flex items-center gap-2">
                      {listing.title}
                      <Badge variant="outline" className="text-green-600 border-green-600">
                        ✓
                      </Badge>
                    </h4>
                    
                    {/* Description */}
                    <p className="text-gray-600 text-sm mt-2 mb-2">{listing.description}</p>
                    
                    {/* Contact Info */}
                    <div className="flex flex-wrap gap-3 mt-2">
                      <a 
                        href="tel:(123) 456-7890" 
                        className="flex items-center gap-2 text-sm font-semibold text-muted-foreground hover:text-primary"
                        onClick={(e) => e.stopPropagation()}
                      >
                        <Phone className="h-4 w-4" />
                        <span>(123) 456-7890</span>
                      </a>
                      <a 
                        href="#" 
                        className="flex items-center gap-2 text-sm font-semibold text-muted-foreground hover:text-primary"
                        onClick={(e) => e.stopPropagation()}
                      >
                        <MapPin className="h-4 w-4" />
                        <span>Directions</span>
                      </a>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>
      </div>
      
      {/* Overlay for mobile filters */}
      {showFilters && (
        <div 
          className="fixed inset-0 bg-black/50 z-30 md:hidden"
          onClick={() => setShowFilters(false)}
        />
      )}
      
      <Footer />
    </div>
  );
}