"use client";

import { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import {
  Heart,
  GitCompare,
  Star,
  ChevronRight,
  Gauge,
  Settings2,
  Sparkles,
  Loader2,
} from "lucide-react";
import { motion } from "framer-motion";

import type { Car } from "@/lib/types";
import { formatPrice, cn } from "@/lib/utils";
import { resolveCarHeroImage } from "@/lib/carImage";
import CarFieldBadges from "@/components/cars/CarFieldBadges";
import { useWishlistStore } from "@/store/useWishlistStore";
import { useCarStore } from "@/store/useCarStore";
import BrandLogo from "@/components/brand/BrandLogo";
import BodyTypeSilhouette from "@/components/ui/BodyTypeSilhouette";
import { CAR_CARD_BLUR } from "@/lib/blurPlaceholder";

export default function CarGridCard({ car }: { car: Car }) {
  const { toggle, has }                                          = useWishlistStore();
  const { addToCompare, removeFromCompare, compareList }         = useCarStore();

  const isWished    = has(car.id);
  const isComparing = compareList.some((c) => c.id === car.id);
  const canCompare  = compareList.length < 4;
  const heroSrc     = resolveCarHeroImage(car);
  const fuelDisplay = car.fuelTypes?.length ? car.fuelTypes : car.fuelType;
  const transDisplay = car.availableTransmissions?.length ? car.availableTransmissions : car.transmission;

  const [wishLoading,    setWishLoading]    = useState(false);
  const [compareLoading, setCompareLoading] = useState(false);

  function handleWishlist() {
    setWishLoading(true);
    toggle(car);
    setTimeout(() => setWishLoading(false), 400);
  }

  function handleCompare() {
    if (!canCompare && !isComparing) return;
    setCompareLoading(true);
    isComparing ? removeFromCompare(car.id) : addToCompare(car);
    setTimeout(() => setCompareLoading(false), 400);
  }

  return (
    <motion.div
      whileHover={{ y: -4 }}
      transition={{ duration: 0.25 }}
      className="group relative min-w-0 overflow-hidden rounded-[24px] border border-gray-200/70 bg-white shadow-[0_4px_20px_rgba(0,0,0,0.05)] hover:shadow-[0_12px_40px_rgba(37,99,235,0.10)] hover:border-blue-100 transition-all duration-300"
    >
      {/* ── IMAGE ────────────────────────────────────────────────────────── */}
      <div className="relative h-[180px] overflow-hidden bg-gradient-to-br from-gray-100 to-gray-50">
        {heroSrc ? (
          <Image
            src={heroSrc}
            alt={car.name}
            fill
            placeholder="blur"
            blurDataURL={CAR_CARD_BLUR}
            quality={75}
            className="object-cover group-hover:scale-105 transition-transform duration-500"
            sizes="(max-width: 640px) 100vw, 33vw"
            loading="lazy"
          />
        ) : (
          /* SVG silhouette — never generic Lucide Car icon */
          <div className="absolute inset-0 flex items-center justify-center p-8 bg-gradient-to-br from-gray-50 to-gray-100">
            <BodyTypeSilhouette
              type={car.bodyType}
              className="w-full h-full text-gray-300 max-h-[100px]"
            />
          </div>
        )}

        <div className="absolute inset-0 bg-gradient-to-t from-black/20 via-transparent to-transparent" />

        {car.badge && (
          <div className="absolute top-3 left-3">
            <div className="flex items-center gap-1 rounded-xl bg-gradient-to-r from-red-500 to-pink-500 px-2.5 py-1 text-[10px] font-black text-white shadow-lg">
              <Sparkles className="w-2.5 h-2.5" aria-hidden="true" />
              {car.badge}
            </div>
          </div>
        )}

        {car.isNew && !car.badge && (
          <div className="absolute top-3 left-3">
            <span className="rounded-xl bg-green-500 px-2.5 py-1 text-[10px] font-black text-white shadow-md">
              NEW
            </span>
          </div>
        )}

        {/* Wishlist button */}
        <motion.button
          type="button"
          whileTap={{ scale: 0.88 }}
          whileHover={{ scale: 1.05 }}
          onClick={handleWishlist}
          disabled={wishLoading}
          aria-label={isWished ? `Remove ${car.name} from wishlist` : `Save ${car.name} to wishlist`}
          aria-pressed={isWished}
          className={cn(
            "absolute top-3 right-3 w-9 h-9 rounded-2xl border flex items-center justify-center transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-red-400 shadow-md",
            isWished
              ? "bg-red-50 border-red-200 text-red-500"
              : "bg-white/90 backdrop-blur-sm border-gray-200/80 text-gray-400 hover:border-red-200 hover:text-red-500"
          )}
        >
          {wishLoading
            ? <Loader2 className="w-3.5 h-3.5 animate-spin" aria-hidden="true" />
            : <Heart className="w-3.5 h-3.5" fill={isWished ? "currentColor" : "none"} aria-hidden="true" />
          }
        </motion.button>
      </div>

      {/* ── BODY ─────────────────────────────────────────────────────────── */}
      <div className="p-4">
        {/* Brand row with logo */}
        <div className="flex items-center gap-1.5 mb-1">
          <BrandLogo brand={car.brand} size={18} showWhiteBg={false} />
          <p className="text-[10px] uppercase tracking-[0.18em] text-blue-600 font-black">{car.brand}</p>
        </div>

        {/* Name */}
        <Link href={`/cars/${car.id}`} className="block mb-1">
          <h2 className="text-sm font-black text-gray-900 leading-snug line-clamp-2 group-hover:text-blue-600 transition-colors duration-300">
            {car.name}
            <span className="ml-1.5 text-[11px] font-medium text-gray-400">({car.year})</span>
          </h2>
        </Link>

        {/* Rating */}
        {car.rating > 0 && (
          <div className="flex items-center gap-2 mb-2">
            <div className="flex items-center gap-0.5 bg-gradient-to-r from-green-500 to-emerald-500 text-white text-[10px] font-black px-2 py-0.5 rounded-lg shadow-sm">
              <Star className="w-2.5 h-2.5 fill-current" aria-hidden="true" />
              {car.rating.toFixed(1)}
            </div>
            <span className="text-[10px] text-gray-400">({car.reviewCount.toLocaleString()})</span>
          </div>
        )}

        {/* Tags */}
        <div className="flex flex-wrap gap-1.5 mb-3">
          <CarFieldBadges value={fuelDisplay} kind="fuel" size="sm" />
          <CarFieldBadges value={transDisplay} kind="transmission" size="sm" />
        </div>

        {/* Key specs */}
        {(car.specs?.mileage || car.specs?.engine) && (
          <div className="flex flex-wrap gap-1.5 border-t border-gray-100 pt-2.5 mb-3">
            {car.specs.mileage && (
              <div className="flex items-center gap-1.5 rounded-xl bg-gray-50 px-2 py-1.5">
                <Gauge className="w-3 h-3 text-blue-500 shrink-0" aria-hidden="true" />
                <span className="text-[10px] font-semibold text-gray-700">{car.specs.mileage}</span>
              </div>
            )}
            {car.specs.engine && (
              <div className="flex items-center gap-1.5 rounded-xl bg-gray-50 px-2 py-1.5">
                <Settings2 className="w-3 h-3 text-blue-500 shrink-0" aria-hidden="true" />
                <span className="text-[10px] font-semibold text-gray-700">{car.specs.engine}</span>
              </div>
            )}
          </div>
        )}

        {/* Price + CTA */}
        <div className="flex items-center justify-between pt-1">
          <div>
            <p className="text-[10px] text-gray-400 font-medium">Starting</p>
            <p className="text-base font-black text-gray-900">{formatPrice(car.priceMin)}</p>
          </div>
          <Link
            href={`/cars/${car.id}`}
            className="inline-flex items-center gap-1 text-xs font-black text-blue-600 hover:text-blue-700 transition-colors"
          >
            Details <ChevronRight className="w-3.5 h-3.5" aria-hidden="true" />
          </Link>
        </div>
      </div>

      {/* ── COMPARE FOOTER ───────────────────────────────────────────────── */}
      <div className="px-4 pb-3 border-t border-gray-100 pt-2.5">
        <button
          type="button"
          onClick={handleCompare}
          disabled={(!canCompare && !isComparing) || compareLoading}
          aria-label={isComparing ? `Remove ${car.name} from comparison` : `Add ${car.name} to comparison`}
          aria-pressed={isComparing}
          className={cn(
            "w-full flex items-center justify-center gap-1.5 rounded-2xl py-2 text-xs font-bold transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-blue-400 border",
            isComparing
              ? "bg-blue-50 border-blue-200 text-blue-600"
              : canCompare
              ? "bg-gray-50 border-gray-200 text-gray-600 hover:bg-blue-50 hover:border-blue-200 hover:text-blue-600"
              : "bg-gray-50 border-gray-100 text-gray-300 cursor-not-allowed"
          )}
        >
          {compareLoading
            ? <Loader2 className="w-3.5 h-3.5 animate-spin" aria-hidden="true" />
            : <GitCompare className="w-3.5 h-3.5" aria-hidden="true" />
          }
          {isComparing ? "Added to Compare" : "Add to Compare"}
        </button>
      </div>
    </motion.div>
  );
}
