'use client';

import Link from 'next/link';
import { Car } from '@/types';
import { useTranslation } from '@/lib/i18n';
import { useTranslate } from '@/lib/useTranslate';

interface CarCardProps {
  car: Car;
}

export default function CarCard({ car }: CarCardProps) {
  const { t, formatPrice, language } = useTranslation();
  const { translate } = useTranslate();
  const mainImage = car.images?.find((img) => img.is_main) || car.images?.[0];
  const imageUrl = mainImage?.url || '/placeholder-car.jpg';

  const formatMileage = (mileage?: number) => {
    if (!mileage) return '-';
    return new Intl.NumberFormat('en-US').format(mileage) + ' km';
  };

  const price = formatPrice(car.final_price_krw || car.price_krw);

  // Translate car fields
  const carName = translate(car.car_name) || `${translate(car.maker?.name)} ${translate(car.model?.name)}`.trim();
  const fuel = translate(car.fuel);

  return (
    <Link href={`/cars/${car.id}`}>
      <div className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition-shadow duration-300">
        {/* Image */}
        <div className="relative h-48 bg-gray-200">
          {mainImage?.url ? (
            <img
              src={imageUrl}
              alt={carName || 'Car'}
              className="w-full h-full object-cover"
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center text-gray-400">
              No Image
            </div>
          )}
          {/* Status Badge */}
          {car.status !== 'active' && (
            <span className="absolute top-2 right-2 bg-red-500 text-white text-xs px-2 py-1 rounded">
              {car.status}
            </span>
          )}
        </div>

        {/* Info */}
        <div className="p-4">
          <h3 className="text-lg font-semibold text-gray-800 truncate">
            {carName || '-'}
          </h3>

          <div className="mt-2 text-sm text-gray-600 space-y-1">
            <div className="flex justify-between">
              <span>{t.year}</span>
              <span className="font-medium">{car.year || '-'}</span>
            </div>
            <div className="flex justify-between">
              <span>{t.mileage}</span>
              <span className="font-medium">{formatMileage(car.mileage)}</span>
            </div>
            <div className="flex justify-between">
              <span>{t.fuel}</span>
              <span className="font-medium">{fuel || '-'}</span>
            </div>
          </div>

          <div className="mt-4 pt-3 border-t">
            <p className="text-lg font-bold text-primary-600">
              {price.usdt}
            </p>
            {/* Show local currency for all languages */}
            <p className="text-sm text-gray-500">
              ({price.local})
            </p>
          </div>
        </div>
      </div>
    </Link>
  );
}
