import { useState, useEffect } from 'react';
import { motion } from 'motion/react';
import { Search, MapPin, Clock, Star, Users, Filter, X } from 'lucide-react';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Card, CardContent } from './ui/card';
import { Badge } from './ui/badge';
import { Checkbox } from './ui/checkbox';
import { Slider } from './ui/slider';
import Navbar from './Navbar';
import { CitySubmenu } from './CitySubmenu';
import { EnhancedTestimonials } from './EnhancedTestimonials';
import { Footer } from './Footer';
import { ImageWithFallback } from './figma/ImageWithFallback';

interface City {
  id: string;
  name: string;
  country: string;
  description: string;
  image: string;
  region: string;
  attractionsCount: number;
  rating: number;
  visitDuration: string;
  startingPrice: number;
  currency: string;
  category: string;
  status: 'available' | 'coming-soon';
  isPopular?: boolean;
  passesAvailable: number;
}

const cities: City[] = [
  {
    id: 'melbourne',
    name: 'Melbourne',
    country: 'Australia',
    description: 'Cultural capital with world-famous coffee culture, street art, and vibrant laneways',
    image: 'https://images.unsplash.com/photo-1624341373902-70e3a8dc9acc?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxtZWxib3VybmUlMjBjaXR5JTIwc2t5bGluZXxlbnwxfHx8fDE3NTc2NjM0ODN8MA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral',
    region: 'Australia & Oceania',
    attractionsCount: 30,
    rating: 4.8,
    visitDuration: '3-7 days',
    startingPrice: 49,
    currency: 'AUD',
    category: 'culture',
    status: 'available',
    isPopular: true,
    passesAvailable: 3
  },
  {
    id: 'sydney',
    name: 'Sydney',
    country: 'Australia',
    description: 'Iconic harbor city with the Opera House, Harbour Bridge, and stunning beaches',
    image: 'https://images.unsplash.com/photo-1523059623039-a9ed027e7fad?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxzeWRuZXklMjBvcGVyYSUyMGhvdXNlfGVufDF8fHx8MTc1NzU5MDk3MXww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral',
    region: 'Australia & Oceania',
    attractionsCount: 25,
    rating: 4.7,
    visitDuration: '3-6 days',
    startingPrice: 52,
    currency: 'AUD',
    category: 'adventure',
    status: 'coming-soon',
    isPopular: true,
    passesAvailable: 2
  },
  {
    id: 'paris',
    name: 'Paris',
    country: 'France',
    description: 'City of Light with world-famous landmarks, art museums, and romantic atmosphere',
    image: 'https://images.unsplash.com/photo-1431274172761-fca41d930114?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxwYXJpcyUyMGVpZmZlbCUyMHRvd2VyfGVufDF8fHx8MTc1NzYxNjQ2OXww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral',
    region: 'Europe',
    attractionsCount: 45,
    rating: 4.9,
    visitDuration: '4-8 days',
    startingPrice: 55,
    currency: 'EUR',
    category: 'culture',
    status: 'coming-soon',
    isPopular: true,
    passesAvailable: 4
  },
  {
    id: 'london',
    name: 'London',
    country: 'United Kingdom',
    description: 'Historic capital with royal palaces, world-class museums, and modern culture',
    image: 'https://images.unsplash.com/photo-1486299267070-83823f5448dd?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxsb25kb24lMjBiaWclMjBiZW58ZW58MXx8fHwxNzU3NjQ3OTYxfDA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral',
    region: 'Europe',
    attractionsCount: 38,
    rating: 4.8,
    visitDuration: '4-7 days',
    startingPrice: 58,
    currency: 'GBP',
    category: 'culture',
    status: 'coming-soon',
    passesAvailable: 3
  },
  {
    id: 'tokyo',
    name: 'Tokyo',
    country: 'Japan',
    description: 'Vibrant metropolis blending ancient traditions with cutting-edge technology',
    image: 'https://images.unsplash.com/photo-1588486691401-93624c48459b?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHx0b2t5byUyMGNpdHklMjBsYW5kc2NhcGV8ZW58MXx8fHwxNzU3NjYzNDk5fDA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral',
    region: 'Asia',
    attractionsCount: 52,
    rating: 4.9,
    visitDuration: '5-10 days',
    startingPrice: 68,
    currency: 'JPY',
    category: 'culture',
    status: 'coming-soon',
    isPopular: true,
    passesAvailable: 5
  },
  {
    id: 'rome',
    name: 'Rome',
    country: 'Italy',
    description: 'Eternal city with ancient history, timeless beauty, and incredible cuisine',
    image: 'https://images.unsplash.com/photo-1706884027668-4b2a1a9701ed?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxyb21lJTIwY29sb3NzZXVtJTIwYW5jaWVudHxlbnwxfHx8fDE3NTc2Mzk3NDN8MA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral',
    region: 'Europe',
    attractionsCount: 34,
    rating: 4.8,
    visitDuration: '3-6 days',
    startingPrice: 45,
    currency: 'EUR',
    category: 'culture',
    status: 'coming-soon',
    passesAvailable: 3
  },
  {
    id: 'barcelona',
    name: 'Barcelona',
    country: 'Spain',
    description: 'Architectural wonder with Gaudí masterpieces, beaches, and vibrant nightlife',
    image: 'https://images.unsplash.com/photo-1539037116277-4db20889f2d4?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxiYXJjZWxvbmElMjBjaXR5fGVufDF8fHx8MTc1NzY2MzUyOXww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral',
    region: 'Europe',
    attractionsCount: 29,
    rating: 4.7,
    visitDuration: '3-5 days',
    startingPrice: 42,
    currency: 'EUR',
    category: 'culture',
    status: 'coming-soon',
    passesAvailable: 2
  },
  {
    id: 'new-york',
    name: 'New York',
    country: 'United States',
    description: 'The city that never sleeps with iconic skyline, Broadway, and world-class dining',
    image: 'https://images.unsplash.com/photo-1496442226666-8d4d0e62e6e9?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxuZXclMjB5b3JrJTIwY2l0eXxlbnwxfHx8fDE3NTc2NjM1MzN8MA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral',
    region: 'North America',
    attractionsCount: 67,
    rating: 4.6,
    visitDuration: '4-8 days',
    startingPrice: 75,
    currency: 'USD',
    category: 'adventure',
    status: 'coming-soon',
    passesAvailable: 6
  }
];

interface CitiesPageProps {
  onBackClick: () => void;
  onHomeClick: () => void;
  onMelbourneClick: () => void;
  onPassesClick: () => void;
  onCitiesClick: () => void;
  onDealsClick: () => void;
  onCheckoutClick: () => void;
  onSignInClick: () => void;
  onAttractionsClick: () => void;
  onBlogsClick: () => void;
  onHowItWorksClick: () => void;
  onFAQClick: () => void;
  onPrivacyPolicyClick: () => void;
  onAboutUsClick: () => void;
  onProfileClick: () => void;
  onCityClick?: (cityId: string) => void;
  currentPage: string;
}

export function CitiesPage({
  onBackClick,
  onHomeClick,
  onMelbourneClick,
  onPassesClick,
  onCitiesClick,
  onDealsClick,
  onCheckoutClick,
  onSignInClick,
  onAttractionsClick,
  onBlogsClick,
  onHowItWorksClick,
  onFAQClick,
  onPrivacyPolicyClick,
  onAboutUsClick,
  onProfileClick,
  onCityClick,
  currentPage
}: CitiesPageProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedRegions, setSelectedRegions] = useState<string[]>([]);
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [selectedStatus, setSelectedStatus] = useState<string[]>([]);
  const [priceRange, setPriceRange] = useState([0, 100]);
  const [showMobileFilters, setShowMobileFilters] = useState(false);
  const [pageNumber, setPageNumber] = useState(1);
  const [itemsPerPage] = useState(9); // Show 9 cities per page (3 rows of 3)

  const regions = [
    { value: 'australia-oceania', label: 'Australia & Oceania', count: 2 },
    { value: 'europe', label: 'Europe', count: 4 },
    { value: 'asia', label: 'Asia', count: 1 },
    { value: 'north-america', label: 'North America', count: 1 }
  ];

  const categories = [
    { value: 'culture', label: 'Culture', count: 6 },
    { value: 'adventure', label: 'Adventure', count: 2 }
  ];

  const statuses = [
    { value: 'available', label: 'Available Now', count: 1 },
    { value: 'coming-soon', label: 'Coming Soon', count: 7 }
  ];

  const filteredCities = cities.filter(city => {
    const matchesSearch = city.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         city.country.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         city.description.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesRegion = selectedRegions.length === 0 || 
                         selectedRegions.some(region => 
                           city.region.toLowerCase().replace(/[^a-z]/g, '-') === region
                         );
    
    const matchesCategory = selectedCategories.length === 0 || selectedCategories.includes(city.category);
    const matchesStatus = selectedStatus.length === 0 || selectedStatus.includes(city.status);
    const matchesPrice = city.startingPrice >= priceRange[0] && city.startingPrice <= priceRange[1];
    
    return matchesSearch && matchesRegion && matchesCategory && matchesStatus && matchesPrice;
  });

  // Pagination logic
  const totalPages = Math.ceil(filteredCities.length / itemsPerPage);
  const startIndex = (pageNumber - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentCities = filteredCities.slice(startIndex, endIndex);
  const totalItems = filteredCities.length;
  const showingFrom = totalItems > 0 ? startIndex + 1 : 0;
  const showingTo = Math.min(endIndex, totalItems);

  // Reset to first page when filters change
  useEffect(() => {
    setPageNumber(1);
  }, [searchQuery, selectedRegions, selectedCategories, selectedStatus, priceRange]);

  const toggleRegion = (region: string) => {
    setSelectedRegions(prev => 
      prev.includes(region) 
        ? prev.filter(r => r !== region)
        : [...prev, region]
    );
  };

  const toggleCategory = (category: string) => {
    setSelectedCategories(prev => 
      prev.includes(category) 
        ? prev.filter(c => c !== category)
        : [...prev, category]
    );
  };

  const toggleStatus = (status: string) => {
    setSelectedStatus(prev => 
      prev.includes(status) 
        ? prev.filter(s => s !== status)
        : [...prev, status]
    );
  };

  const clearAllFilters = () => {
    setSelectedRegions([]);
    setSelectedCategories([]);
    setSelectedStatus([]);
    setPriceRange([0, 100]);
    setSearchQuery('');
  };

  const FilterSidebar = ({ isMobile = false }) => (
    <div className={`bg-white ${isMobile ? 'p-6' : 'p-6 sticky top-44'} rounded-lg border border-gray-100 h-fit`}>
      <div className="flex items-center justify-between mb-6">
        <h3 className="font-semibold text-gray-900">Filters</h3>
        {isMobile && (
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setShowMobileFilters(false)}
          >
            <X className="w-4 h-4" />
          </Button>
        )}
      </div>

      {/* Search by region */}
      <div className="mb-6">
        <h4 className="font-medium text-gray-900 mb-3">Region</h4>
        <div className="space-y-3">
          {regions.map(region => (
            <div key={region.value} className="flex items-center space-x-3">
              <Checkbox
                id={region.value}
                checked={selectedRegions.includes(region.value)}
                onCheckedChange={() => toggleRegion(region.value)}
              />
              <label
                htmlFor={region.value}
                className="text-sm text-gray-700 cursor-pointer flex-1"
              >
                {region.label} ({region.count})
              </label>
            </div>
          ))}
        </div>
      </div>

      {/* Category */}
      <div className="mb-6">
        <h4 className="font-medium text-gray-900 mb-3">Category</h4>
        <div className="space-y-3">
          {categories.map(category => (
            <div key={category.value} className="flex items-center space-x-3">
              <Checkbox
                id={category.value}
                checked={selectedCategories.includes(category.value)}
                onCheckedChange={() => toggleCategory(category.value)}
              />
              <label
                htmlFor={category.value}
                className="text-sm text-gray-700 cursor-pointer flex-1"
              >
                {category.label} ({category.count})
              </label>
            </div>
          ))}
        </div>
      </div>

      {/* Status */}
      <div className="mb-6">
        <h4 className="font-medium text-gray-900 mb-3">Availability</h4>
        <div className="space-y-3">
          {statuses.map(status => (
            <div key={status.value} className="flex items-center space-x-3">
              <Checkbox
                id={status.value}
                checked={selectedStatus.includes(status.value)}
                onCheckedChange={() => toggleStatus(status.value)}
              />
              <label
                htmlFor={status.value}
                className="text-sm text-gray-700 cursor-pointer flex-1"
              >
                {status.label} ({status.count})
              </label>
            </div>
          ))}
        </div>
      </div>

      {/* Price Range */}
      <div className="mb-6">
        <h4 className="font-medium text-gray-900 mb-3">Starting Price Range</h4>
        <div className="px-3">
          <Slider
            value={priceRange}
            onValueChange={setPriceRange}
            min={0}
            max={100}
            step={5}
            className="mb-3"
          />
          <div className="flex justify-between text-sm text-gray-600">
            <span>${priceRange[0]}</span>
            <span>${priceRange[1]}</span>
          </div>
        </div>
      </div>

      {/* Clear filters */}
      <Button
        variant="outline"
        onClick={clearAllFilters}
        className="w-full"
      >
        Clear All Filters
      </Button>
    </div>
  );

  const handleCityClick = (cityId: string) => {
    if (cityId === 'melbourne') {
      onMelbourneClick();
    } else {
      onCityClick?.(cityId);
    }
  };

  return (
    <div className="min-h-screen bg-background">
      <Navbar
        activeCity=""
        onCityChange={(city) => {
          if (city === 'Melbourne') {
            onMelbourneClick();
          }
        }}
        onSignInClick={onSignInClick}
        onPassesClick={onPassesClick}
        onCitiesClick={() => {}} // Already on cities page
        onDealsClick={onDealsClick}
        onCheckoutClick={onCheckoutClick}
        onHomeClick={onHomeClick}
        onAttractionsClick={onAttractionsClick}
        onBlogsClick={onBlogsClick}
        onHowItWorksClick={onHowItWorksClick}
        onFAQClick={onFAQClick}
        onPrivacyPolicyClick={onPrivacyPolicyClick}
        onAboutUsClick={onAboutUsClick}
        onProfileClick={onProfileClick}
        currentPage="cities"
        isUserSignedIn={!!user}
        user={user}
      />

      <div className="container mx-auto px-4 py-8">
        <div className="flex flex-col lg:flex-row gap-8 pt-32">
          {/* Desktop Sidebar */}
          <div className="hidden lg:block lg:w-1/4">
            <FilterSidebar />
          </div>

          {/* Main Content */}
          <div className="flex-1">
            {/* Header */}
            <div className="mb-8">
              <h1 className="mb-2">Explore <span className="font-bold italic">Cities</span></h1>
              <p className="text-gray-600">
                Discover amazing destinations around the world with our curated city passes
              </p>
            </div>

            {/* Search Bar */}
            <div className="mb-8">
              <div className="relative max-w-md">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                <Input
                  placeholder="Search cities..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10 bg-white border-gray-200"
                />
              </div>
            </div>

            {/* Mobile Filter Button */}
            <div className="lg:hidden mb-6">
              <Button
                variant="outline"
                onClick={() => setShowMobileFilters(true)}
                className="w-full"
              >
                <Filter className="w-4 h-4 mr-2" />
                Filters ({selectedRegions.length + selectedCategories.length + selectedStatus.length})
              </Button>
            </div>

            {/* Results Count */}
            <div className="mb-6">
              <p className="text-gray-600">
                Showing {showingFrom}-{showingTo} of {totalItems} city(s)
              </p>
            </div>

            {/* Cities Grid */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.5, delay: 0.2 }}
              className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"
            >
              {currentCities.map((city, index) => (
                <motion.div
                  key={city.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5, delay: index * 0.1 }}
                >
                  <Card 
                    className="group cursor-pointer interactive-card h-full"
                    onClick={() => handleCityClick(city.id)}
                  >
                    <CardContent className="p-0">
                      <div className="relative">
                        <ImageWithFallback
                          src={city.image}
                          alt={city.name}
                          className="w-full h-48 object-cover rounded-t-lg"
                        />
                        {city.isPopular && (
                          <Badge className="absolute top-3 left-3 bg-primary text-white">
                            Popular
                          </Badge>
                        )}
                        <div className="absolute top-3 right-3 bg-white rounded-full p-2 shadow-sm">
                          <Star className="w-4 h-4 fill-current text-yellow-500" />
                        </div>
                        <Badge 
                          className={`absolute bottom-3 right-3 ${
                            city.status === 'available' 
                              ? 'bg-green-600 text-white' 
                              : 'bg-orange-600 text-white'
                          }`}
                        >
                          {city.status === 'available' ? 'Available' : 'Coming Soon'}
                        </Badge>
                      </div>
                      
                      <div className="p-4">
                        <div className="flex items-start justify-between mb-2">
                          <div className="flex-1">
                            <p className="text-sm text-gray-500 mb-1">{city.country}</p>
                            <h3 className="font-semibold text-gray-900 group-hover:text-primary transition-colors">
                              {city.name}
                            </h3>
                          </div>
                        </div>
                        
                        <p className="text-sm text-gray-600 mb-3 line-clamp-2">
                          {city.description}
                        </p>
                        
                        <div className="flex items-center gap-4 text-sm text-gray-500 mb-3">
                          <div className="flex items-center gap-1">
                            <Users className="w-4 h-4" />
                            <span>{city.attractionsCount} attractions</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <Clock className="w-4 h-4" />
                            <span>{city.visitDuration}</span>
                          </div>
                        </div>
                        
                        <div className="flex items-center gap-4 text-sm text-gray-500 mb-3">
                          <div className="flex items-center gap-1">
                            <Star className="w-4 h-4 fill-current text-yellow-500" />
                            <span>{city.rating}</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <MapPin className="w-4 h-4" />
                            <span>{city.region}</span>
                          </div>
                        </div>
                        
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-1">
                            <span className="text-sm text-gray-500">From</span>
                            <span className="font-semibold">${city.startingPrice} {city.currency}</span>
                          </div>
                          <Badge 
                            variant="secondary"
                            className="text-xs"
                          >
                            {city.passesAvailable} {city.passesAvailable === 1 ? 'Pass' : 'Passes'}
                          </Badge>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </motion.div>
              ))}
            </motion.div>

            {totalItems === 0 && (
              <div className="text-center py-12">
                <p className="text-gray-500 mb-4">No cities found matching your criteria</p>
                <Button onClick={clearAllFilters} variant="outline">
                  Clear All Filters
                </Button>
              </div>
            )}

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="mt-12 flex flex-col sm:flex-row items-center justify-between gap-4">
                <div className="text-sm text-gray-600">
                  Page {pageNumber} of {totalPages}
                </div>
                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    onClick={() => setPageNumber(Math.max(1, pageNumber - 1))}
                    disabled={pageNumber === 1}
                    className="px-3 py-2"
                  >
                    Previous
                  </Button>
                  
                  {/* Page numbers */}
                  <div className="flex items-center gap-1">
                    {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                      let pageNum;
                      if (totalPages <= 5) {
                        pageNum = i + 1;
                      } else if (pageNumber <= 3) {
                        pageNum = i + 1;
                      } else if (pageNumber >= totalPages - 2) {
                        pageNum = totalPages - 4 + i;
                      } else {
                        pageNum = pageNumber - 2 + i;
                      }
                      
                      return (
                        <Button
                          key={pageNum}
                          variant={pageNumber === pageNum ? "default" : "outline"}
                          onClick={() => setPageNumber(pageNum)}
                          className="px-3 py-2 min-w-[40px]"
                        >
                          {pageNum}
                        </Button>
                      );
                    })}
                  </div>
                  
                  <Button
                    variant="outline"
                    onClick={() => setPageNumber(Math.min(totalPages, pageNumber + 1))}
                    disabled={pageNumber === totalPages}
                    className="px-3 py-2"
                  >
                    Next
                  </Button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Mobile Filter Modal */}
      {showMobileFilters && (
        <div className="fixed inset-0 z-50 lg:hidden">
          <div className="fixed inset-0 bg-black bg-opacity-50" onClick={() => setShowMobileFilters(false)} />
          <div className="fixed inset-y-0 left-0 w-80 bg-white overflow-y-auto">
            <FilterSidebar isMobile />
          </div>
        </div>
      )}

      {/* Enhanced Testimonials Section */}
      <EnhancedTestimonials />

      <Footer 
        onHomeClick={onHomeClick}
        onMelbourneClick={onMelbourneClick}
        onPassesClick={onPassesClick}
        onSignInClick={onSignInClick}
        onAttractionsClick={onAttractionsClick}
        onBlogsClick={onBlogsClick}
        onHowItWorksClick={onHowItWorksClick}
        onFAQClick={onFAQClick}
        onPrivacyPolicyClick={onPrivacyPolicyClick}
        currentPage={currentPage}
      />
    </div>
  );
}