import { useState, useEffect } from 'react';
import { Header } from '@/components/layout/Header';
import { ParkCard } from '@/components/parks/ParkCard';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { MapPin, Search, Filter, SlidersHorizontal } from 'lucide-react';
import { Park } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';
import { useNavigate } from 'react-router-dom';

export default function Parks() {
  const [parks, setParks] = useState<Park[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState('name');
  const [filterType, setFilterType] = useState('all');
  const [filterStatus, setFilterStatus] = useState('all');
  const navigate = useNavigate();

  useEffect(() => {
    fetchParks();
  }, [sortBy, filterType, filterStatus]);

  const fetchParks = async () => {
    try {
      let query = supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`);

      // Apply filters
      if (filterType !== 'all') {
        query = query.eq('park_type', filterType);
      }
      if (filterStatus !== 'all') {
        query = query.eq('status', filterStatus);
      }

      // Apply sorting
      switch (sortBy) {
        case 'rating':
          query = query.order('average_rating', { ascending: false });
          break;
        case 'rides':
          query = query.order('ride_count', { ascending: false });
          break;
        case 'reviews':
          query = query.order('review_count', { ascending: false });
          break;
        default:
          query = query.order('name');
      }

      const { data } = await query;
      setParks(data || []);
    } catch (error) {
      console.error('Error fetching parks:', error);
    } finally {
      setLoading(false);
    }
  };

  const filteredParks = parks.filter(park =>
    park.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    park.location?.city?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    park.location?.country?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const handleParkClick = (park: Park) => {
    navigate(`/parks/${park.slug}`);
  };

  const parkTypes = [
    { value: 'all', label: 'All Types' },
    { value: 'theme_park', label: 'Theme Parks' },
    { value: 'amusement_park', label: 'Amusement Parks' },
    { value: 'water_park', label: 'Water Parks' },
    { value: 'family_entertainment', label: 'Family Entertainment' }
  ];

  const statusOptions = [
    { value: 'all', label: 'All Status' },
    { value: 'operating', label: 'Operating' },
    { value: 'seasonal', label: 'Seasonal' },
    { value: 'under_construction', label: 'Under Construction' },
    { value: 'closed', label: 'Closed' }
  ];

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="animate-pulse space-y-6">
            <div className="h-12 bg-muted rounded w-1/3"></div>
            <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {[...Array(8)].map((_, i) => (
                <div key={i} className="h-64 bg-muted rounded-lg"></div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <Header />
      
      <main className="container mx-auto px-4 py-8">
        {/* Page Header */}
        <div className="mb-8">
          <div className="flex items-center gap-3 mb-4">
            <MapPin className="w-8 h-8 text-primary" />
            <h1 className="text-4xl font-bold">Theme Parks</h1>
          </div>
          <p className="text-lg text-muted-foreground">
            Discover amazing theme parks, amusement parks, and attractions worldwide
          </p>
          <div className="flex items-center gap-2 mt-2">
            <Badge variant="secondary">{filteredParks.length} parks found</Badge>
            <Badge variant="outline">{parks.reduce((sum, park) => sum + park.ride_count, 0)} total rides</Badge>
          </div>
        </div>

        {/* Search and Filters */}
        <div className="mb-8 space-y-4">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
              <Input
                placeholder="Search parks by name, city, or country..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10"
              />
            </div>
            <div className="flex gap-2">
              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger className="w-[180px]">
                  <SlidersHorizontal className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="name">Name A-Z</SelectItem>
                  <SelectItem value="rating">Highest Rated</SelectItem>
                  <SelectItem value="rides">Most Rides</SelectItem>
                  <SelectItem value="reviews">Most Reviews</SelectItem>
                </SelectContent>
              </Select>
              
              <Select value={filterType} onValueChange={setFilterType}>
                <SelectTrigger className="w-[160px]">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {parkTypes.map(type => (
                    <SelectItem key={type.value} value={type.value}>
                      {type.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-[140px]">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {statusOptions.map(status => (
                    <SelectItem key={status.value} value={status.value}>
                      {status.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>

        {/* Parks Grid */}
        {filteredParks.length > 0 ? (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-6 gap-6">
            {filteredParks.map((park) => (
              <ParkCard 
                key={park.id} 
                park={park} 
                onClick={() => handleParkClick(park)}
              />
            ))}
          </div>
        ) : (
          <div className="text-center py-12">
            <MapPin className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
            <h3 className="text-xl font-semibold mb-2">No parks found</h3>
            <p className="text-muted-foreground">
              Try adjusting your search criteria or filters
            </p>
          </div>
        )}
      </main>
    </div>
  );
}