import React from "react";
import { Link, useNavigate } from "react-router-dom";
import { Clock, ArrowRight } from "lucide-react";
import { Button } from "../ui/button";
import { Badge } from "../ui/badge";

const ServiceCard = ({ service }) => {
  const navigate = useNavigate();

  const handleCardClick = () => {
    navigate(`/services/${service.id}`);
  };

  // Get the primary image URL
  const getImageUrl = () => {
    if (service.images && service.images.length > 0) {
      const primaryImage =
        service.images.find((img) => img.is_primary) || service.images[0];
      const url = primaryImage.url || primaryImage.image_url || primaryImage;
      return url.startsWith("/uploads")
        ? `${process.env.REACT_APP_BACKEND_URL}${url}`
        : url;
    }
    return service.image_url;
  };

  return (
    <div
      className="group rounded-xl border border-border bg-card p-6 hover:shadow-lg transition-all duration-300 hover-lift cursor-pointer"
      data-testid={`service-card-${service.id}`}
      onClick={handleCardClick}
    >
      {/* Image */}
      <div className="relative aspect-video rounded-lg overflow-hidden mb-4 bg-muted">
        <img
          src={getImageUrl()}
          alt={service.name}
          className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
          loading="lazy"
        />
        <Badge className="absolute top-3 left-3 capitalize">
          {service.category}
        </Badge>
      </div>

      {/* Content */}
      <div className="space-y-3">
        <h3 className="font-semibold text-lg font-['Outfit'] group-hover:text-primary transition-colors">
          {service.name}
        </h3>

        <div
          className="text-sm text-muted-foreground line-clamp-2 prose prose-sm max-w-none"
          dangerouslySetInnerHTML={{ __html: service.description }}
        />

        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <Clock className="h-4 w-4" />
          <span>{service.duration}</span>
        </div>

        <div className="flex items-center justify-between pt-3 border-t border-border">
          <div>
            <span className="text-xs text-muted-foreground">
              {service.price > 0 ? "Starting from" : "Price"}
            </span>
            <p className="text-xl font-bold font-['Outfit']">
              {service.price > 0
                ? `$${service.price.toFixed(2)}`
                : "Contact for quote"}
            </p>
          </div>
          <Button
            className="rounded-full gap-2 btn-press"
            data-testid={`book-service-${service.id}`}
            onClick={(e) => {
              e.stopPropagation();
              navigate(`/services/${service.id}`);
            }}
          >
            Book Now
            <ArrowRight className="h-4 w-4" />
          </Button>
        </div>
      </div>
    </div>
  );
};

export default React.memo(ServiceCard);
