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 { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Separator } from '@/components/ui/separator';
import { MapPin, Star, Clock, Phone, Globe, Calendar, ArrowLeft, Users, Zap, Camera, Castle, FerrisWheel, Waves, Tent, Theater, Train } from 'lucide-react';
import { ReviewsSection } from '@/components/reviews/ReviewsSection';
import { MeasurementDisplay } from '@/components/ui/measurement-display';
import { Park, Ride } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';
export default function ParkDetail() {
  const {
    slug
  } = useParams<{
    slug: string;
  }>();
  const navigate = useNavigate();
  const [park, setPark] = useState<Park | null>(null);
  const [rides, setRides] = useState<Ride[]>([]);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    if (slug) {
      fetchParkData();
    }
  }, [slug]);
  const fetchParkData = async () => {
    try {
      // Fetch park details
      const {
        data: parkData
      } = await supabase.from('parks').select(`
          *, 
          location:locations(*), 
          operator:companies!parks_operator_id_fkey(*),
          property_owner:companies!parks_property_owner_id_fkey(*)
        `).eq('slug', slug).maybeSingle();
      if (parkData) {
        setPark(parkData);

        // Fetch park rides
        const {
          data: ridesData
        } = await supabase.from('rides').select(`*`).eq('park_id', parkData.id).order('name');
        setRides(ridesData || []);
      }
    } catch (error) {
      console.error('Error fetching park data:', error);
    } finally {
      setLoading(false);
    }
  };
  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 getParkTypeIcon = (type: string) => {
    switch (type) {
      case 'theme_park':
        return <Castle className="w-20 h-20" />;
      case 'amusement_park':
        return <FerrisWheel className="w-20 h-20" />;
      case 'water_park':
        return <Waves className="w-20 h-20" />;
      case 'family_entertainment':
        return <Tent className="w-20 h-20" />;
      default:
        return <FerrisWheel className="w-20 h-20" />;
    }
  };
  const formatParkType = (type: string) => {
    return type.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
  };
  const getRideIcon = (category: string) => {
    switch (category) {
      case 'roller_coaster':
        return <FerrisWheel className="w-5 h-5" />;
      case 'water_ride':
        return <Waves className="w-5 h-5" />;
      case 'dark_ride':
        return <Theater className="w-5 h-5" />;
      case 'flat_ride':
        return <FerrisWheel className="w-5 h-5" />;
      case 'kiddie_ride':
        return <FerrisWheel className="w-5 h-5" />;
      case 'transportation':
        return <Train className="w-5 h-5" />;
      default:
        return <FerrisWheel className="w-5 h-5" />;
    }
  };
  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 (!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">Park Not Found</h1>
            <p className="text-muted-foreground mb-6">
              The park you're looking for doesn't exist or has been removed.
            </p>
            <Button onClick={() => navigate('/parks')}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              Back to Parks
            </Button>
          </div>
        </div>
      </div>;
  }
  return <div className="min-h-screen bg-background">
      <Header />
      
      <main className="container mx-auto px-4 py-8">
        {/* Back Button */}
        <Button variant="ghost" onClick={() => navigate('/parks')} className="mb-6">
          <ArrowLeft className="w-4 h-4 mr-2" />
          Back to Parks
        </Button>

        {/* 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">
            {park.banner_image_url ? <img src={park.banner_image_url} alt={park.name} className="w-full h-full object-cover" /> : <div className="flex items-center justify-center h-full">
                <div className="opacity-50">
                  {getParkTypeIcon(park.park_type)}
                </div>
              </div>}
            <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />
            
            {/* Park 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(park.status)} border`}>
                      {park.status.replace('_', ' ').toUpperCase()}
                    </Badge>
                    <Badge variant="outline" className="bg-black/20 text-white border-white/20">
                      {formatParkType(park.park_type)}
                    </Badge>
                  </div>
                  <h1 className="text-4xl md:text-6xl font-bold text-white mb-2">
                    {park.name}
                  </h1>
                  {park.location && <div className="flex items-center text-white/90 text-lg">
                      <MapPin className="w-5 h-5 mr-2" />
                      {park.location.city && `${park.location.city}, `}{park.location.country}
                    </div>}
                </div>
                
                {park.average_rating > 0 && <div className="bg-black/20 backdrop-blur-sm rounded-lg p-4 text-center">
                    <div className="flex items-center gap-2 text-white mb-1">
                      <Star className="w-5 h-5 fill-yellow-400 text-yellow-400" />
                      <span className="text-2xl font-bold">{park.average_rating.toFixed(1)}</span>
                    </div>
                    <div className="text-white/70 text-sm">
                      {park.review_count} reviews
                    </div>
                  </div>}
              </div>
            </div>
          </div>
        </div>

        {/* Quick Stats */}
        <div className="relative mb-12">
          {/* Background decorative elements */}
          <div className="absolute inset-0 bg-gradient-to-r from-primary/5 via-secondary/5 to-accent/5 rounded-3xl blur-xl"></div>
          
          <div className="relative grid grid-cols-2 md:grid-cols-4 gap-4 p-4 bg-gradient-to-br from-background/80 via-card/90 to-background/80 backdrop-blur-sm rounded-xl border border-border/50 shadow-md">
            {/* Total Rides */}
            <div className="group relative overflow-hidden">
              <Card className="h-full border-0 bg-gradient-to-br from-primary/10 via-primary/5 to-transparent hover:shadow-lg hover:shadow-primary/15 transition-all duration-300 hover:scale-[1.02]">
                <CardContent className="p-4 text-center relative">
                  <div className="absolute top-1 right-1 opacity-20 group-hover:opacity-40 transition-opacity">
                    <FerrisWheel className="w-6 h-6 text-primary" />
                  </div>
                  <div className="text-2xl font-bold text-primary mb-1 group-hover:scale-105 transition-transform">
                    {park.ride_count}
                  </div>
                  <div className="text-xs font-medium text-muted-foreground">Total Rides</div>
                </CardContent>
              </Card>
            </div>

            {/* Roller Coasters */}
            <div className="group relative overflow-hidden">
              <Card className="h-full border-0 bg-gradient-to-br from-accent/10 via-accent/5 to-transparent hover:shadow-lg hover:shadow-accent/15 transition-all duration-300 hover:scale-[1.02]">
                <CardContent className="p-4 text-center relative">
                  <div className="absolute top-1 right-1 opacity-20 group-hover:opacity-40 transition-opacity">
                    <Zap className="w-6 h-6 text-accent" />
                  </div>
                  <div className="text-2xl font-bold text-accent mb-1 group-hover:scale-105 transition-transform">
                    {park.coaster_count}
                  </div>
                  <div className="text-xs font-medium text-muted-foreground">Roller Coasters</div>
                </CardContent>
              </Card>
            </div>

            {/* Reviews */}
            <div className="group relative overflow-hidden">
              <Card className="h-full border-0 bg-gradient-to-br from-secondary/10 via-secondary/5 to-transparent hover:shadow-lg hover:shadow-secondary/15 transition-all duration-300 hover:scale-[1.02]">
                <CardContent className="p-4 text-center relative">
                  <div className="absolute top-1 right-1 opacity-20 group-hover:opacity-40 transition-opacity">
                    <Star className="w-6 h-6 text-secondary" />
                  </div>
                  <div className="text-2xl font-bold text-secondary mb-1 group-hover:scale-105 transition-transform">
                    {park.review_count}
                  </div>
                  <div className="text-xs font-medium text-muted-foreground">Reviews</div>
                  {park.average_rating > 0 && <div className="flex items-center justify-center gap-1 mt-1">
                      <Star className="w-3 h-3 fill-yellow-400 text-yellow-400" />
                      <span className="text-xs font-medium text-yellow-500">
                        {park.average_rating.toFixed(1)}
                      </span>
                    </div>}
                </CardContent>
              </Card>
            </div>

            {/* Operating Status */}
            <div className="group relative overflow-hidden">
              <Card className="h-full border-0 bg-gradient-to-br from-muted/20 via-muted/10 to-transparent hover:shadow-lg hover:shadow-muted/15 transition-all duration-300 hover:scale-[1.02]">
                <CardContent className="p-4 text-center relative">
                  <div className="flex items-center justify-center mb-2 group-hover:scale-105 transition-transform">
                    <div className="p-2 rounded-full bg-gradient-to-br from-primary/20 to-accent/20">
                      {park.opening_date ? <Calendar className="w-5 h-5" /> : <Clock className="w-5 h-5" />}
                    </div>
                  </div>
                  <div className="text-xs font-medium text-foreground">
                    {park.opening_date ? `Opened ${new Date(park.opening_date).getFullYear()}` : 'Opening Soon'}
                  </div>
                  
                </CardContent>
              </Card>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <Tabs defaultValue="overview" className="w-full">
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="overview">Overview</TabsTrigger>
            <TabsTrigger value="rides">Rides ({rides.length})</TabsTrigger>
            <TabsTrigger value="reviews">Reviews</TabsTrigger>
            <TabsTrigger value="photos">Photos</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 */}
                {park.description && <Card>
                    <CardHeader>
                      <CardTitle>About {park.name}</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-muted-foreground leading-relaxed">
                        {park.description}
                      </p>
                    </CardContent>
                  </Card>}

                {/* Top Rides Preview */}
                <Card>
                  <CardHeader>
                    <CardTitle>Featured Rides</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="grid md:grid-cols-2 gap-4">
                      {rides.slice(0, 4).map(ride => <div key={ride.id} className="flex items-center gap-3 p-3 border rounded-lg hover:bg-muted/50 cursor-pointer transition-colors" onClick={() => navigate(`/parks/${park.slug}/rides/${ride.slug}`)}>
                          <div className="flex items-center">{getRideIcon(ride.category)}</div>
                          <div className="flex-1">
                            <h4 className="font-medium">{ride.name}</h4>
                            <p className="text-sm text-muted-foreground">
                              {ride.category.replace('_', ' ')}
                            </p>
                          </div>
                          {ride.average_rating > 0 && <div className="flex items-center gap-1">
                              <Star className="w-3 h-3 fill-yellow-400 text-yellow-400" />
                              <span className="text-sm">{ride.average_rating.toFixed(1)}</span>
                            </div>}
                        </div>)}
                    </div>
                  </CardContent>
                </Card>
              </div>

              <div className="space-y-6">
                {/* Park Information */}
                <Card>
                  <CardHeader>
                    <CardTitle>Park Information</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {park.opening_date && <div className="flex items-center gap-3">
                        <Calendar className="w-4 h-4 text-muted-foreground" />
                        <div>
                          <div className="font-medium">Opened</div>
                          <div className="text-sm text-muted-foreground">
                            {new Date(park.opening_date).getFullYear()}
                          </div>
                        </div>
                      </div>}

                    {park.operator && <div className="flex items-center gap-3">
                        <Users className="w-4 h-4 text-muted-foreground" />
                        <div>
                          <div className="font-medium">Operator</div>
                          <div className="text-sm text-muted-foreground">
                            {park.operator.name}
                          </div>
                        </div>
                      </div>}

                    {park.website_url && <div className="flex items-center gap-3">
                        <Globe className="w-4 h-4 text-muted-foreground" />
                        <div>
                          <div className="font-medium">Website</div>
                          <a href={park.website_url} target="_blank" rel="noopener noreferrer" className="text-sm text-primary hover:underline">
                            Visit Website
                          </a>
                        </div>
                      </div>}

                    {park.phone && <div className="flex items-center gap-3">
                        <Phone className="w-4 h-4 text-muted-foreground" />
                        <div>
                          <div className="font-medium">Phone</div>
                          <div className="text-sm text-muted-foreground">
                            {park.phone}
                          </div>
                        </div>
                      </div>}

                    <Separator />

                    <div className="space-y-2">
                      <div className="font-medium">Location</div>
                      {park.location && <div className="text-sm text-muted-foreground space-y-1">
                          {park.location.city && <div>{park.location.city}</div>}
                          {park.location.state_province && <div>{park.location.state_province}</div>}
                          <div>{park.location.country}</div>
                        </div>}
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          </TabsContent>

          <TabsContent value="rides" className="mt-6">
            <div className="grid md:grid-cols-3 lg:grid-cols-4 gap-4">
              {rides.map(ride => (
                <Card 
                  key={ride.id} 
                  className="group overflow-hidden hover:shadow-xl transition-all duration-300 cursor-pointer border-0 bg-gradient-to-br from-card via-card/95 to-card/90 backdrop-blur-sm"
                  onClick={() => navigate(`/parks/${park.slug}/rides/${ride.slug}`)}
                >
                  <div className="aspect-[3/2] bg-gradient-to-br from-primary/20 via-secondary/15 to-accent/10 relative overflow-hidden">
                    {ride.image_url ? (
                      <img 
                        src={ride.image_url} 
                        alt={ride.name}
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                      />
                    ) : (
                      <div className="flex items-center justify-center h-full">
                        <div className="opacity-40 group-hover:opacity-60 transition-opacity">
                          {getRideIcon(ride.category)}
                        </div>
                      </div>
                    )}
                    
                    {/* Status Badge */}
                    <div className="absolute top-3 right-3">
                      <Badge 
                        variant="secondary" 
                        className={`text-xs font-medium ${
                          ride.status === 'operating' 
                            ? 'bg-green-500/20 text-green-400 border-green-500/30' 
                            : ride.status === 'closed' 
                            ? 'bg-red-500/20 text-red-400 border-red-500/30'
                            : 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30'
                        }`}
                      >
                        {ride.status}
                      </Badge>
                    </div>

                    {/* Rating */}
                    {ride.average_rating > 0 && (
                      <div className="absolute bottom-3 right-3 bg-black/50 backdrop-blur-sm rounded-lg px-2 py-1">
                        <div className="flex items-center gap-1">
                          <Star className="w-3 h-3 fill-yellow-400 text-yellow-400" />
                          <span className="text-white text-xs font-medium">
                            {ride.average_rating.toFixed(1)}
                          </span>
                        </div>
                      </div>
                    )}
                  </div>

                  <CardContent className="p-3">
                    <div className="space-y-2">
                      {/* Title and Category */}
                      <div>
                        <h3 className="font-semibold text-lg group-hover:text-primary transition-colors line-clamp-1">
                          {ride.name}
                        </h3>
                        <div className="flex items-center gap-2 mt-1">
                          <div className="opacity-60">
                            {getRideIcon(ride.category)}
                          </div>
                          <p className="text-sm text-muted-foreground capitalize">
                            {ride.category.replace('_', ' ')}
                          </p>
                        </div>
                      </div>

                      {/* Description */}
                      {ride.description && (
                        <p className="text-sm text-muted-foreground line-clamp-2 leading-relaxed">
                          {ride.description}
                        </p>
                      )}

                      {/* Stats */}
                      <div className="flex items-center gap-2 flex-wrap">
                        {ride.max_speed_kmh && (
                          <span className="bg-primary/10 text-primary px-2 py-1 rounded-md text-xs font-medium">
                            <MeasurementDisplay value={ride.max_speed_kmh} type="speed" />
                          </span>
                        )}
                        {ride.max_height_meters && (
                          <span className="bg-accent/10 text-accent px-2 py-1 rounded-md text-xs font-medium">
                            <MeasurementDisplay value={ride.max_height_meters} type="distance" />
                          </span>
                        )}
                        {ride.inversions > 0 && (
                          <span className="bg-secondary/10 text-secondary px-2 py-1 rounded-md text-xs font-medium">
                            {ride.inversions} inversions
                          </span>
                        )}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </TabsContent>

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

          <TabsContent value="photos" className="mt-6">
            <div className="text-center py-12">
              <Camera className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
              <h3 className="text-xl font-semibold mb-2">Photo Gallery Coming Soon</h3>
              <p className="text-muted-foreground">
                Photo galleries and media uploads will be available soon
              </p>
            </div>
          </TabsContent>
        </Tabs>
      </main>
    </div>;
}