'use client';
import { useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { motion } from 'framer-motion';
import { ArrowLeft, Calendar, Gauge, Fuel, Cog, Tag, Eye, Phone, MessageCircle, ChevronLeft, ChevronRight } from 'lucide-react';
import { VehicleCard } from '@/components/public/vehicle-card';
import { useLanguage } from '@/lib/i18n/language-context';

export function VehicleDetailClient({ vehicle = {} as any, relatedVehicles = [] }: any) {
  const images = vehicle?.images ?? [];
  const [currentImage, setCurrentImage] = useState(0);
  const isSold = vehicle?.status === 'SOLD';
  const { t, locale } = useLanguage();
  const categoryName = (locale === 'en' && vehicle?.category?.nameEn) ? vehicle.category.nameEn : (vehicle?.category?.name ?? t.common.equipment);

  const currentImgUrl = images?.[currentImage]?.url ?? '/images/cat-trucks.jpg';

  const specs = [
    { icon: Calendar, label: t.vehicleDetail.year, value: vehicle?.year },
    { icon: Gauge, label: t.vehicleDetail.mileage, value: vehicle?.mileage != null ? `${(vehicle.mileage ?? 0)?.toLocaleString()} mi` : null },
    { icon: Fuel, label: t.vehicleDetail.fuel, value: vehicle?.fuelType },
    { icon: Cog, label: t.vehicleDetail.transmission, value: vehicle?.transmission },
    { label: t.vehicleDetail.engine, value: vehicle?.engineType },
    { label: t.vehicleDetail.horsepower, value: vehicle?.horsepower },
    { label: t.vehicleDetail.color, value: vehicle?.color },
    { label: t.vehicleDetail.vin, value: vehicle?.vin },
    { label: t.vehicleDetail.stockNumber, value: vehicle?.stockNumber },
    { label: t.vehicleDetail.condition, value: vehicle?.condition },
  ]?.filter((s: any) => s?.value);

  const whatsappMsg = encodeURIComponent(`${t.whatsapp.vehicleMessage} ${vehicle?.title ?? t.common.equipment}. ${t.whatsapp.moreInfo}`);

  return (
    <div className="min-h-screen bg-[#faf5ef]">
      <div className="max-w-[1200px] mx-auto px-4 py-6">
        <Link href="/inventory" className="inline-flex items-center gap-2 text-sm text-gray-500 hover:text-red-600 transition mb-6">
          <ArrowLeft className="w-4 h-4" /> {t.vehicleDetail.backToInventory}
        </Link>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Image Gallery */}
          <motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }}>
            <div className="relative aspect-[4/3] rounded-xl overflow-hidden bg-gray-100 shadow-lg">
              <Image src={currentImgUrl} alt={vehicle?.title ?? 'Vehicle'} fill className="object-cover" />
              {isSold && (
                <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
                  <span className="bg-red-600 text-white px-6 py-3 rounded-lg font-bold text-2xl -rotate-12">{t.vehicleDetail.soldBadge}</span>
                </div>
              )}
              {(images?.length ?? 0) > 1 && (
                <>
                  <button onClick={() => setCurrentImage(Math.max(0, currentImage - 1))} className="absolute left-3 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white p-2 rounded-full transition">
                    <ChevronLeft className="w-5 h-5" />
                  </button>
                  <button onClick={() => setCurrentImage(Math.min((images?.length ?? 1) - 1, currentImage + 1))} className="absolute right-3 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white p-2 rounded-full transition">
                    <ChevronRight className="w-5 h-5" />
                  </button>
                </>
              )}
            </div>
            {(images?.length ?? 0) > 1 && (
              <div className="flex gap-2 mt-3 overflow-x-auto pb-2">
                {(images ?? [])?.map((img: any, i: number) => (
                  <button key={i} onClick={() => setCurrentImage(i)} className={`relative w-20 h-16 rounded-lg overflow-hidden shrink-0 border-2 transition ${i === currentImage ? 'border-red-500' : 'border-transparent opacity-70 hover:opacity-100'}`}>
                    <Image src={img?.url ?? '/images/cat-trucks.jpg'} alt={`Thumbnail ${i + 1}`} fill className="object-cover" />
                  </button>
                ))}
              </div>
            )}
          </motion.div>

          {/* Details */}
          <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }}>
            <span className="text-xs font-medium text-red-600 bg-red-50 px-3 py-1 rounded-full">{categoryName}</span>
            <h1 className="font-display text-2xl md:text-3xl font-bold tracking-tight mt-3">{vehicle?.title ?? t.common.noTitle}</h1>
            <div className="flex items-center gap-4 mt-2 text-sm text-gray-500">
              <span className="flex items-center gap-1"><Eye className="w-4 h-4" /> {vehicle?.viewCount ?? 0} {t.vehicleDetail.views}</span>
              <span className={`font-medium px-2 py-0.5 rounded-full text-xs ${isSold ? 'bg-gray-200 text-gray-600' : 'bg-green-100 text-green-700'}`}>
                {isSold ? t.vehicleDetail.sold : t.vehicleDetail.available}
              </span>
            </div>
            <div className="mt-4 text-3xl font-bold text-red-600 flex items-center gap-2">
              <Tag className="w-6 h-6" />
              ${(vehicle?.price ?? 0)?.toLocaleString()}
            </div>

            {vehicle?.description && (
              <div className="mt-6">
                <h3 className="font-semibold text-sm text-gray-900 mb-2">{t.vehicleDetail.description}</h3>
                <p className="text-gray-600 text-sm leading-relaxed whitespace-pre-line">{vehicle.description}</p>
              </div>
            )}

            {/* Specs */}
            <div className="mt-6 grid grid-cols-2 gap-3">
              {(specs ?? [])?.map((spec: any, i: number) => (
                <div key={i} className="bg-white rounded-lg p-3 shadow-sm">
                  <span className="text-xs text-gray-400">{spec?.label ?? ''}</span>
                  <p className="font-medium text-sm text-gray-900 mt-0.5">{spec?.value ?? '-'}</p>
                </div>
              ))}
            </div>

            {/* CTA */}
            {!isSold && (
              <div className="mt-8 flex flex-wrap gap-3">
                <Link href={`/contact?vehicle=${vehicle?.id ?? ''}`} className="flex-1 bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg font-semibold text-sm text-center transition">
                  {t.vehicleDetail.requestInfo}
                </Link>
                <a href={`https://wa.me/19085909802?text=${whatsappMsg}`} target="_blank" rel="noopener noreferrer" className="bg-green-500 hover:bg-green-600 text-white px-6 py-3 rounded-lg font-semibold text-sm transition flex items-center gap-2">
                  <MessageCircle className="w-4 h-4" /> WhatsApp
                </a>
                <a href="tel:9085909802" className="bg-[#1a1a1a] hover:bg-gray-800 text-white px-6 py-3 rounded-lg font-semibold text-sm transition flex items-center gap-2">
                  <Phone className="w-4 h-4" /> {t.vehicleDetail.call}
                </a>
              </div>
            )}
          </motion.div>
        </div>

        {/* Related */}
        {(relatedVehicles?.length ?? 0) > 0 && (
          <div className="mt-16">
            <h2 className="font-display text-2xl font-bold tracking-tight mb-6">{t.vehicleDetail.relatedTitle} <span className="text-red-600">{t.vehicleDetail.relatedHighlight}</span></h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {(relatedVehicles ?? [])?.map((v: any) => <VehicleCard key={v?.id} vehicle={v} />)}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
