"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import { X, GitCompare, Plus, Sparkles, Loader2 } from "lucide-react";
import { motion } from "framer-motion";
import { useCarStore } from "@/store/useCarStore";
import { compareCars, aiCompare } from "@/lib/api";
import { formatPrice, cn } from "@/lib/utils";
import type { CompareResponse, AICompareResponse } from "@/lib/types";
import { resolveCarHeroImage } from "@/lib/carImage";
import BrandLogo from "@/components/brand/BrandLogo";
import BodyTypeSilhouette from "@/components/ui/BodyTypeSilhouette";

export default function ComparePage() {
  const { compareList, removeFromCompare } = useCarStore();

  const [result, setResult] = useState<CompareResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [aiResult, setAiResult] = useState<AICompareResponse | null>(null);
  const [aiLoading, setAiLoading] = useState(false);

  // Fetch spec comparison
  useEffect(() => {
    if (compareList.length < 2) { setResult(null); return; }
    setLoading(true);
    setError(null);
    compareCars(compareList.map((c) => c.id))
      .then(setResult)
      .catch(() => setError("Failed to load comparison"))
      .finally(() => setLoading(false));
  }, [compareList]);

  // Fetch AI compare summary
  useEffect(() => {
    if (compareList.length < 2) { setAiResult(null); return; }
    setAiLoading(true);
    aiCompare(compareList.map((c) => c.id))
      .then(setAiResult)
      .catch(() => setAiResult(null))  // graceful: no error shown if OpenAI not set
      .finally(() => setAiLoading(false));
  }, [compareList]);

  const cars = result?.cars ?? compareList;
  const cols = cars.length + (cars.length < 4 ? 1 : 0);

  /* EMPTY STATE */
  if (compareList.length === 0) {
    return (
      <div className="max-w-[1280px] mx-auto px-4 py-24">
        <div className="max-w-xl mx-auto text-center">
          <div className="w-24 h-24 rounded-[30px] bg-gradient-to-br from-blue-50 to-cyan-50 flex items-center justify-center mx-auto mb-6 shadow-lg">
            <GitCompare className="w-10 h-10 text-blue-600" />
          </div>
          <h1 className="text-4xl font-black text-gray-900 mb-3">Compare Cars</h1>
          <p className="text-gray-500 text-lg leading-relaxed mb-8">
            Add multiple cars and compare their price, mileage, specifications &amp; features side by side.
          </p>
          <Link
            href="/cars"
            className="inline-flex items-center gap-2 rounded-2xl bg-gradient-to-r from-blue-600 to-cyan-500 px-8 py-4 text-white font-black shadow-xl shadow-blue-100 hover:scale-105 transition-all duration-300"
          >
            Browse Cars
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-[1280px] mx-auto px-4 py-6 pb-24">
      {/* PAGE HEADER */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-6">
        <div>
          <p className="text-[11px] uppercase tracking-[0.2em] text-blue-600 font-black mb-1">
            Smart Comparison
          </p>
          <h1 className="text-3xl font-black text-gray-900">Compare Cars</h1>
        </div>
        <div className="inline-flex items-center gap-2 rounded-2xl bg-white border border-gray-200 px-4 py-3 shadow-sm">
          <Sparkles className="w-4 h-4 text-blue-500" />
          <span className="text-sm font-semibold text-gray-700">
            {compareList.length} of 4 cars selected
          </span>
        </div>
      </div>

      {error && (
        <div className="mb-5 rounded-2xl border border-red-200 bg-red-50 px-5 py-4 text-sm font-medium text-red-700">
          {error}
        </div>
      )}

      {/* ── AI Compare Summary ── */}
      {(aiLoading || aiResult) && (
        <div className="mb-6 rounded-[28px] bg-gradient-to-br from-blue-600 via-blue-700 to-indigo-700 overflow-hidden shadow-[0_8px_30px_rgba(37,99,235,0.25)]">
          <div className="px-6 py-5">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-2xl bg-white/20 backdrop-blur flex items-center justify-center">
                <Sparkles className="w-5 h-5 text-white" />
              </div>
              <div>
                <p className="text-[10px] uppercase tracking-[0.2em] text-blue-200 font-black">Expert Verdict</p>
                <p className="text-base font-black text-white">Comparison Summary</p>
              </div>
            </div>

            {aiLoading ? (
              <div className="flex items-center gap-3 py-2">
                <Loader2 className="w-4 h-4 text-blue-200 animate-spin shrink-0" />
                <p className="text-sm text-blue-200">Analysing {compareList.length} cars…</p>
              </div>
            ) : aiResult ? (
              <>
                <p className="text-sm leading-relaxed text-blue-50 font-medium mb-4">
                  {aiResult.summary}
                </p>
                {aiResult.winner && (
                  <div className="inline-flex items-center gap-2 bg-white/20 rounded-2xl px-4 py-2">
                    <span className="text-xs text-blue-200 font-bold">Best Pick:</span>
                    <span className="text-sm text-white font-black">{aiResult.winner}</span>
                  </div>
                )}
              </>
            ) : null}
            <p className="text-[10px] text-blue-300 mt-4">
              For guidance only
            </p>
          </div>
        </div>
      )}

      {/* CAR HEADER CARDS */}
      <div className="overflow-x-auto scrollbar-thin pb-2 mb-6">
        <div
          className="grid gap-4"
          style={{ gridTemplateColumns: `repeat(${cols}, minmax(200px,1fr))` }}
        >
            {cars.map((car) => {
              const heroSrc = resolveCarHeroImage(car);
              return (
                <motion.div
                  key={car.id}
                  whileHover={{ y: -4 }}
                  transition={{ duration: 0.25 }}
                  className="group relative overflow-hidden rounded-[30px] border border-gray-200/70 bg-white shadow-[0_10px_40px_rgba(0,0,0,0.05)]"
                >
                  <button
                    onClick={() => removeFromCompare(car.id)}
                    aria-label={`Remove ${car.name} from comparison`}
                    className="absolute top-4 right-4 z-10 w-9 h-9 rounded-2xl bg-white/90 backdrop-blur-xl border border-gray-200 flex items-center justify-center hover:bg-red-50 hover:border-red-200 hover:text-red-500 transition-all duration-300 shadow-md focus:outline-none focus:ring-2 focus:ring-red-400"
                  >
                    <X className="w-4 h-4" aria-hidden="true" />
                  </button>
                  <div className="relative aspect-[16/10] overflow-hidden bg-gradient-to-br from-gray-100 to-gray-50">
                    {heroSrc ? (
                      <Image
                        src={heroSrc}
                        alt={car.name}
                        fill
                        className="object-cover transition-transform duration-700 group-hover:scale-105"
                        sizes="400px"
                      />
                    ) : (
                      <div className="absolute inset-0 flex items-center justify-center p-10">
                        <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" />
                  </div>
                  <div className="p-5">
                    <div className="flex items-center gap-2 mb-2">
                      <BrandLogo brand={car.brand} size={22} showWhiteBg={false} />
                      <p className="text-[10px] uppercase tracking-[0.2em] text-blue-600 font-black">{car.brand}</p>
                    </div>
                    <Link href={`/cars/${car.id}`} className="block">
                      <h2 className="text-lg font-black text-gray-900 leading-tight hover:text-blue-600 transition-colors duration-300 line-clamp-2 min-h-[48px]">
                        {car.name}
                      </h2>
                    </Link>
                    <p className="text-2xl font-black text-blue-600">{formatPrice(car.priceMin)}</p>
                  </div>
                </motion.div>
              );
            })}

            {/* ADD SLOT */}
            {compareList.length < 4 && (
              <Link
                href="/cars"
                className="group rounded-[30px] border-2 border-dashed border-gray-300 bg-white flex flex-col items-center justify-center p-8 min-h-[320px] hover:border-blue-300 hover:bg-blue-50/40 transition-all duration-300"
              >
                <div className="w-16 h-16 rounded-3xl bg-gray-100 flex items-center justify-center mb-4 group-hover:bg-blue-100 transition-colors duration-300">
                  <Plus className="w-8 h-8 text-gray-400 group-hover:text-blue-600" />
                </div>
                <span className="text-lg font-black text-gray-700 group-hover:text-blue-600 transition-colors">
                  Add Car
                </span>
                <p className="text-sm text-gray-400 mt-2 text-center">Compare up to 4 cars</p>
              </Link>
            )}
          </div>
        </div>

          {/* LOADING */}
          {loading && (
            <div className="rounded-[30px] border border-gray-200 bg-white p-12 text-center shadow-sm">
              <div className="w-12 h-12 rounded-full border-4 border-blue-100 border-t-blue-600 animate-spin mx-auto mb-5" />
              <p className="text-gray-500 font-medium">Loading comparison...</p>
            </div>
          )}

          {/* SPEC TABLE */}
          {!loading && result && (
            <div className="overflow-hidden rounded-[30px] border border-gray-200/70 bg-white shadow-[0_10px_40px_rgba(0,0,0,0.04)]">
              <div className="px-6 py-5 border-b border-gray-100 bg-gradient-to-r from-gray-50 to-blue-50">
                <h2 className="text-sm uppercase tracking-[0.2em] text-gray-700 font-black">
                  Specifications Comparison
                </h2>
              </div>
              <div className="overflow-x-auto">
                <div className="min-w-[900px]">
                  {result.specs.map((spec, i) => (
                    <div
                      key={spec.key}
                      className={cn(
                        "border-b border-gray-100 last:border-0",
                        i % 2 === 1 ? "bg-gray-50/50" : "bg-white"
                      )}
                      style={{
                        display: "grid",
                        gridTemplateColumns: `240px repeat(${cars.length}, minmax(0,1fr))`,
                      }}
                    >
                      <div className="px-6 py-5 flex items-center bg-white sticky left-0 z-10 border-r border-gray-100">
                        <span className="text-sm font-black text-gray-600">{spec.label}</span>
                      </div>
                      {spec.values.map((val, j) => (
                        <div
                          key={j}
                          className={cn(
                            "px-5 py-5 text-center text-sm flex items-center justify-center font-semibold",
                            val == null ? "text-gray-300" : "text-gray-800"
                          )}
                        >
                          {val == null ? "—" : String(val)}
                        </div>
                      ))}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
    </div>
  );
}
