'use client';

import { useState } from 'react';

export interface CarSearchItem {
  id: string;
  car_name?: string;
  maker_name?: string;
  model_name?: string;
  year?: number;
  month?: number;
  mileage?: number;
  price?: number;  // For compatibility
  original_price?: number;  // From Carmodoo
  final_price?: number;  // From Carmodoo (calculated with margins)
  fuel?: string;
  transmission?: string;
  color?: string;
  displacement?: number;
  main_image?: string;
  check_num?: string;
}

interface CarSearchTableProps {
  cars: CarSearchItem[];
  selectedCars: Set<string>;
  onSelectCar: (carId: string) => void;
  onSelectAll: () => void;
  loading?: boolean;
  showCheckNum?: boolean;
  emptyMessage?: string;
}

// 차량명 번역 함수
const translateCarName = (koreanName: string | undefined): string => {
  if (!koreanName) return '-';

  const translations: Record<string, string> = {
    '현대': 'Hyundai', '제네시스': 'Genesis', '기아': 'Kia',
    '쉐보레(대우)': 'Chevrolet', '쉐보레': 'Chevrolet',
    '르노(삼성)': 'Renault', 'KG모빌리티(쌍용)': 'KG Mobility',
    '닛산': 'Nissan', '렉서스': 'Lexus', '토요타': 'Toyota', '혼다': 'Honda',
    '쏘렌토': 'Sorento', '스포티지': 'Sportage', '셀토스': 'Seltos',
    '카니발': 'Carnival', '모닝': 'Morning', '레이': 'Ray',
    '아반떼': 'Avante', '쏘나타': 'Sonata', '그랜저': 'Grandeur',
    '투싼': 'Tucson', '싼타페': 'Santa Fe', '팰리세이드': 'Palisade',
    '코나': 'Kona', '스타리아': 'Staria', '캐스퍼': 'Casper',
    'GV70': 'GV70', 'GV80': 'GV80', 'G70': 'G70', 'G80': 'G80', 'G90': 'G90',
    'K5': 'K5', 'K7': 'K7', 'K8': 'K8', 'K9': 'K9',
    '스팅어': 'Stinger', 'EV6': 'EV6', 'EV9': 'EV9',
    '아이오닉': 'Ioniq', '넥쏘': 'Nexo',
  };

  let result = koreanName;
  const sortedKeys = Object.keys(translations).sort((a, b) => b.length - a.length);
  for (const korean of sortedKeys) {
    result = result.replace(new RegExp(korean, 'g'), translations[korean]);
  }
  return result;
};

export default function CarSearchTable({
  cars,
  selectedCars,
  onSelectCar,
  onSelectAll,
  loading = false,
  showCheckNum = true,
  emptyMessage = 'No cars found. Try adjusting your search criteria.',
}: CarSearchTableProps) {
  if (loading) {
    return (
      <div className="flex justify-center py-12">
        <div className="w-8 h-8 border-4 border-primary-600 border-t-transparent rounded-full animate-spin"></div>
      </div>
    );
  }

  if (cars.length === 0) {
    return (
      <div className="text-center py-12 text-gray-500">
        <div className="text-4xl mb-4">🔍</div>
        <p>{emptyMessage}</p>
      </div>
    );
  }

  return (
    <div className="overflow-x-auto">
      <table className="w-full">
        <thead>
          <tr className="border-b border-gray-200 bg-gray-50">
            <th className="py-3 px-2 text-center text-sm font-medium text-gray-600">
              <input
                type="checkbox"
                checked={selectedCars.size === cars.length && cars.length > 0}
                onChange={onSelectAll}
                className="w-5 h-5 rounded border-gray-300 text-primary-600"
              />
            </th>
            <th className="py-3 px-4 text-left text-sm font-medium text-gray-600">Image</th>
            <th className="py-3 px-4 text-left text-sm font-medium text-gray-600">Car Name</th>
            <th className="py-3 px-4 text-left text-sm font-medium text-gray-600">Year</th>
            <th className="py-3 px-4 text-left text-sm font-medium text-gray-600">Mileage</th>
            <th className="py-3 px-4 text-right text-sm font-medium text-gray-600">Price (KRW)</th>
            <th className="py-3 px-4 text-right text-sm font-medium text-gray-600">Price (USD)</th>
            <th className="py-3 px-4 text-left text-sm font-medium text-gray-600">Fuel</th>
            {showCheckNum && (
              <th className="py-3 px-4 text-left text-sm font-medium text-gray-600">Check#</th>
            )}
          </tr>
        </thead>
        <tbody>
          {cars.map((car) => (
            <tr
              key={car.id}
              onClick={() => onSelectCar(car.id)}
              className={`border-b border-gray-100 hover:bg-gray-50 cursor-pointer ${
                selectedCars.has(car.id) ? 'bg-primary-50' : ''
              }`}
            >
              <td className="py-3 px-2 text-center">
                <input
                  type="checkbox"
                  checked={selectedCars.has(car.id)}
                  onChange={() => onSelectCar(car.id)}
                  onClick={(e) => e.stopPropagation()}
                  className="w-5 h-5 rounded border-gray-300 text-primary-600"
                />
              </td>
              <td className="py-3 px-4">
                <div className="w-20 h-14 bg-gray-200 rounded overflow-hidden">
                  {car.main_image ? (
                    <img
                      src={car.main_image}
                      alt={car.car_name || 'Car'}
                      className="w-full h-full object-cover"
                      onError={(e) => {
                        (e.target as HTMLImageElement).style.display = 'none';
                      }}
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-gray-400 text-xs">
                      No Image
                    </div>
                  )}
                </div>
              </td>
              <td className="py-3 px-4">
                <div className="font-medium text-gray-800">{translateCarName(car.car_name)}</div>
                <div className="text-xs text-gray-500">
                  {car.maker_name} {car.model_name}
                </div>
              </td>
              <td className="py-3 px-4 text-gray-600">
                {car.year}년{car.month ? ` ${car.month}월` : ''}
              </td>
              <td className="py-3 px-4 text-gray-600">
                {car.mileage?.toLocaleString()} km
              </td>
              <td className="py-3 px-4 text-right text-gray-600">
                {(() => {
                  const priceKrw = car.original_price || car.price || 0;
                  return priceKrw > 0 ? `₩${priceKrw.toLocaleString()}` : '-';
                })()}
              </td>
              <td className="py-3 px-4 text-right font-semibold text-primary-600">
                {(() => {
                  const finalPrice = car.final_price || car.original_price || car.price || 0;
                  return finalPrice > 0 ? `$${Math.round(finalPrice / 1400).toLocaleString()}` : '-';
                })()}
              </td>
              <td className="py-3 px-4 text-gray-600">{car.fuel || '-'}</td>
              {showCheckNum && (
                <td className="py-3 px-4 text-gray-600">
                  {car.check_num ? (
                    <span className="text-green-600 text-xs font-medium">
                      ✓ {car.check_num.slice(-4)}
                    </span>
                  ) : (
                    <span className="text-gray-400 text-xs">-</span>
                  )}
                </td>
              )}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
