import { useState } from 'react';
import { Link } from 'react-router-dom';
import { Heart, MapPin, Star } from 'lucide-react';
import { Badge } from '../ui/Badge';
import { api } from '../../api/client';
import { useAuth } from '../../context/AuthContext';
import type { RentalListing } from '../../types/rental';
import { formatCurrency } from '../../utils/format';

interface RentalCardProps {
  rental: RentalListing;
}

const categoryEmojis: Record<string, string> = {
  APARTMENT: '\u{1F3E0}',
  HOUSE: '\u{1F3E1}',
  CAR: '\u{1F697}',
  MOTORCYCLE: '\u{1F3CD}',
  BICYCLE: '\u{1F6B2}',
  EBIKE: '\u26A1',
  OTHER: '\u{1F4E6}',
};

export function RentalCard({ rental }: RentalCardProps) {
  const { isAuthenticated } = useAuth();
  const [isFav, setIsFav] = useState(rental.isFavorited ?? false);
  const [toggling, setToggling] = useState(false);

  const emoji = categoryEmojis[rental.category] ?? '\u{1F4E6}';

  const handleFavorite = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (!isAuthenticated || toggling) return;
    setToggling(true);
    try {
      const res = await api.post<{ isFavorited: boolean }>(`/rentals/${rental.id}/favorite`);
      setIsFav(res.isFavorited);
    } catch {
      // silently ignore
    }
    setToggling(false);
  };

  const hasImage = rental.images?.[0]?.url;

  return (
    <Link to={`/rentals/${rental.id}`} className="group block">
      <div className="bg-white rounded-2xl border border-gray-100 overflow-hidden shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200">
        {/* Image */}
        <div className="relative aspect-square bg-gray-100">
          {hasImage ? (
            <img src={rental.images[0].url} alt={rental.title} className="w-full h-full object-cover" />
          ) : (
            <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-primary-50 to-pink-50">
              <span className="text-5xl">{emoji}</span>
            </div>
          )}
          {isAuthenticated && (
            <button
              onClick={handleFavorite}
              className="absolute top-2 right-2 p-1.5 bg-white/80 backdrop-blur rounded-full hover:bg-white transition-colors cursor-pointer"
            >
              <Heart className={`w-4 h-4 ${isFav ? 'fill-pink-500 text-pink-500' : 'text-gray-400'}`} />
            </button>
          )}
        </div>

        {/* Content */}
        <div className="p-3">
          <h3 className="text-sm font-semibold text-gray-900 truncate group-hover:text-primary-600 transition-colors">
            {rental.title}
          </h3>

          <div className="flex items-baseline gap-1.5 mt-1">
            {rental.dailyPrice != null && (
              <p className="text-lg font-bold text-primary-600">
                {formatCurrency(rental.dailyPrice)}
                <span className="text-xs font-normal text-gray-400">/day</span>
              </p>
            )}
            {rental.monthlyPrice != null && (
              <p className={`font-bold text-primary-600 ${rental.dailyPrice != null ? 'text-sm' : 'text-lg'}`}>
                {rental.dailyPrice != null && <span className="text-gray-300 font-normal mx-1">&middot;</span>}
                {formatCurrency(rental.monthlyPrice)}
                <span className="text-xs font-normal text-gray-400">/mo</span>
              </p>
            )}
          </div>

          <div className="flex items-center justify-between mt-2">
            <Badge variant="info">{rental.category.replace('_', ' ')}</Badge>
            <span className="flex items-center gap-1 text-xs text-gray-400">
              <MapPin className="w-3 h-3" />
              {rental.location}
            </span>
          </div>

          {rental.avgRating != null && rental._count?.reviews != null && rental._count.reviews > 0 && (
            <div className="flex items-center gap-1 mt-2 text-xs text-gray-500">
              <Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" />
              <span className="font-medium text-gray-700">{rental.avgRating.toFixed(1)}</span>
              <span>({rental._count.reviews})</span>
            </div>
          )}
        </div>
      </div>
    </Link>
  );
}
