import { useState, useEffect } from 'react';
import { Search, Filter, MapPin, SlidersHorizontal, FerrisWheel } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Sheet, SheetContent, SheetTrigger, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { ParkCard } from './ParkCard';
import { Park } from '@/types/database';
import { supabase } from '@/lib/supabaseClient';
import { getErrorMessage } from '@/lib/errorHandler';

export function ParkGrid() {
  const [parks, setParks] = useState<Park[]>([]);
  const [filteredParks, setFilteredParks] = useState<Park[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState('name');
  const [filterStatus, setFilterStatus] = useState('all');
  const [filterType, setFilterType] = useState('all');

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

  useEffect(() => {
    filterAndSortParks();
  }, [parks, searchTerm, sortBy, filterStatus, filterType]);

  const fetchParks = async () => {
    try {
      const { data, error } = await supabase
        .from('parks')
        .select(`
          *,
          location:locations(*),
          operator:companies!parks_operator_id_fkey(*),
          property_owner:companies!parks_property_owner_id_fkey(*)
        `)
        .order('name');

      if (error) throw error;
      setParks(data || []);
    } catch (error: unknown) {
      // Parks fetch failed - display empty grid
    } finally {
      setLoading(false);
    }
  };

  const filterAndSortParks = () => {
    let filtered = parks.filter(park => {
      const matchesSearch = park.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          park.description?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          park.location?.city?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          park.location?.country?.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesStatus = filterStatus === 'all' || park.status === filterStatus;
      const matchesType = filterType === 'all' || park.park_type === filterType;

      return matchesSearch && matchesStatus && matchesType;
    });

    // Sort parks
    filtered.sort((a, b) => {
      switch (sortBy) {
        case 'name':
          return a.name.localeCompare(b.name);
        case 'rating':
          return (b.average_rating || 0) - (a.average_rating || 0);
        case 'rides':
          return (b.ride_count || 0) - (a.ride_count || 0);
        case 'recent':
          return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
        default:
          return 0;
      }
    });

    setFilteredParks(filtered);
  };

  const clearFilters = () => {
    setSearchTerm('');
    setSortBy('name');
    setFilterStatus('all');
    setFilterType('all');
  };

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

  return (
    <div className="container mx-auto px-4 py-8 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
            Discover Theme Parks
          </h2>
          <p className="text-muted-foreground mt-1">
            Explore {parks.length} amazing theme parks around the world
          </p>
        </div>
        <Button 
          variant="outline" 
          className="bg-gradient-to-r from-primary/10 to-accent/10 border-primary/20"
        >
          <MapPin className="w-4 h-4 mr-2" />
          View Map
        </Button>
      </div>

      {/* Search and Filters */}
      <div className="flex flex-col md:flex-row gap-4 items-center">
        {/* Search */}
        <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, locations, or descriptions..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10 bg-muted/50 border-border/50 focus:border-primary/50"
          />
        </div>

        {/* Quick Sort */}
        <Select value={sortBy} onValueChange={setSortBy}>
          <SelectTrigger className="w-48 bg-muted/50 border-border/50">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="name">Sort by Name</SelectItem>
            <SelectItem value="rating">Sort by Rating</SelectItem>
            <SelectItem value="rides">Sort by Ride Count</SelectItem>
            <SelectItem value="recent">Recently Added</SelectItem>
          </SelectContent>
        </Select>

        {/* Advanced Filters */}
        <Sheet>
          <SheetTrigger asChild>
            <Button variant="outline" className="flex items-center gap-2">
              <SlidersHorizontal className="w-4 h-4" />
              Filters
              {(filterStatus !== 'all' || filterType !== 'all') && (
                <Badge variant="secondary" className="ml-1">
                  {(filterStatus !== 'all' ? 1 : 0) + (filterType !== 'all' ? 1 : 0)}
                </Badge>
              )}
            </Button>
          </SheetTrigger>
          <SheetContent>
            <SheetHeader>
              <SheetTitle>Filter Parks</SheetTitle>
            </SheetHeader>
            <div className="space-y-6 mt-6">
              {/* Status Filter */}
              <div>
                <label className="text-sm font-medium mb-2 block">Park Status</label>
                <Select value={filterStatus} onValueChange={setFilterStatus}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Statuses</SelectItem>
                    <SelectItem value="operating">Operating</SelectItem>
                    <SelectItem value="seasonal">Seasonal</SelectItem>
                    <SelectItem value="under_construction">Under Construction</SelectItem>
                    <SelectItem value="closed">Closed</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* Type Filter */}
              <div>
                <label className="text-sm font-medium mb-2 block">Park Type</label>
                <Select value={filterType} onValueChange={setFilterType}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Types</SelectItem>
                    <SelectItem value="theme_park">Theme Park</SelectItem>
                    <SelectItem value="amusement_park">Amusement Park</SelectItem>
                    <SelectItem value="water_park">Water Park</SelectItem>
                    <SelectItem value="family_entertainment">Family Entertainment</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <Button onClick={clearFilters} variant="outline" className="w-full">
                Clear All Filters
              </Button>
            </div>
          </SheetContent>
        </Sheet>
      </div>

      {/* Active Filters */}
      {(filterStatus !== 'all' || filterType !== 'all' || searchTerm) && (
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-sm text-muted-foreground">Active filters:</span>
          {searchTerm && (
            <Badge variant="secondary" onClick={() => setSearchTerm('')} className="cursor-pointer">
              Search: {searchTerm} ✕
            </Badge>
          )}
          {filterStatus !== 'all' && (
            <Badge variant="secondary" onClick={() => setFilterStatus('all')} className="cursor-pointer">
              Status: {filterStatus} ✕
            </Badge>
          )}
          {filterType !== 'all' && (
            <Badge variant="secondary" onClick={() => setFilterType('all')} className="cursor-pointer">
              Type: {filterType.replace('_', ' ')} ✕
            </Badge>
          )}
          <Button variant="ghost" size="sm" onClick={clearFilters}>
            Clear all
          </Button>
        </div>
      )}

      {/* Results Count */}
      <div className="text-sm text-muted-foreground">
        Showing {filteredParks.length} of {parks.length} parks
      </div>

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