import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Filter, SlidersHorizontal, FerrisWheel, Plus, ArrowLeft } from 'lucide-react';
import { AutocompleteSearch } from '@/components/search/AutocompleteSearch';
import { RideCard } from '@/components/rides/RideCard';
import { RideForm } from '@/components/admin/RideForm';
import { Ride, Park } from '@/types/database';
import { RideSubmissionData } from '@/types/submission-data';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/hooks/useAuth';
import { toast } from '@/hooks/use-toast';
import { getErrorMessage } from '@/lib/errorHandler';
import { useAuthModal } from '@/hooks/useAuthModal';
import { useDocumentTitle } from '@/hooks/useDocumentTitle';
import { useOpenGraph } from '@/hooks/useOpenGraph';

export default function ParkRides() {
  const { parkSlug } = useParams<{ parkSlug: string }>();
  const navigate = useNavigate();
  const { user } = useAuth();
  const { requireAuth } = useAuthModal();
  const [park, setPark] = useState<Park | null>(null);
  const [rides, setRides] = useState<Ride[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState('name');
  const [filterCategory, setFilterCategory] = useState('all');
  
  // Update document title when park changes
  useDocumentTitle(park ? `${park.name} - Rides` : 'Park Rides');
  const [filterStatus, setFilterStatus] = useState('all');
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);

  useEffect(() => {
    if (parkSlug) {
      fetchParkAndRides();
    }
  }, [parkSlug, sortBy, filterCategory, filterStatus]);

  const fetchParkAndRides = async () => {
    try {
      setLoading(true);
      
      // Fetch park details first
      const { data: parkData, error: parkError } = await supabase
        .from('parks')
        .select('*')
        .eq('slug', parkSlug || '')
        .maybeSingle();

      if (parkError) throw parkError;
      
      if (!parkData) {
        toast({
          title: "Park Not Found",
          description: "The park you're looking for doesn't exist.",
          variant: "destructive"
        });
        navigate('/parks');
        return;
      }

      setPark(parkData);

      // Fetch rides for this park
      let query = supabase
        .from('rides')
        .select(`
          *, 
          manufacturer:companies!rides_manufacturer_id_fkey(*)
        `)
        .eq('park_id', parkData.id);

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

      // Apply sorting
      switch (sortBy) {
        case 'rating':
          query = query.order('average_rating', { ascending: false });
          break;
        case 'speed':
          query = query.order('max_speed_kmh', { ascending: false, nullsFirst: false });
          break;
      case 'height':
        query = query.order('max_height_meters', { ascending: false, nullsFirst: false });
        break;
        case 'reviews':
          query = query.order('review_count', { ascending: false });
          break;
        default:
          query = query.order('name');
      }

      const { data: ridesData, error: ridesError } = await query;
      
      if (ridesError) throw ridesError;
      
      // Supabase returns nullable types, but our Ride type uses undefined
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      setRides((ridesData || []) as any);
    } catch (error) {
      console.error('Error fetching park and rides:', error);
      toast({
        title: "Error",
        description: "Failed to load park rides.",
        variant: "destructive"
      });
    } finally {
      setLoading(false);
    }
  };

  const handleCreateSubmit = async (data: Omit<RideSubmissionData, 'park_id'> & { park_id?: string }) => {
    try {
      if (!park) {
        toast({
          title: "Error",
          description: "Park information not loaded",
          variant: "destructive"
        });
        return;
      }

      // Pre-fill park_id in the submission and convert nulls to undefined
      const submissionData = {
        ...data,
        description: data.description ?? undefined,
        park_id: park.id,
      };

      const { submitRideCreation } = await import('@/lib/entitySubmissionHelpers');
      // Type assertion needed: Form data structure doesn't perfectly match submission helper expectations
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      await submitRideCreation(submissionData as any, user!.id);

      toast({
        title: "Ride Submitted",
        description: "Your ride submission has been sent for moderation review.",
      });

      setIsCreateModalOpen(false);
    } catch (error) {
      const errorMsg = getErrorMessage(error);
      toast({
        title: "Submission Failed",
        description: errorMsg,
        variant: "destructive"
      });
    }
  };

  const filteredRides = rides.filter(ride =>
    ride.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    ride.manufacturer?.name?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  useOpenGraph({
    title: park ? `${park.name} - Rides & Attractions` : 'Park Rides',
    description: park 
      ? `Explore ${filteredRides.length} rides and attractions at ${park.name}` 
      : undefined,
    imageUrl: park?.banner_image_url ?? filteredRides[0]?.banner_image_url ?? undefined,
    imageId: park?.banner_image_id ?? filteredRides[0]?.banner_image_id ?? undefined,
    type: 'website',
    enabled: !!park && !loading
  });

  const categories = [
    { value: 'all', label: 'All Categories' },
    { value: 'roller_coaster', label: 'Roller Coasters' },
    { value: 'flat_ride', label: 'Flat Rides' },
    { value: 'water_ride', label: 'Water Rides' },
    { value: 'dark_ride', label: 'Dark Rides' },
    { value: 'kiddie_ride', label: 'Kiddie Rides' },
    { value: 'transportation', label: 'Transportation' }
  ];

  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>
    );
  }

  if (!park) {
    return null;
  }

  return (
    <div className="min-h-screen bg-background">
      <Header />
      
      <main className="container mx-auto px-4 md:px-6 lg:px-8 xl:px-8 2xl:px-10 py-6 xl:py-8">
        {/* Back Button & Page Header */}
        <div className="mb-8">
          <Button
            variant="ghost"
            onClick={() => navigate(`/parks/${park.slug}`)}
            className="mb-4 -ml-2 gap-2"
          >
            <ArrowLeft className="w-4 h-4" />
            Back to {park.name}
          </Button>
          
          <div className="flex items-center gap-3 mb-4">
            <FerrisWheel className="w-8 h-8 text-primary" />
            <h1 className="text-4xl font-bold">{park.name}</h1>
          </div>
          <p className="text-lg text-muted-foreground mb-4">
            Rides & Attractions
          </p>
          
          <div className="flex items-center justify-between">
            <div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
              <Badge variant="secondary" className="flex items-center justify-center text-sm sm:text-base px-2 py-0.5 sm:px-3 sm:py-1 whitespace-nowrap">
                {filteredRides.length} rides
              </Badge>
              <Badge variant="outline" className="flex items-center justify-center text-xs sm:text-sm px-2 py-0.5 whitespace-nowrap">
                {rides.filter(r => r.category === 'roller_coaster').length} coasters
              </Badge>
            </div>

            <div className="flex items-center gap-2">
              <Button 
                onClick={() => requireAuth(() => setIsCreateModalOpen(true), "Sign in to add a new ride")}
                className="gap-2"
              >
                <Plus className="w-4 h-4" />
                Add Ride
              </Button>
            </div>
          </div>
        </div>

        {/* Search and Filters */}
        <div className="mb-8 space-y-4">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1">
              <AutocompleteSearch
                placeholder="Search rides by name or manufacturer..."
                types={['ride']}
                limit={8}
                onSearch={(query) => setSearchQuery(query)}
                showRecentSearches={false}
              />
            </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="speed">Fastest</SelectItem>
                  <SelectItem value="height">Tallest</SelectItem>
                  <SelectItem value="reviews">Most Reviews</SelectItem>
                </SelectContent>
              </Select>
              
              <Select value={filterCategory} onValueChange={setFilterCategory}>
                <SelectTrigger className="w-[160px]">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {categories.map(category => (
                    <SelectItem key={category.value} value={category.value}>
                      {category.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>

        {/* Rides Grid */}
        {filteredRides.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
            {filteredRides.map((ride) => (
              <RideCard 
                key={ride.id} 
                ride={ride} 
                showParkName={false}
                parkSlug={park.slug}
              />
            ))}
          </div>
        ) : (
          <div className="text-center py-12">
            <FerrisWheel className="w-16 h-16 mb-4 mx-auto text-muted-foreground" />
            <h3 className="text-xl font-semibold mb-2">No rides found</h3>
            <p className="text-muted-foreground mb-4">
              {rides.length === 0 
                ? `${park.name} doesn't have any rides yet.`
                : 'Try adjusting your search criteria or filters'
              }
            </p>
            {rides.length === 0 && user && (
              <Button onClick={() => setIsCreateModalOpen(true)} className="gap-2">
                <Plus className="w-4 h-4" />
                Add First Ride
              </Button>
            )}
          </div>
        )}

        {/* Create Modal */}
        <Dialog open={isCreateModalOpen} onOpenChange={setIsCreateModalOpen}>
          <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
            <RideForm
              onSubmit={handleCreateSubmit as any}
              onCancel={() => setIsCreateModalOpen(false)}
              isEditing={false}
              initialData={{ park_id: park.id }}
            />
          </DialogContent>
        </Dialog>
      </main>
    </div>
  );
}
