import { useNavigate } from 'react-router-dom';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Star, MapPin, Clock, Zap, FerrisWheel, Waves, Theater, Train, ArrowUp, CheckCircle, Calendar, Hammer, XCircle } from 'lucide-react';
import { MeasurementDisplay } from '@/components/ui/measurement-display';
import { Ride } from '@/types/database';
import { getCloudflareImageUrl } from '@/lib/cloudflareImageUtils';

interface RideCardProps {
  ride: Ride;
  showParkName?: boolean;
  className?: string;
  parkSlug?: string;
}

export function RideCard({ ride, showParkName = true, className, parkSlug }: RideCardProps) {
  const navigate = useNavigate();

  const handleRideClick = () => {
    const slug = parkSlug || ride.park?.slug;
    navigate(`/parks/${slug}/rides/${ride.slug}`);
  };

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

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

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'operating': return <CheckCircle className="w-3 h-3" />;
      case 'seasonal': return <Calendar className="w-3 h-3" />;
      case 'under_construction': return <Hammer className="w-3 h-3" />;
      default: return <XCircle className="w-3 h-3" />;
    }
  };

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

  return (
    <Card 
      className={`group overflow-hidden border-border/50 bg-gradient-to-br from-card via-card to-card/80 hover:shadow-2xl hover:shadow-primary/20 hover:border-primary/30 transition-all duration-300 cursor-pointer hover:scale-[1.02] relative before:absolute before:inset-0 before:rounded-lg before:p-[1px] before:bg-gradient-to-br before:from-primary/20 before:via-transparent before:to-accent/20 before:-z-10 before:opacity-0 hover:before:opacity-100 before:transition-opacity before:duration-300 ${className}`}
      onClick={handleRideClick}
    >
      <div className="relative overflow-hidden">
        {/* Image/Icon Section */}
        <div className="aspect-[3/2] bg-gradient-to-br from-primary/20 via-secondary/20 to-accent/20 flex items-center justify-center relative">
          {(ride.card_image_url || ride.card_image_id || ride.image_url) ? (
            <img 
              src={ride.card_image_url || getCloudflareImageUrl(ride.card_image_id || '', 'card') || ride.image_url || ''}
              srcSet={ride.card_image_id ? `
                ${getCloudflareImageUrl(ride.card_image_id, 'cardthumb')} 600w,
                ${getCloudflareImageUrl(ride.card_image_id, 'card')} 1200w
              ` : undefined}
              sizes="(max-width: 640px) 600px, 1200px"
              alt={ride.name}
              className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
              loading="lazy"
            />
          ) : (
            <div className="flex items-center justify-center w-20 h-20">
              <div className="relative">
                <div className="absolute inset-0 rounded-full bg-primary/20 blur-xl animate-pulse" />
                <div className="relative w-12 h-12 rounded-full bg-gradient-to-br from-primary/30 to-secondary/30 flex items-center justify-center border border-primary/20">
                  {getRideIcon(ride.category)}
                </div>
              </div>
            </div>
          )}
          
          {/* Gradient Overlay */}
          <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent opacity-80 group-hover:opacity-60 transition-opacity duration-300" />
          
          {/* Status Badge */}
          <Badge 
            className={`absolute top-3 right-3 ${getStatusColor(ride.status)} backdrop-blur-sm border shadow-lg font-medium text-xs px-2.5 py-1 inline-flex items-center gap-1.5`}
          >
            {getStatusIcon(ride.status)}
            <span>{ride.status.replace('_', ' ').toUpperCase()}</span>
          </Badge>
        </div>

        <CardContent className="p-2.5 space-y-1.5 border-t border-border/30">
          {/* Header */}
          <div className="space-y-0.5 min-w-0">
            <h3 className="font-bold text-base group-hover:text-primary transition-colors line-clamp-2 break-words group-hover:drop-shadow-[0_0_8px_rgba(var(--primary),0.5)] transition-all duration-300">
              {ride.name}
            </h3>
            
            {showParkName && ride.park?.name && (
              <Badge className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-background/80 backdrop-blur-md border-border/50 text-foreground shadow-lg shadow-primary/10 hover:shadow-xl hover:shadow-primary/20 hover:border-primary/50 transition-all duration-300 group/badge max-w-[calc(100%-1rem)]">
                <div className="w-4 h-4 rounded-full bg-gradient-to-br from-primary to-primary/50 flex items-center justify-center shadow-sm group-hover/badge:scale-110 transition-transform flex-shrink-0">
                  <MapPin className="w-2.5 h-2.5 text-primary-foreground" />
                </div>
                <span className="font-medium truncate text-xs min-w-0">
                  {ride.park.name}
                </span>
              </Badge>
            )}
          </div>

          {/* Stats & Rating */}
          <div className="flex flex-col gap-1.5">
            {/* Stats Row */}
            {(Number(ride.max_speed_kmh || 0) > 0 || Number(ride.max_height_meters || 0) > 0 || Number(ride.duration_seconds || 0) > 0) && (
              <div className="flex items-center gap-3 flex-wrap text-sm">
                {Number(ride.max_speed_kmh || 0) > 0 && (
                  <div className="flex items-center gap-1 min-w-0">
                    <Zap className="w-4 h-4 text-primary/70 flex-shrink-0" />
                    <span className="font-medium whitespace-nowrap">
                      <MeasurementDisplay value={ride.max_speed_kmh || 0} type="speed" />
                    </span>
                  </div>
                )}
                {Number(ride.max_height_meters || 0) > 0 && (
                  <div className="flex items-center gap-1 min-w-0">
                    <ArrowUp className="w-4 h-4 text-accent/70 flex-shrink-0" />
                    <span className="font-medium whitespace-nowrap">
                      <MeasurementDisplay value={ride.max_height_meters || 0} type="distance" />
                    </span>
                  </div>
                )}
                {Number(ride.duration_seconds || 0) > 0 && (
                  <div className="flex items-center gap-1 min-w-0">
                    <Clock className="w-4 h-4 text-secondary/70 flex-shrink-0" />
                    <span className="font-medium whitespace-nowrap">
                      {Math.floor((ride.duration_seconds || 0) / 60)}<span className="text-muted-foreground text-xs ml-0.5">min</span>
                    </span>
                  </div>
                )}
              </div>
            )}
            
            {/* Rating */}
            {(ride.average_rating != null && ride.average_rating > 0) && (
              <div className="inline-flex items-center gap-1 text-sm">
                <Star className="w-4 h-4 fill-yellow-500 text-yellow-500" />
                <span className="font-semibold text-foreground">{ride.average_rating.toFixed(1)}</span>
                {(ride.review_count != null && ride.review_count > 0) && (
                  <span className="text-muted-foreground">({ride.review_count})</span>
                )}
              </div>
            )}
          </div>
        </CardContent>
      </div>
    </Card>
  );
}