"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  Sparkles, RotateCcw, ArrowRight, Info, Trophy, Layers,
  GitCompare, Car, MessageCircle, Loader2,
} from "lucide-react";
import type { WizardInput, WizardMatchResult, WizardResult } from "@/lib/types";
import { formatPrice } from "@/lib/utils";
import { fetchCars } from "@/lib/api";
import { buildFallbackMatches } from "@/lib/wizardScoring";
import WizardResultCard from "@/components/wizard/WizardResultCard";

interface WizardResultsProps {
  result: WizardResult;
  budgetMin: number;
  budgetMax: number;
  fuelTypes: string[];
  bodyTypes: string[];
  familySize: number;
  onReset: () => void;
}

function openCarAdvisor() {
  window.dispatchEvent(new CustomEvent("drivehub:open-advisor"));
}

export default function WizardResults({
  result,
  budgetMin,
  budgetMax,
  fuelTypes,
  bodyTypes,
  familySize,
  onReset,
}: WizardResultsProps) {
  const { bestMatch, alternatives, totalMatches, aiPowered } = result;
  const [fallbackMatches, setFallbackMatches] = useState<WizardMatchResult[]>([]);
  const [loadingFallback, setLoadingFallback] = useState(false);

  const hasExactMatch = Boolean(bestMatch);
  const exactAlternatives = alternatives;
  const showFallback = !hasExactMatch;

  useEffect(() => {
    if (hasExactMatch) {
      setFallbackMatches([]);
      return;
    }

    let cancelled = false;
    setLoadingFallback(true);

    const input: WizardInput = {
      budgetMin,
      budgetMax,
      fuelTypes,
      bodyTypes,
      familySize,
    };

    buildFallbackMatches(input, fetchCars)
      .then((matches) => {
        if (!cancelled) setFallbackMatches(matches);
      })
      .catch(() => {
        if (!cancelled) setFallbackMatches([]);
      })
      .finally(() => {
        if (!cancelled) setLoadingFallback(false);
      });

    return () => { cancelled = true; };
  }, [hasExactMatch, budgetMin, budgetMax, fuelTypes, bodyTypes, familySize]);

  const displayAlternatives = showFallback ? fallbackMatches : exactAlternatives;
  const totalShown = (hasExactMatch ? 1 : 0) + displayAlternatives.length;

  return (
    <div className="w-full min-w-0">
      {/* Header */}
      <div className="text-center mb-10 min-w-0 px-1">
        <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-blue-100 text-blue-700 text-xs font-black mb-4">
          {aiPowered
            ? <><Sparkles className="w-3.5 h-3.5" /> {totalMatches} cars analysed</>
            : <><Info className="w-3.5 h-3.5" /> {totalMatches} cars matched</>
          }
        </div>
        <h2 className="text-2xl sm:text-3xl md:text-4xl font-black text-gray-900 mb-2 break-words">
          {hasExactMatch ? "Your Perfect Match" : "Closest Matches For You"}
        </h2>
        <p className="text-gray-500 text-sm max-w-xl mx-auto break-words">
          Based on {formatPrice(budgetMin)} – {formatPrice(budgetMax)} budget,&nbsp;
          {fuelTypes.length ? fuelTypes.join(" / ") : "any fuel"},&nbsp;
          {bodyTypes.length ? bodiesLabel(bodyTypes) : "any body type"},&nbsp;
          family of {familySize}
        </p>
      </div>

      {/* No exact match banner */}
      {showFallback && (
        <div className="rounded-2xl bg-gradient-to-r from-amber-50 to-orange-50 border border-amber-200/80 px-4 sm:px-6 py-5 mb-8 text-center min-w-0">
          <h3 className="text-lg font-black text-gray-800 mb-1 break-words">
            No exact matches found, but we found these alternatives
          </h3>
          <p className="text-sm text-gray-500 break-words">
            Ranked by budget, fuel type, body type, and family size — the closest options in our catalogue.
          </p>
        </div>
      )}

      {loadingFallback && showFallback && (
        <div className="flex flex-col items-center justify-center py-16 gap-4">
          <Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
          <p className="text-sm text-gray-500 font-medium">Finding nearest alternatives…</p>
        </div>
      )}

      {/* Best Match */}
      {hasExactMatch && bestMatch && (
        <section className="mb-10">
          <div className="flex items-center gap-3 mb-5">
            <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-blue-600 to-indigo-600 flex items-center justify-center shadow-md shadow-blue-100">
              <Trophy className="w-4 h-4 text-yellow-300" />
            </div>
            <div>
              <h3 className="text-lg font-black text-gray-900">Best Match</h3>
              <p className="text-xs text-gray-500">Top pick based on your preferences</p>
            </div>
          </div>
          <div className="max-w-md mx-auto min-w-0 w-full">
            <WizardResultCard
              match={bestMatch}
              rank={1}
              budgetMin={budgetMin}
              budgetMax={budgetMax}
              fuelTypes={fuelTypes}
              bodyTypes={bodyTypes}
              familySize={familySize}
              featured
            />
          </div>
        </section>
      )}

      {/* Alternatives */}
      {!loadingFallback && displayAlternatives.length > 0 && (
        <section className="mb-10">
          <div className="flex items-center gap-3 mb-5">
            <div className="w-9 h-9 rounded-xl bg-gray-100 flex items-center justify-center">
              <Layers className="w-4 h-4 text-gray-600" />
            </div>
            <div>
              <h3 className="text-lg font-black text-gray-900">
                {hasExactMatch ? "Alternatives" : "Recommended Alternatives"}
              </h3>
              <p className="text-xs text-gray-500">
                {hasExactMatch
                  ? "Other strong options worth considering"
                  : `${displayAlternatives.length} nearest matches from our inventory`}
              </p>
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 min-w-0">
            {displayAlternatives.map((alt, i) => (
              <WizardResultCard
                key={alt.car.id}
                match={alt}
                rank={hasExactMatch ? i + 2 : i + 1}
                budgetMin={budgetMin}
                budgetMax={budgetMax}
                fuelTypes={fuelTypes}
                bodyTypes={bodyTypes}
                familySize={familySize}
              />
            ))}
          </div>
        </section>
      )}

      {/* Empty after fallback attempt */}
      {!loadingFallback && !hasExactMatch && displayAlternatives.length === 0 && (
        <div className="rounded-2xl bg-white border border-gray-200 p-8 sm:p-12 text-center mb-8 shadow-sm min-w-0">
          <Car className="w-12 h-12 text-gray-300 mx-auto mb-4" />
          <h3 className="text-xl font-black text-gray-800 mb-2">No cars available yet</h3>
          <p className="text-gray-500 text-sm mb-6">
            Try widening your budget or adjusting your preferences.
          </p>
          <button
            type="button"
            onClick={onReset}
            className="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-2xl font-bold hover:bg-blue-700 transition-colors"
          >
            <RotateCcw className="w-4 h-4" /> Try Again
          </button>
        </div>
      )}

      {/* Bottom CTA */}
      {totalShown > 0 && (
        <section className="mt-12 rounded-2xl bg-gradient-to-br from-blue-600 via-indigo-600 to-purple-700 p-6 sm:p-8 md:p-10 text-center text-white shadow-[0_12px_40px_rgba(37,99,235,0.25)] min-w-0">
          <h3 className="text-xl md:text-2xl font-black mb-2 break-words">Still not sure?</h3>
          <p className="text-blue-100 text-sm mb-6 max-w-md mx-auto break-words">
            Compare your picks side-by-side, browse the full catalogue, or chat with our AI car advisor.
          </p>
          <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-center gap-3 min-w-0">
            <Link
              href="/compare"
              className="inline-flex items-center gap-2 px-6 py-3 rounded-2xl bg-white text-blue-700 font-bold hover:bg-blue-50 transition-all shadow-lg sm:min-w-[160px] justify-center"
            >
              <GitCompare className="w-4 h-4" />
              Compare Cars
            </Link>
            <Link
              href="/cars"
              className="inline-flex items-center gap-2 px-6 py-3 rounded-2xl bg-white/15 backdrop-blur border border-white/25 text-white font-bold hover:bg-white/25 transition-all sm:min-w-[160px] justify-center"
            >
              Browse All Cars
              <ArrowRight className="w-4 h-4" />
            </Link>
            <button
              type="button"
              onClick={openCarAdvisor}
              className="inline-flex items-center gap-2 px-6 py-3 rounded-2xl bg-white/15 backdrop-blur border border-white/25 text-white font-bold hover:bg-white/25 transition-all sm:min-w-[160px] justify-center"
            >
              <MessageCircle className="w-4 h-4" />
              Talk to Car Advisor
            </button>
          </div>
        </section>
      )}

      {/* Secondary actions */}
      <div className="flex flex-col sm:flex-row items-center justify-center gap-4 pt-8">
        <button
          type="button"
          onClick={onReset}
          className="flex items-center gap-2 px-6 py-3 rounded-2xl border border-gray-200 text-gray-700 font-bold hover:border-blue-300 hover:text-blue-600 transition-all bg-white"
        >
          <RotateCcw className="w-4 h-4" />
          Start Over
        </button>
      </div>
    </div>
  );
}

function bodiesLabel(bodies: string[]): string {
  if (bodies.length <= 2) return bodies.join(" / ");
  return `${bodies.slice(0, 2).join(", ")} +${bodies.length - 2}`;
}
