import { useState, lazy, Suspense, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header';
import { getBannerUrls } from '@/lib/cloudflareImageUtils';
import { trackPageView } from '@/lib/viewTracking';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Separator } from '@/components/ui/separator';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { AdminFormSkeleton } from '@/components/loading/PageSkeletons';
import { 
  MapPin, 
  Star, 
  Clock, 
  Zap,
  ArrowLeft,
  Users,
  Ruler,
  Timer,
  TrendingUp,
  TrendingDown,
  Camera,
  Heart,
  RotateCcw,
  AlertTriangle,
  FerrisWheel,
  Waves,
  Theater,
  Train,
  Edit,
  Wrench,
  Sparkles,
  Repeat,
  Baby
} from 'lucide-react';
import { ReviewsSection } from '@/components/reviews/ReviewsSection';
import { MeasurementDisplay } from '@/components/ui/measurement-display';
import { EntityPhotoGallery } from '@/components/upload/EntityPhotoGallery';
import { RatingDistribution } from '@/components/rides/RatingDistribution';
import { RideHighlights } from '@/components/rides/RideHighlights';
import { SimilarRides } from '@/components/rides/SimilarRides';
import { FormerNames } from '@/components/rides/FormerNames';
import { RecentPhotosPreview } from '@/components/rides/RecentPhotosPreview';
import { ParkLocationMap } from '@/components/maps/ParkLocationMap';
import { Ride } from '@/types/database';
import { useAuth } from '@/hooks/useAuth';
import { useRideDetail } from '@/hooks/rides/useRideDetail';
import { usePhotoCount } from '@/hooks/photos/usePhotoCount';

// Lazy load admin forms
const RideForm = lazy(() => import('@/components/admin/RideForm').then(m => ({ default: m.RideForm })));
import { useUserRole } from '@/hooks/useUserRole';
import { toast } from '@/hooks/use-toast';
import { getErrorMessage } from '@/lib/errorHandler';
import { VersionIndicator } from '@/components/versioning/VersionIndicator';
import { EntityHistoryTabs } from '@/components/history/EntityHistoryTabs';
import { useAuthModal } from '@/hooks/useAuthModal';
import { MetaTags } from '@/components/seo';

// Extended Ride type with additional properties for easier access
interface RideWithParkId extends Ride {
  currentParkId?: string;
}

export default function RideDetail() {
  const { parkSlug, rideSlug } = useParams<{ parkSlug: string; rideSlug: string }>();
  const navigate = useNavigate();
  const { user } = useAuth();
  const { isModerator } = useUserRole();
  const { requireAuth } = useAuthModal();
  const [activeTab, setActiveTab] = useState("overview");
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  
  // Fetch ride data with caching
  const { data: rideData, isLoading: loading } = useRideDetail(parkSlug, rideSlug);
  
  // Cast to RideWithParkId to include currentParkId
  const ride = rideData as RideWithParkId | null;
  
  // Fetch photo count with caching
  const { data: photoCount = 0, isLoading: statsLoading } = usePhotoCount('ride', ride?.id, !!ride?.id);

  // Track page view when ride is loaded
  useEffect(() => {
    if (ride?.id) {
      trackPageView('ride', ride.id);
    }
  }, [ride?.id]);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'operating': return 'bg-green-500/20 text-green-400 border-green-500/30';
      case 'seasonal': return 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30';
      case 'under_construction': return 'bg-blue-500/20 text-blue-400 border-blue-500/30';
      default: return 'bg-red-500/20 text-red-400 border-red-500/30';
    }
  };

  const getRideIcon = (category: string) => {
    switch (category) {
      case 'roller_coaster': return <FerrisWheel className="w-20 h-20" />;
      case 'water_ride': return <Waves className="w-20 h-20" />;
      case 'dark_ride': return <Theater className="w-20 h-20" />;
      case 'flat_ride': return <FerrisWheel className="w-20 h-20" />;
      case 'kiddie_ride': return <FerrisWheel className="w-20 h-20" />;
      case 'transportation': return <Train className="w-20 h-20" />;
      default: return <FerrisWheel className="w-20 h-20" />;
    }
  };

  const formatCategory = (category: string) => {
    return category.split('_').map(word => 
      word.charAt(0).toUpperCase() + word.slice(1)
    ).join(' ');
  };

  const handleEditSubmit = async (data: any) => {
    if (!user || !ride) return;

    try {
      // Everyone goes through submission queue
      const { submitRideUpdate } = await import('@/lib/entitySubmissionHelpers');
      await submitRideUpdate(ride.id, data, user.id);

      toast({
        title: "Edit Submitted",
        description: isModerator()
          ? "Your edit has been submitted. You can approve it in the moderation queue."
          : "Your ride edit has been submitted for review."
      });

      setIsEditModalOpen(false);
    } catch (error) {
      const errorMsg = getErrorMessage(error);
      toast({
        title: "Error",
        description: errorMsg || "Failed to submit edit.",
        variant: "destructive"
      });
    }
  };

  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-64 bg-muted rounded-lg"></div>
            <div className="h-8 bg-muted rounded w-1/2"></div>
            <div className="h-4 bg-muted rounded w-1/3"></div>
          </div>
        </div>
      </div>
    );
  }

  if (!ride || !ride.park) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="text-center py-12">
            <h1 className="text-2xl font-bold mb-4">Ride Not Found</h1>
            <p className="text-muted-foreground mb-6">
              The ride you're looking for doesn't exist or has been removed.
            </p>
            <Button onClick={() => navigate('/rides')}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              Back to Rides
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <MetaTags entityType="ride" entitySlug={rideSlug} parkSlug={parkSlug} />
      <Header />
      
      <main className="container mx-auto px-4 py-8 max-w-7xl">
        {/* Back Button and Edit Button */}
        <div className="flex items-center justify-between mb-6">
          <Button 
            variant="ghost" 
            onClick={() => navigate(`/parks/${ride.park?.slug}`)}
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back to {ride.park?.name}
          </Button>
          
          <Button 
            variant="outline"
            onClick={() => requireAuth(() => setIsEditModalOpen(true), "Sign in to edit this ride")}
          >
            <Edit className="w-4 h-4 mr-2" />
            Edit Ride
          </Button>
        </div>

        {/* Hero Section */}
        <div className="relative mb-8">
          <div className="aspect-[21/9] bg-gradient-to-br from-primary/20 via-secondary/20 to-accent/20 rounded-lg overflow-hidden relative">
            {(ride.banner_image_url || ride.banner_image_id) ? (
              <picture>
                <source 
                  media="(max-width: 768px)" 
                  srcSet={getBannerUrls(ride.banner_image_id ?? undefined).mobile || ride.banner_image_url || undefined} 
                />
                <img 
                  src={getBannerUrls(ride.banner_image_id ?? undefined).desktop || ride.banner_image_url || undefined}
                  alt={ride.name}
                  className="w-full h-full object-cover"
                  loading="eager"
                />
              </picture>
            ) : (
              <div className="flex items-center justify-center h-full">
                <div className="opacity-50">
                  {getRideIcon(ride.category)}
                </div>
              </div>
            )}
            <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />
            
            {/* Ride Title Overlay */}
            <div className="absolute bottom-0 left-0 right-0 p-8">
              <div className="flex items-end justify-between">
                <div>
                  <div className="flex items-center gap-3 mb-2">
                    <Badge className={`${getStatusColor(ride.status)} border`}>
                      {ride.status.replace('_', ' ').toUpperCase()}
                    </Badge>
                    <Badge variant="outline" className="bg-black/20 text-white border-white/20">
                      {formatCategory(ride.category)}
                    </Badge>
                  </div>
                  <h1 className="text-4xl md:text-6xl font-bold text-white mb-2">
                    {ride.name}
                  </h1>
                  <div className="flex items-center text-white/90 text-lg">
                    <MapPin className="w-5 h-5 mr-2" />
                    {ride.park.name}
                  </div>
                  <div className="mt-3">
                    <VersionIndicator 
                      entityType="ride" 
                      entityId={ride.id} 
                      entityName={ride.name}
                    />
                  </div>
                </div>
                
                {(ride.average_rating ?? 0) > 0 && (
                  <div className="bg-black/30 backdrop-blur-md rounded-lg p-6 text-center min-w-[160px]">
                    <div className="flex items-center justify-center gap-2 text-white mb-2">
                      <Star className="w-6 h-6 fill-yellow-400 text-yellow-400" />
                      <span className="text-3xl font-bold">
                        {(ride.average_rating ?? 0).toFixed(1)}
                      </span>
                    </div>
                    <div className="text-white/90 text-sm mb-3">
                      {ride.review_count} {ride.review_count === 1 ? "review" : "reviews"}
                    </div>
                    <Button 
                      size="sm" 
                      variant="secondary"
                      onClick={() => setActiveTab("reviews")}
                    >
                      Write Review
                    </Button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Quick Stats */}
        <div className="max-w-6xl mx-auto mb-8">
          <div className="flex flex-wrap justify-center gap-3 lg:gap-4">
          {ride.max_speed_kmh !== null && ride.max_speed_kmh !== undefined && ride.max_speed_kmh > 0 && (
            <Card>
              <CardContent className="p-4 text-center">
                <Zap className="w-6 h-6 text-primary mx-auto mb-2" />
                <div className="text-2xl font-bold text-primary">
                  <MeasurementDisplay value={ride.max_speed_kmh} type="speed" />
                </div>
              </CardContent>
            </Card>
          )}
          
          {ride.max_height_meters !== null && ride.max_height_meters !== undefined && ride.max_height_meters > 0 && (
            <Card>
              <CardContent className="p-4 text-center">
                <TrendingUp className="w-6 h-6 text-accent mx-auto mb-2" />
                <div className="text-2xl font-bold text-accent">
                  <MeasurementDisplay value={ride.max_height_meters} type="distance" />
                </div>
              </CardContent>
            </Card>
          )}
          
          {ride.length_meters !== null && ride.length_meters !== undefined && ride.length_meters > 0 && (
            <Card>
              <CardContent className="p-4 text-center">
                <Ruler className="w-6 h-6 text-secondary mx-auto mb-2" />
                <div className="text-2xl font-bold text-secondary">
                  <MeasurementDisplay value={ride.length_meters} type="distance" />
                </div>
                <div className="text-sm text-muted-foreground">long</div>
              </CardContent>
            </Card>
          )}
          
          {ride.duration_seconds !== null && ride.duration_seconds !== undefined && ride.duration_seconds > 0 && (
            <Card>
              <CardContent className="p-4 text-center">
                <Timer className="w-6 h-6 text-primary mx-auto mb-2" />
                <div className="text-2xl font-bold text-primary">{Math.floor(ride.duration_seconds / 60)}:{(ride.duration_seconds % 60).toString().padStart(2, '0')}</div>
                <div className="text-sm text-muted-foreground">duration</div>
              </CardContent>
            </Card>
          )}
          
          {ride.capacity_per_hour !== null && ride.capacity_per_hour !== undefined && ride.capacity_per_hour > 0 && (
            <Card>
              <CardContent className="p-4 text-center">
                <Users className="w-6 h-6 text-accent mx-auto mb-2" />
                <div className="text-2xl font-bold text-accent">{ride.capacity_per_hour}</div>
                <div className="text-sm text-muted-foreground">riders/hour</div>
              </CardContent>
            </Card>
          )}
          
          {ride.inversions !== null && ride.inversions !== undefined && 
           (ride.category === 'roller_coaster' || ride.category?.toLowerCase().includes('coaster')) && (
            <Card>
              <CardContent className="p-4 text-center">
                <RotateCcw className="w-6 h-6 text-accent mx-auto mb-2" />
                <div className="text-2xl font-bold text-accent">{ride.inversions}</div>
                <div className="text-sm text-muted-foreground">inversions</div>
              </CardContent>
            </Card>
          )}

          {/* New roller coaster specific stats */}
          {ride.drop_height_meters !== null && ride.drop_height_meters !== undefined && ride.drop_height_meters > 0 && (
            <Card>
              <CardContent className="p-4 text-center">
                <TrendingDown className="w-6 h-6 mx-auto mb-2 text-destructive" />
                <div className="text-2xl font-bold text-destructive">
                  <MeasurementDisplay value={ride.drop_height_meters} type="distance" />
                </div>
                <div className="text-sm text-muted-foreground">drop</div>
              </CardContent>
            </Card>
          )}

          {ride.max_g_force !== null && ride.max_g_force !== undefined && ride.max_g_force > 0 && (
            <Card>
              <CardContent className="p-4 text-center">
                <Zap className="w-6 h-6 mx-auto mb-2 text-warning" />
                <div className="text-2xl font-bold text-warning">{ride.max_g_force}g</div>
                <div className="text-sm text-muted-foreground">max G-force</div>
              </CardContent>
            </Card>
          )}
        </div>
        </div>


        {/* Main Content */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-2 md:grid-cols-5">
            <TabsTrigger value="overview">Overview</TabsTrigger>
            <TabsTrigger value="specs">Specifications</TabsTrigger>
            <TabsTrigger value="reviews">
              Reviews {(ride.review_count ?? 0) > 0 && `(${ride.review_count})`}
            </TabsTrigger>
            <TabsTrigger value="photos">
              Photos {!statsLoading && photoCount > 0 && `(${photoCount})`}
            </TabsTrigger>
            <TabsTrigger value="history">History</TabsTrigger>
          </TabsList>

          <TabsContent value="overview" className="mt-6">
            <div className="grid lg:grid-cols-3 gap-6">
              <div className="lg:col-span-2 space-y-6">
                {/* Description */}
                {ride.description && (
                  <Card>
                    <CardHeader>
                      <CardTitle>About {ride.name}</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-muted-foreground leading-relaxed">
                        {ride.description}
                      </p>
                    </CardContent>
                  </Card>
                )}

                {ride.name_history && ride.name_history.length > 0 && (
                  <FormerNames nameHistory={ride.name_history} currentName={ride.name} />
                )}

                <SimilarRides 
                  currentRideId={ride.id}
                  parkId={ride.currentParkId || ''}
                  parkSlug={parkSlug || ''}
                  category={ride.category}
                />

                <RecentPhotosPreview 
                  rideId={ride.id}
                  onViewAll={() => setActiveTab("photos")}
                />
              </div>

              <div className="space-y-6">
                <RatingDistribution 
                  rideId={ride.id}
                  totalReviews={ride.review_count ?? 0}
                  averageRating={ride.average_rating ?? 0}
                />
                {/* Ride Information */}
                <Card>
                  <CardHeader>
                    <CardTitle>Ride Information</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div>
                      <div className="font-medium">Category</div>
                      <div className="text-sm text-muted-foreground">
                        {formatCategory(ride.category)}
                      </div>
                    </div>

                    {ride.opening_date && (
                      <div className="flex items-center gap-3">
                        <Clock className="w-4 h-4 text-muted-foreground" />
                        <div>
                          <div className="font-medium">Opened</div>
                          <div className="text-sm text-muted-foreground">
                            {ride.opening_date.split('-')[0]}
                          </div>
                        </div>
                      </div>
                    )}

                    {ride.manufacturer && (
                      <div className="flex items-center gap-3">
                        <Users className="w-4 h-4 text-muted-foreground" />
                        <div>
                          <div className="font-medium">Manufacturer</div>
                          <div className="text-sm text-muted-foreground">
                            {ride.manufacturer.name}
                          </div>
                        </div>
                      </div>
                    )}

                    {ride.designer && (
                      <div className="flex items-center gap-3">
                        <Users className="w-4 h-4 text-muted-foreground" />
                        <div>
                          <div className="font-medium">Designer</div>
                          <div className="text-sm text-muted-foreground">
                            {ride.designer.name}
                          </div>
                        </div>
                      </div>
                    )}

                    {/* Roller Coaster Specific Info */}
                    {ride.category === 'roller_coaster' && (ride.coaster_type || ride.seating_type || ride.intensity_level) && (
                      <>
                        <Separator />
                        <div className="space-y-3">
                          <div className="font-medium">Coaster Details</div>
                          {ride.coaster_type && (
                            <div className="flex items-center gap-3">
                              <div className="text-lg">🎢</div>
                              <div>
                                <div className="font-medium">Type</div>
                                <div className="text-sm text-muted-foreground">
                                  {ride.coaster_type.charAt(0).toUpperCase() + ride.coaster_type.slice(1)}
                                </div>
                              </div>
                            </div>
                          )}
                          {ride.seating_type && (
                            <div className="flex items-center gap-3">
                              <div className="text-lg">💺</div>
                              <div>
                                <div className="font-medium">Seating</div>
                                <div className="text-sm text-muted-foreground">
                                  {ride.seating_type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
                                </div>
                              </div>
                            </div>
                          )}
                          {ride.intensity_level && (
                            <div className="flex items-center gap-3">
                              <div className="text-lg">🔥</div>
                              <div>
                                <div className="font-medium">Intensity</div>
                                <div className="text-sm text-muted-foreground">
                                  {ride.intensity_level.charAt(0).toUpperCase() + ride.intensity_level.slice(1)}
                                </div>
                              </div>
                            </div>
                          )}
                        </div>
                      </>
                    )}

                    <Separator />

                    <div className="space-y-2">
                      <div className="font-medium">Located at</div>
                      <Button 
                        variant="outline" 
                        className="w-full justify-start"
                        onClick={() => navigate(`/parks/${ride.park?.slug}`)}
                      >
                        <MapPin className="w-4 h-4 mr-2" />
                        {ride.park.name}
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          </TabsContent>

          <TabsContent value="specs" className="mt-6">
            <div className="grid md:grid-cols-2 gap-6">
              {/* Performance Stats */}
              <Card>
                <CardHeader>
                  <CardTitle>Performance</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {ride.max_speed_kmh && (
                    <div className="flex justify-between">
                      <span>Maximum Speed</span>
                      <span className="font-medium">
                        <MeasurementDisplay value={ride.max_speed_kmh} type="speed" />
                      </span>
                    </div>
                  )}
                  {ride.max_height_meters && (
                    <div className="flex justify-between">
                      <span>Maximum Height</span>
                      <span className="font-medium">
                        <MeasurementDisplay value={ride.max_height_meters} type="distance" />
                      </span>
                    </div>
                  )}
                  {ride.length_meters && (
                    <div className="flex justify-between">
                      <span>Track Length</span>
                      <span className="font-medium">
                        <MeasurementDisplay value={ride.length_meters} type="distance" />
                      </span>
                    </div>
                  )}
                  {ride.duration_seconds && (
                    <div className="flex justify-between">
                      <span>Ride Duration</span>
                      <span className="font-medium">{Math.floor(ride.duration_seconds / 60)}:{(ride.duration_seconds % 60).toString().padStart(2, '0')}</span>
                    </div>
                  )}
                  {ride.inversions && ride.inversions > 0 && (
                    <div className="flex justify-between">
                      <span>Inversions</span>
                      <span className="font-medium">{ride.inversions}</span>
                    </div>
                  )}
                  {ride.drop_height_meters && (
                    <div className="flex justify-between">
                      <span>Drop Height</span>
                      <span className="font-medium">
                        <MeasurementDisplay value={ride.drop_height_meters} type="distance" />
                      </span>
                    </div>
                  )}
                  {ride.max_g_force && (
                    <div className="flex justify-between">
                      <span>Maximum G-Force</span>
                      <span className="font-medium">{ride.max_g_force}g</span>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* Operational Info */}
              <Card>
                <CardHeader>
                  <CardTitle>Operational Details</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {ride.capacity_per_hour && (
                    <div className="flex justify-between">
                      <span>Capacity</span>
                      <span className="font-medium">{ride.capacity_per_hour} riders/hour</span>
                    </div>
                  )}
                  {ride.height_requirement && (
                    <div className="flex justify-between">
                      <span>Height Requirement</span>
                      <span className="font-medium">
                        <MeasurementDisplay value={ride.height_requirement} type="height" /> minimum
                      </span>
                    </div>
                  )}
                  {ride.age_requirement && (
                    <div className="flex justify-between">
                      <span>Age Requirement</span>
                      <span className="font-medium">{ride.age_requirement}+ years</span>
                    </div>
                  )}
                  <div className="flex justify-between">
                    <span>Status</span>
                    <Badge className={getStatusColor(ride.status)}>
                      {ride.status.replace('_', ' ')}
                    </Badge>
                  </div>
                </CardContent>
              </Card>

              {/* Coaster Materials & Propulsion */}
              {ride.category === 'roller_coaster' && (
                (ride.track_material?.length ?? 0) > 0 || 
                (ride.support_material?.length ?? 0) > 0 || 
                (ride.propulsion_method?.length ?? 0) > 0
              ) && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Wrench className="w-5 h-5" />
                      Coaster Construction
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {ride.track_material && ride.track_material.length > 0 && (
                      <div>
                        <div className="text-sm font-medium mb-2">Track Material</div>
                        <div className="flex flex-wrap gap-2">
                          {ride.track_material.map(material => (
                            <Badge key={material} variant="outline">
                              {material.replace('_', ' ').toUpperCase()}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    )}
                    {ride.support_material && ride.support_material.length > 0 && (
                      <div>
                        <div className="text-sm font-medium mb-2">Support Material</div>
                        <div className="flex flex-wrap gap-2">
                          {ride.support_material.map(material => (
                            <Badge key={material} variant="outline">
                              {material.replace('_', ' ').toUpperCase()}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    )}
                    {ride.propulsion_method && ride.propulsion_method.length > 0 && (
                      <div>
                        <div className="text-sm font-medium mb-2">Propulsion Method</div>
                        <div className="flex flex-wrap gap-2">
                          {ride.propulsion_method.map(method => (
                            <Badge key={method} variant="outline">
                              {method.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}

              {/* Water Ride Details */}
              {ride.category === 'water_ride' && (
                ride.water_depth_cm || ride.splash_height_meters || ride.wetness_level || 
                ride.flume_type || ride.boat_capacity
              ) && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Waves className="w-5 h-5" />
                      Water Ride Details
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {ride.water_depth_cm && (
                      <div className="flex justify-between">
                        <span>Water Depth</span>
                        <span className="font-medium">
                          <MeasurementDisplay value={ride.water_depth_cm} type="height" />
                        </span>
                      </div>
                    )}
                    {ride.splash_height_meters && (
                      <div className="flex justify-between">
                        <span>Splash Height</span>
                        <span className="font-medium">
                          <MeasurementDisplay value={ride.splash_height_meters} type="distance" />
                        </span>
                      </div>
                    )}
                    {ride.wetness_level && (
                      <div className="flex justify-between">
                        <span>Wetness Level</span>
                        <Badge variant="outline">
                          {ride.wetness_level.charAt(0).toUpperCase() + ride.wetness_level.slice(1)}
                        </Badge>
                      </div>
                    )}
                    {ride.flume_type && (
                      <div className="flex justify-between">
                        <span>Flume Type</span>
                        <span className="font-medium">
                          {ride.flume_type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
                        </span>
                      </div>
                    )}
                    {ride.boat_capacity && (
                      <div className="flex justify-between">
                        <span>Boat Capacity</span>
                        <span className="font-medium">{ride.boat_capacity} riders</span>
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}

              {/* Dark Ride Details */}
              {ride.category === 'dark_ride' && (
                ride.theme_name || ride.story_description || ride.show_duration_seconds || 
                ride.animatronics_count || ride.projection_type || ride.ride_system || ride.scenes_count
              ) && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Sparkles className="w-5 h-5" />
                      Dark Ride Details
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {ride.theme_name && (
                      <div className="flex justify-between">
                        <span>Theme</span>
                        <span className="font-medium">{ride.theme_name}</span>
                      </div>
                    )}
                    {ride.story_description && (
                      <div>
                        <div className="text-sm font-medium mb-1">Story</div>
                        <p className="text-sm text-muted-foreground">{ride.story_description}</p>
                      </div>
                    )}
                    {ride.show_duration_seconds && (
                      <div className="flex justify-between">
                        <span>Show Duration</span>
                        <span className="font-medium">
                          {Math.floor(ride.show_duration_seconds / 60)}:{(ride.show_duration_seconds % 60).toString().padStart(2, '0')}
                        </span>
                      </div>
                    )}
                    {ride.animatronics_count && (
                      <div className="flex justify-between">
                        <span>Animatronics</span>
                        <span className="font-medium">{ride.animatronics_count}</span>
                      </div>
                    )}
                    {ride.scenes_count && (
                      <div className="flex justify-between">
                        <span>Scenes</span>
                        <span className="font-medium">{ride.scenes_count}</span>
                      </div>
                    )}
                    {ride.projection_type && (
                      <div className="flex justify-between">
                        <span>Projection Type</span>
                        <span className="font-medium">
                          {ride.projection_type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
                        </span>
                      </div>
                    )}
                    {ride.ride_system && (
                      <div className="flex justify-between">
                        <span>Ride System</span>
                        <span className="font-medium">
                          {ride.ride_system.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
                        </span>
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}

              {/* Flat Ride Details */}
              {ride.category === 'flat_ride' && (
                ride.rotation_type || ride.motion_pattern || ride.platform_count || 
                ride.swing_angle_degrees || ride.rotation_speed_rpm || ride.arm_length_meters || 
                ride.max_height_reached_meters
              ) && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Repeat className="w-5 h-5" />
                      Flat Ride Details
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {ride.rotation_type && (
                      <div className="flex justify-between">
                        <span>Rotation Type</span>
                        <span className="font-medium">
                          {ride.rotation_type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
                        </span>
                      </div>
                    )}
                    {ride.motion_pattern && (
                      <div className="flex justify-between">
                        <span>Motion Pattern</span>
                        <span className="font-medium">
                          {ride.motion_pattern.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
                        </span>
                      </div>
                    )}
                    {ride.platform_count && (
                      <div className="flex justify-between">
                        <span>Platforms</span>
                        <span className="font-medium">{ride.platform_count}</span>
                      </div>
                    )}
                    {ride.swing_angle_degrees && (
                      <div className="flex justify-between">
                        <span>Swing Angle</span>
                        <span className="font-medium">{ride.swing_angle_degrees}°</span>
                      </div>
                    )}
                    {ride.rotation_speed_rpm && (
                      <div className="flex justify-between">
                        <span>Rotation Speed</span>
                        <span className="font-medium">{ride.rotation_speed_rpm} RPM</span>
                      </div>
                    )}
                    {ride.arm_length_meters && (
                      <div className="flex justify-between">
                        <span>Arm Length</span>
                        <span className="font-medium">
                          <MeasurementDisplay value={ride.arm_length_meters} type="distance" />
                        </span>
                      </div>
                    )}
                    {ride.max_height_reached_meters && (
                      <div className="flex justify-between">
                        <span>Max Height Reached</span>
                        <span className="font-medium">
                          <MeasurementDisplay value={ride.max_height_reached_meters} type="distance" />
                        </span>
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}

              {/* Kiddie Ride Details */}
              {ride.category === 'kiddie_ride' && (
                ride.min_age || ride.max_age || ride.educational_theme || ride.character_theme
              ) && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Baby className="w-5 h-5" />
                      Kiddie Ride Details
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {(ride.min_age || ride.max_age) && (
                      <div className="flex justify-between">
                        <span>Age Range</span>
                        <span className="font-medium">
                          {ride.min_age && ride.max_age ? `${ride.min_age}-${ride.max_age} years` :
                           ride.min_age ? `${ride.min_age}+ years` :
                           ride.max_age ? `Up to ${ride.max_age} years` : 'N/A'}
                        </span>
                      </div>
                    )}
                    {ride.educational_theme && (
                      <div className="flex justify-between">
                        <span>Educational Theme</span>
                        <span className="font-medium">{ride.educational_theme}</span>
                      </div>
                    )}
                    {ride.character_theme && (
                      <div className="flex justify-between">
                        <span>Character Theme</span>
                        <span className="font-medium">{ride.character_theme}</span>
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}

              {/* Transportation Details */}
              {ride.category === 'transportation' && (
                ride.transport_type || ride.route_length_meters || ride.stations_count || 
                ride.vehicle_capacity || ride.vehicles_count || ride.round_trip_duration_seconds
              ) && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Train className="w-5 h-5" />
                      Transportation Details
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {ride.transport_type && (
                      <div className="flex justify-between">
                        <span>Transport Type</span>
                        <span className="font-medium">
                          {ride.transport_type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
                        </span>
                      </div>
                    )}
                    {ride.route_length_meters && (
                      <div className="flex justify-between">
                        <span>Route Length</span>
                        <span className="font-medium">
                          <MeasurementDisplay value={ride.route_length_meters} type="distance" />
                        </span>
                      </div>
                    )}
                    {ride.stations_count && (
                      <div className="flex justify-between">
                        <span>Stations</span>
                        <span className="font-medium">{ride.stations_count}</span>
                      </div>
                    )}
                    {ride.vehicle_capacity && (
                      <div className="flex justify-between">
                        <span>Vehicle Capacity</span>
                        <span className="font-medium">{ride.vehicle_capacity} passengers</span>
                      </div>
                    )}
                    {ride.vehicles_count && (
                      <div className="flex justify-between">
                        <span>Number of Vehicles</span>
                        <span className="font-medium">{ride.vehicles_count}</span>
                      </div>
                    )}
                    {ride.round_trip_duration_seconds && (
                      <div className="flex justify-between">
                        <span>Round Trip Duration</span>
                        <span className="font-medium">
                          {Math.floor(ride.round_trip_duration_seconds / 60)}:{(ride.round_trip_duration_seconds % 60).toString().padStart(2, '0')}
                        </span>
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}
            </div>
          </TabsContent>

          <TabsContent value="reviews" className="mt-6">
            <ReviewsSection
              entityType="ride"
              entityId={ride.id}
              entityName={ride.name}
              averageRating={ride.average_rating ?? 0}
              reviewCount={ride.review_count ?? 0}
            />
          </TabsContent>

          <TabsContent value="photos" className="mt-6">
            <EntityPhotoGallery
              entityId={ride.id}
              entityType="ride"
              entityName={ride.name}
              parentId={ride.currentParkId}
            />
          </TabsContent>

          <TabsContent value="history" className="mt-6">
            <EntityHistoryTabs
              entityType="ride"
              entityId={ride.id}
              entityName={ride.name}
              currentName={ride.name}
              formerNames={ride.name_history}
            />
          </TabsContent>
        </Tabs>

        {/* Edit Ride Modal */}
        <Dialog open={isEditModalOpen} onOpenChange={setIsEditModalOpen}>
          <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Edit Ride</DialogTitle>
              <DialogDescription>
                {isModerator() 
                  ? "Make changes to this ride. Changes will be applied immediately."
                  : "Submit changes to this ride for review. A moderator will review your submission."}
              </DialogDescription>
            </DialogHeader>
            <Suspense fallback={<AdminFormSkeleton />}>
              {ride && (
                <RideForm
                  initialData={{
                    id: ride.id,
                    name: ride.name,
                    slug: ride.slug,
                    description: ride.description ?? undefined,
                    category: ride.category,
                    ride_sub_type: ride.ride_sub_type ?? undefined,
                    status: ride.status as "operating" | "closed_permanently" | "closed_temporarily" | "under_construction" | "relocated" | "stored" | "demolished",
                    opening_date: ride.opening_date ?? undefined,
                    closing_date: ride.closing_date ?? undefined,
                    height_requirement: ride.height_requirement ?? undefined,
                    age_requirement: ride.age_requirement ?? undefined,
                    capacity_per_hour: ride.capacity_per_hour ?? undefined,
                    duration_seconds: ride.duration_seconds ?? undefined,
                    max_speed_kmh: ride.max_speed_kmh ?? undefined,
                    max_height_meters: ride.max_height_meters ?? undefined,
                    length_meters: ride.length_meters ?? undefined,
                    inversions: ride.inversions ?? undefined,
                    // Coaster fields
                    coaster_type: ride.coaster_type ?? undefined,
                    seating_type: ride.seating_type ?? undefined,
                    intensity_level: ride.intensity_level ?? undefined,
                    track_material: ride.track_material,
                    support_material: ride.support_material,
                    propulsion_method: ride.propulsion_method,
                    drop_height_meters: ride.drop_height_meters ?? undefined,
                    max_g_force: ride.max_g_force ?? undefined,
                    // Water ride fields
                    water_depth_cm: ride.water_depth_cm ?? undefined,
                    splash_height_meters: ride.splash_height_meters ?? undefined,
                    wetness_level: ride.wetness_level as any,
                    flume_type: ride.flume_type ?? undefined,
                    boat_capacity: ride.boat_capacity ?? undefined,
                    // Dark ride fields
                    theme_name: ride.theme_name ?? undefined,
                    story_description: ride.story_description ?? undefined,
                    show_duration_seconds: ride.show_duration_seconds ?? undefined,
                    animatronics_count: ride.animatronics_count ?? undefined,
                    projection_type: ride.projection_type ?? undefined,
                    ride_system: ride.ride_system ?? undefined,
                    scenes_count: ride.scenes_count ?? undefined,
                    // Flat ride fields
                    rotation_type: ride.rotation_type as any,
                    motion_pattern: ride.motion_pattern ?? undefined,
                    platform_count: ride.platform_count ?? undefined,
                    swing_angle_degrees: ride.swing_angle_degrees ?? undefined,
                    rotation_speed_rpm: ride.rotation_speed_rpm ?? undefined,
                    arm_length_meters: ride.arm_length_meters ?? undefined,
                    max_height_reached_meters: ride.max_height_reached_meters ?? undefined,
                    // Kiddie ride fields
                    min_age: ride.min_age ?? undefined,
                    max_age: ride.max_age ?? undefined,
                    educational_theme: ride.educational_theme ?? undefined,
                    character_theme: ride.character_theme ?? undefined,
                    // Transportation fields
                    transport_type: ride.transport_type as any,
                    route_length_meters: ride.route_length_meters ?? undefined,
                    stations_count: ride.stations_count ?? undefined,
                    vehicle_capacity: ride.vehicle_capacity ?? undefined,
                    vehicles_count: ride.vehicles_count ?? undefined,
                    round_trip_duration_seconds: ride.round_trip_duration_seconds ?? undefined,
                    // Common fields
                    manufacturer_id: ride.manufacturer?.id,
                    ride_model_id: ride.ride_model?.id,
                    banner_image_url: ride.banner_image_url ?? undefined,
                    card_image_url: ride.card_image_url ?? undefined
                  }}
                  onSubmit={handleEditSubmit}
                  onCancel={() => setIsEditModalOpen(false)}
                  isEditing={true}
                />
              )}
            </Suspense>
          </DialogContent>
        </Dialog>
      </main>
    </div>
  );
}
