"use client";

import { useState, useEffect, useCallback } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import { motion } from "framer-motion";
import {
  ArrowLeft,
  Trophy,
  Eye,
  Calendar,
  Sparkles,
  CheckCircle2,
  MessageSquare,
  ChevronRight,
} from "lucide-react";
import { fetchComparison } from "@/lib/api";
import type { CarComparison, ComparisonCategory } from "@/lib/types";
import { cn } from "@/lib/utils";

// ── Helpers ───────────────────────────────────────────────────────────────────

function formatDate(iso: string) {
  try {
    return new Date(iso).toLocaleDateString("en-IN", {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  } catch {
    return iso;
  }
}

// ── Score bar row ─────────────────────────────────────────────────────────────

function ScoreRow({ category }: { category: ComparisonCategory }) {
  const c1 = Math.max(0, Math.min(10, category.car1Score));
  const c2 = Math.max(0, Math.min(10, category.car2Score));

  return (
    <motion.div
      initial={{ opacity: 0, x: -10 }}
      animate={{ opacity: 1, x: 0 }}
      className="py-3"
    >
      <div className="flex items-center gap-3 mb-2 min-w-0">
        <span className="text-xs font-bold text-gray-500 uppercase tracking-wider flex-1 text-center break-words">
          {category.name}
        </span>
        {category.winner !== "tie" && (
          <span className={cn(
            "text-xs font-bold px-2 py-0.5 rounded-full",
            category.winner === "car1"
              ? "bg-blue-50 text-blue-600"
              : "bg-purple-50 text-purple-600"
          )}>
            {category.winner === "car1" ? "Better" : "Better"}
          </span>
        )}
      </div>
      <div className="flex items-center gap-2 sm:gap-3 min-w-0">
        <div className={cn(
          "w-10 sm:w-14 shrink-0 text-right text-xs sm:text-sm font-black tabular-nums",
          c1 > c2 ? "text-blue-600" : c1 < c2 ? "text-gray-400" : "text-gray-600"
        )}>
          {c1}/10
        </div>
        <div className="flex-1 min-w-0 h-3 bg-gray-100 rounded-full relative overflow-hidden">
          <motion.div
            initial={{ width: 0 }}
            animate={{ width: `${c1 * 10}%` }}
            transition={{ duration: 0.7, delay: 0.1, ease: "easeOut" }}
            className={cn(
              "h-full rounded-full absolute left-0",
              c1 >= c2 ? "bg-blue-500" : "bg-blue-300"
            )}
          />
        </div>
        <div className="flex-1 min-w-0 h-3 bg-gray-100 rounded-full relative overflow-hidden">
          <motion.div
            initial={{ width: 0 }}
            animate={{ width: `${c2 * 10}%` }}
            transition={{ duration: 0.7, delay: 0.2, ease: "easeOut" }}
            className={cn(
              "h-full rounded-full absolute right-0",
              c2 >= c1 ? "bg-purple-500" : "bg-purple-300"
            )}
          />
        </div>
        <div className={cn(
          "w-10 sm:w-14 shrink-0 text-left text-xs sm:text-sm font-black tabular-nums",
          c2 > c1 ? "text-purple-600" : c2 < c1 ? "text-gray-400" : "text-gray-600"
        )}>
          {c2}/10
        </div>
      </div>
      {category.note && (
        <p className="text-xs text-gray-400 text-center mt-1 break-words">{category.note}</p>
      )}
    </motion.div>
  );
}

// ── Skeleton ──────────────────────────────────────────────────────────────────

function ComparisonSkeleton() {
  return (
    <div className="animate-pulse space-y-6">
      <div className="grid grid-cols-[1fr,auto,1fr] gap-4 items-center">
        <div className="h-8 bg-gray-200 rounded-2xl" />
        <div className="w-12 h-12 bg-gray-200 rounded-full" />
        <div className="h-8 bg-gray-200 rounded-2xl" />
      </div>
      {Array.from({ length: 5 }).map((_, i) => (
        <div key={i} className="h-10 bg-gray-100 rounded-2xl" />
      ))}
    </div>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────────────

export default function ComparisonDetailPage() {
  const params = useParams();
  const slug = params?.slug as string;

  const [comparison, setComparison] = useState<CarComparison | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    if (!slug) {
      setComparison(null);
      setError("Comparison not found or failed to load.");
      setLoading(false);
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const c = await fetchComparison(slug);
      setComparison(c);
    } catch {
      setComparison(null);
      setError("Comparison not found or failed to load.");
    } finally {
      setLoading(false);
    }
  }, [slug]);

  useEffect(() => {
    load();
  }, [load]);

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 flex flex-col items-center justify-center gap-4 p-4">
        <div className="w-14 h-14 rounded-2xl bg-red-50 flex items-center justify-center">
          <MessageSquare className="w-7 h-7 text-red-400" />
        </div>
        <p className="text-gray-700 font-bold text-lg text-center break-words max-w-sm">{error}</p>
        <Link href="/compare" className="flex items-center gap-2 text-sm font-bold text-blue-600 hover:underline">
          <ArrowLeft className="w-4 h-4" />
          Back to Comparisons
        </Link>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 min-w-0">
      {/* Hero */}
      <div className="bg-gradient-to-br from-gray-900 via-slate-900 to-gray-900 text-white pt-10 pb-16 px-4">
        <div className="max-w-4xl mx-auto min-w-0">
          <Link
            href="/compare"
            className="inline-flex items-center gap-2 text-sm font-bold text-gray-300 hover:text-white transition-colors mb-6"
          >
            <ArrowLeft className="w-4 h-4" />
            Back to Comparisons
          </Link>

          {loading ? (
            <div className="animate-pulse space-y-4">
              <div className="grid grid-cols-[1fr,auto,1fr] gap-4 items-center">
                <div className="h-10 bg-white/10 rounded-2xl" />
                <div className="w-14 h-14 bg-white/10 rounded-full" />
                <div className="h-10 bg-white/10 rounded-2xl" />
              </div>
            </div>
          ) : comparison ? (
            <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}>
              {/* Winner badge */}
              {comparison.winner && (
                <div className="flex justify-center mb-6">
                  <div className="inline-flex items-center gap-2 bg-amber-500/20 border border-amber-500/40 text-amber-300 px-4 py-2 rounded-full text-sm font-bold max-w-full text-center break-words">
                    <Trophy className="w-4 h-4 text-amber-400 shrink-0" />
                    <span className="break-words">{comparison.winner} wins this comparison</span>
                  </div>
                </div>
              )}

              {/* VS header */}
              <div className="grid grid-cols-[minmax(0,1fr),auto,minmax(0,1fr)] gap-2 sm:gap-4 items-center mb-6">
                <div className="text-center min-w-0">
                  <h2 className="text-xl sm:text-2xl md:text-3xl font-black text-white leading-tight break-words">{comparison.car1Name}</h2>
                  <span className="text-sm text-blue-400 font-bold mt-1 block">Your Choice?</span>
                </div>
                <div className="bg-white text-gray-900 font-black text-sm sm:text-lg w-10 h-10 sm:w-14 sm:h-14 rounded-full flex items-center justify-center shadow-xl shrink-0">
                  VS
                </div>
                <div className="text-center min-w-0">
                  <h2 className="text-xl sm:text-2xl md:text-3xl font-black text-white leading-tight break-words">{comparison.car2Name}</h2>
                  <span className="text-sm text-purple-400 font-bold mt-1 block">Or This?</span>
                </div>
              </div>

              {/* Metadata */}
              <div className="flex flex-wrap items-center justify-center gap-4 text-sm text-gray-400">
                {comparison.aiGenerated && (
                  <span className="flex items-center gap-1.5 text-purple-300">
                    <Sparkles className="w-4 h-4" />
                    DriveHub Editorial
                  </span>
                )}
                <span className="flex items-center gap-1.5">
                  <Calendar className="w-4 h-4" />
                  {formatDate(comparison.publishedAt)}
                </span>
                {comparison.views > 0 && (
                  <span className="flex items-center gap-1.5">
                    <Eye className="w-4 h-4" />
                    {comparison.views.toLocaleString()} views
                  </span>
                )}
              </div>
            </motion.div>
          ) : null}
        </div>
      </div>

      {/* Content */}
      <div className="max-w-4xl mx-auto px-4 py-10 space-y-10 min-w-0">
        {loading ? (
          <ComparisonSkeleton />
        ) : comparison ? (
          <>
            {/* Score cards */}
            {comparison.categories?.length > 0 && (
              <section>
                <h2 className="text-xl font-black text-gray-900 mb-2">Head-to-Head Scores</h2>
                <div className="flex flex-wrap items-center gap-x-4 gap-y-2 mb-4 min-w-0">
                  <div className="flex items-center gap-2 text-sm min-w-0 max-w-full">
                    <div className="w-3 h-3 rounded-full bg-blue-500 shrink-0" />
                    <span className="font-bold text-gray-700 break-words">{comparison.car1Name}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm min-w-0 max-w-full">
                    <div className="w-3 h-3 rounded-full bg-purple-500 shrink-0" />
                    <span className="font-bold text-gray-700 break-words">{comparison.car2Name}</span>
                  </div>
                </div>
                <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-6 divide-y divide-gray-50 min-w-0">
                  {comparison.categories.map((cat, i) => (
                    <ScoreRow key={i} category={cat} />
                  ))}
                </div>
              </section>
            )}

            {/* Verdict */}
            {(comparison.verdict || comparison.winnerReason) && (
              <section>
                <div className="bg-gradient-to-r from-amber-50 to-orange-50 border border-amber-200 rounded-2xl p-4 sm:p-6 min-w-0">
                  <div className="flex items-start gap-3 mb-4 min-w-0">
                    <div className="w-10 h-10 rounded-xl bg-amber-100 flex items-center justify-center shrink-0">
                      <Trophy className="w-5 h-5 text-amber-600" />
                    </div>
                    <div className="min-w-0">
                      <h3 className="text-lg font-black text-gray-900">Verdict</h3>
                      {comparison.winner && (
                        <p className="text-sm font-bold text-amber-700 mt-0.5 break-words">
                          Winner: {comparison.winner}
                        </p>
                      )}
                    </div>
                  </div>
                  {comparison.winnerReason && (
                    <p className="text-gray-700 leading-relaxed mb-3 break-words">{comparison.winnerReason}</p>
                  )}
                  {comparison.verdict && comparison.verdict !== comparison.winnerReason && (
                    <p className="text-gray-600 text-sm leading-relaxed break-words">{comparison.verdict}</p>
                  )}
                </div>
              </section>
            )}

            {/* Detailed content */}
            {comparison.content && (
              <section className="min-w-0">
                <h2 className="text-xl font-black text-gray-900 mb-6">Detailed Comparison</h2>
                <div className="min-w-0 overflow-x-auto">
                  <div
                    className="blog-content text-gray-700"
                    dangerouslySetInnerHTML={{ __html: comparison.content }}
                  />
                </div>
              </section>
            )}

            {/* CTA row */}
            <section>
              <h2 className="text-xl font-black text-gray-900 mb-4">Get On-Road Price</h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {[
                  { name: comparison.car1Name, id: comparison.car1Id, color: "from-blue-600 to-cyan-500", shadow: "shadow-blue-100" },
                  { name: comparison.car2Name, id: comparison.car2Id, color: "from-purple-600 to-violet-500", shadow: "shadow-purple-100" },
                ].map((car) => (
                  <Link
                    key={car.id}
                    href={`/cars/${car.id}`}
                    className={cn(
                      "group flex items-center justify-between gap-3 p-4 sm:p-5 rounded-2xl bg-gradient-to-r text-white font-bold shadow-xl transition-all duration-200 hover:shadow-2xl hover:-translate-y-0.5 min-w-0",
                      car.color,
                      car.shadow
                    )}
                  >
                    <div className="min-w-0">
                      <p className="text-sm opacity-75 font-medium">Get price for</p>
                      <p className="text-base sm:text-lg font-black break-words">{car.name}</p>
                    </div>
                    <ChevronRight className="w-6 h-6 opacity-70 group-hover:translate-x-1 transition-transform shrink-0" />
                  </Link>
                ))}
              </div>
            </section>

            {/* Quick summary */}
            <section className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-6 min-w-0">
              <h3 className="text-sm font-black text-gray-900 uppercase tracking-wider mb-4 flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-green-500 shrink-0" />
                Quick Summary
              </h3>
              <div className="grid grid-cols-1 xs:grid-cols-2 gap-4 text-sm min-w-0">
                <div className="min-w-0">
                  <p className="text-gray-400 font-medium mb-1">Car 1</p>
                  <p className="font-black text-gray-900 break-words">{comparison.car1Name}</p>
                </div>
                <div className="min-w-0">
                  <p className="text-gray-400 font-medium mb-1">Car 2</p>
                  <p className="font-black text-gray-900 break-words">{comparison.car2Name}</p>
                </div>
                {comparison.winner && (
                  <div className="col-span-1 xs:col-span-2 min-w-0">
                    <p className="text-gray-400 font-medium mb-1">Winner</p>
                    <p className="font-black text-amber-600 flex items-center gap-1 break-words">
                      <Trophy className="w-4 h-4 shrink-0" />
                      {comparison.winner}
                    </p>
                  </div>
                )}
              </div>
            </section>
          </>
        ) : !loading ? (
          <div className="text-center py-16">
            <p className="text-gray-500 font-medium mb-4">Comparison not found.</p>
            <Link href="/compare" className="inline-flex items-center gap-2 text-sm font-bold text-blue-600 hover:underline">
              <ArrowLeft className="w-4 h-4" />
              Back to Comparisons
            </Link>
          </div>
        ) : null}
      </div>

      <style>{`
        .blog-content { overflow-wrap: anywhere; word-break: break-word; }
        .blog-content h1 { font-size: 2rem; font-weight: 900; color: #111827; margin: 2rem 0 1rem; line-height: 1.2; }
        .blog-content h2 { font-size: 1.5rem; font-weight: 900; color: #111827; margin: 2rem 0 0.75rem; line-height: 1.3; }
        .blog-content h3 { font-size: 1.25rem; font-weight: 800; color: #1f2937; margin: 1.5rem 0 0.5rem; line-height: 1.4; }
        .blog-content h4 { font-size: 1.1rem; font-weight: 700; color: #374151; margin: 1.25rem 0 0.5rem; }
        .blog-content p  { margin: 0 0 1.25rem; line-height: 1.75; color: #374151; }
        .blog-content ul { list-style: disc; padding-left: 1.5rem; margin: 0 0 1.25rem; }
        .blog-content ol { list-style: decimal; padding-left: 1.5rem; margin: 0 0 1.25rem; }
        .blog-content li { margin-bottom: 0.4rem; line-height: 1.7; color: #374151; }
        .blog-content a  { color: #2563eb; text-decoration: underline; }
        .blog-content strong { font-weight: 700; color: #111827; }
        .blog-content blockquote { border-left: 4px solid #8b5cf6; padding: 0.75rem 1rem; margin: 1.5rem 0; background: #f5f3ff; border-radius: 0 0.75rem 0.75rem 0; color: #5b21b6; }
        .blog-content pre  { background: #1f2937; color: #f9fafb; padding: 1.25rem; border-radius: 0.75rem; overflow-x: auto; margin: 1.5rem 0; }
        .blog-content table { display: block; width: 100%; max-width: 100%; overflow-x: auto; border-collapse: collapse; margin: 1.5rem 0; font-size: 0.9rem; }
        .blog-content th { background: #f3f4f6; font-weight: 700; padding: 0.75rem 1rem; text-align: left; border: 1px solid #e5e7eb; }
        .blog-content td { padding: 0.625rem 1rem; border: 1px solid #e5e7eb; }
        .blog-content tr:nth-child(even) td { background: #f9fafb; }
        .blog-content img { max-width: 100%; height: auto; border-radius: 0.75rem; margin: 1.5rem 0; }
        .blog-content hr { border: 0; border-top: 1px solid #e5e7eb; margin: 2rem 0; }
      `}</style>
    </div>
  );
}
