"use client";

import { memo } from "react";
import Link from "next/link";
import Image from "next/image";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Clock, Star, Users } from "lucide-react";
import { useS3Image } from "@/hooks/use-s3-image";

interface TourCardProps {
  id: string;
  title: string;
  slug: string;
  description: string;
  city: string;
  durationMin: number | null;
  priceCents: number | null;
  tags: string[];
  avgRating: number | null;
  reviewCount?: number;
  imageUrl?: string | null;
  guideName: string;
  guideId?: string;
  // Legacy support
  tour?: {
    id: string;
    title: string;
    slug: string;
    description: string;
    city: string;
    durationMin: number | null;
    priceCents: number | null;
    tags: string[];
    avgRating: number | null;
    createdBy: {
      id?: string;
      name: string | null;
    };
  };
}

const TourCard = memo(function TourCard(props: TourCardProps) {
  // Support both new props and legacy tour object
  const {
    id = props.tour?.id,
    title = props.tour?.title,
    slug = props.tour?.slug,
    description = props.tour?.description,
    city = props.tour?.city,
    durationMin = props.tour?.durationMin,
    priceCents = props.tour?.priceCents,
    tags = props.tour?.tags || [],
    avgRating = props.tour?.avgRating,
    reviewCount = 0,
    imageUrl,
    guideName = props.tour?.createdBy.name || "Guide",
    guideId = props.tour?.createdBy.id,
  } = props;

  // Get signed URL for S3 images
  const displayImageUrl = useS3Image(imageUrl);

  const formatPrice = (cents: number | null) => {
    if (!cents) return "Free";
    return `CHF ${(cents / 100).toFixed(0)}`;
  };

  const formatDuration = (minutes: number | null) => {
    if (!minutes) return null;
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    if (hours === 0) return `${mins}min`;
    if (mins === 0) return `${hours}h`;
    return `${hours}h ${mins}min`;
  };

  if (!id || !title || !slug) {
    return null;
  }

  return (
    <Card className="group hover:shadow-lg transition-all duration-300 overflow-hidden">
      <div className="relative h-48 bg-linear-to-br from-blue-100 to-indigo-100 overflow-hidden">
        {displayImageUrl ? (
          <Image
            src={displayImageUrl}
            alt={title}
            fill
            sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
            className="object-cover group-hover:scale-105 transition-transform duration-300"
            loading="lazy"
            quality={95}
          />
        ) : (
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="text-6xl opacity-20">🏛️</div>
          </div>
        )}
        <div className="absolute top-3 right-3 z-10">
          <Badge variant="secondary" className="bg-white/90 backdrop-blur-sm">
            {city}
          </Badge>
        </div>
        {avgRating && (
          <div className="absolute top-3 left-3 z-10">
            <Badge className="bg-white/90 backdrop-blur-sm text-yellow-600 border-0">
              <Star className="h-3 w-3 mr-1 fill-yellow-600" />
              {avgRating.toFixed(1)}
              {reviewCount > 0 && (
                <span className="ml-1 text-xs">({reviewCount})</span>
              )}
            </Badge>
          </div>
        )}
      </div>

      <CardContent className="p-4 space-y-3">
        <div>
          <h3 className="font-semibold text-lg line-clamp-1 group-hover:text-blue-600 transition-colors">
            {title}
          </h3>
          <p className="text-sm text-gray-600 line-clamp-2 mt-1">
            {description}
          </p>
        </div>

        <div className="flex items-center gap-2 text-sm text-gray-500">
          <Users className="h-4 w-4" />
          {guideId ? (
            <Link href={`/users/${guideId}`} className="hover:text-blue-600 hover:underline">
              by {guideName}
            </Link>
          ) : (
            <span>by {guideName}</span>
          )}
        </div>

        <div className="flex flex-wrap gap-2">
          {tags.slice(0, 3).map((tag) => (
            <Badge key={tag} variant="outline" className="text-xs">
              {tag}
            </Badge>
          ))}
        </div>

        <div className="flex items-center justify-between pt-2 border-t">
          <div className="space-y-1">
            <div className="flex items-center gap-2 text-sm text-gray-600">
              {durationMin && (
                <>
                  <Clock className="h-4 w-4" />
                  <span>{formatDuration(durationMin)}</span>
                </>
              )}
            </div>
            <div className="text-lg font-bold text-gray-900">
              {formatPrice(priceCents ?? null)} 
              <span className="text-sm text-gray-500 font-normal">
                {" "}
                / person
              </span>
            </div>
          </div>

          <Link href={`/tours/${slug}`}>
            <Button size="sm" className="group-hover:shadow-md transition-shadow">
              View Tour
            </Button>
          </Link>
        </div>
      </CardContent>
    </Card>
  );
});

export { TourCard };
