"use client";

import { useState, useRef } from "react";
import {
  Sparkles, ChevronRight, ChevronLeft, Check, X as XIcon,
  Fuel, Users, Zap, Leaf, Droplets, Flame,
  RotateCcw, Loader2, IndianRupee,
} from "lucide-react";
import { wizardRecommend } from "@/lib/api";
import type { WizardInput, WizardResult } from "@/lib/types";
import { cn, formatPrice } from "@/lib/utils";
import WizardResults from "@/components/wizard/WizardResults";

// ── Constants ─────────────────────────────────────────────────────────────────
// Budget values in lakhs — matches DB storage & /cars filter API

const BUDGET_OPTIONS = [
  { key: "under_5l",  label: "Under ₹5L",   sub: "Entry level",     min: 2.0,   max: 5.0   },
  { key: "5_to_8l",   label: "₹5 – 8L",     sub: "Budget",          min: 5.0,   max: 8.0   },
  { key: "8_to_12l",  label: "₹8 – 12L",    sub: "Mid-range",       min: 8.0,   max: 12.0  },
  { key: "12_to_20l", label: "₹12 – 20L",   sub: "Upper mid",       min: 12.0,  max: 20.0  },
  { key: "20_to_40l", label: "₹20 – 40L",   sub: "Premium",         min: 20.0,  max: 40.0  },
  { key: "above_40l", label: "₹40L+",        sub: "Luxury",          min: 40.0,  max: 1000.0 },
];

const FUEL_OPTIONS = [
  { key: "Petrol",       label: "Petrol",      icon: Flame,    color: "amber",  desc: "Wide availability, lower upfront cost" },
  { key: "Diesel",       label: "Diesel",      icon: Droplets, color: "blue",   desc: "Better highway mileage, higher efficiency" },
  { key: "Electric",     label: "Electric",    icon: Zap,      color: "green",  desc: "Zero emissions, lowest running cost" },
  { key: "Hybrid",       label: "Hybrid",      icon: Leaf,     color: "teal",   desc: "Best city mileage, eco-friendly" },
  { key: "CNG",          label: "CNG",         icon: Fuel,     color: "sky",    desc: "Very low running cost, eco-friendly" },
];

const BODY_OPTIONS = [
  { key: "Hatchback", label: "Hatchback", desc: "Compact & easy to park",        emoji: "🚗" },
  { key: "Sedan",     label: "Sedan",     desc: "Boot space & premium feel",     emoji: "🚙" },
  { key: "SUV",       label: "SUV",       desc: "High ground clearance & space", emoji: "🛻" },
  { key: "MUV",       label: "MUV / Van", desc: "Maximum seating capacity",      emoji: "🚐" },
  { key: "Coupe",     label: "Coupe",     desc: "Sporty design, performance",    emoji: "🏎️" },
];

const FAMILY_OPTIONS = [
  { size: 1,  label: "Just Me",       sub: "Solo driver",         icon: "🧑" },
  { size: 2,  label: "Couple",        sub: "2 people",            icon: "👫" },
  { size: 4,  label: "Small Family",  sub: "3 – 4 people",        icon: "👨‍👩‍👧" },
  { size: 6,  label: "Large Family",  sub: "5 – 6 people",        icon: "👨‍👩‍👧‍👦" },
  { size: 7,  label: "Big Family",    sub: "7 + people",          icon: "🏠" },
];

type Step = 0 | 1 | 2 | 3;

// ── helpers ───────────────────────────────────────────────────────────────────

const COLOR: Record<string, string> = {
  amber: "bg-amber-50 border-amber-300 text-amber-700 shadow-amber-100",
  blue:  "bg-blue-50  border-blue-300  text-blue-700  shadow-blue-100",
  green: "bg-green-50 border-green-300 text-green-700 shadow-green-100",
  teal:  "bg-teal-50  border-teal-300  text-teal-700  shadow-teal-100",
  sky:   "bg-sky-50   border-sky-300   text-sky-700   shadow-sky-100",
};
const COLOR_SEL: Record<string, string> = {
  amber: "bg-amber-500 border-amber-500 text-white shadow-amber-200",
  blue:  "bg-blue-500  border-blue-500  text-white shadow-blue-200",
  green: "bg-green-500 border-green-500 text-white shadow-green-200",
  teal:  "bg-teal-500  border-teal-500  text-white shadow-teal-200",
  sky:   "bg-sky-500   border-sky-500   text-white shadow-sky-200",
};

// ── Step progress bar ─────────────────────────────────────────────────────────

function ProgressBar({ step }: { step: Step }) {
  const steps = [
    { short: "Budget", full: "Budget" },
    { short: "Fuel", full: "Fuel" },
    { short: "Body", full: "Body Type" },
    { short: "Family", full: "Family" },
  ];
  return (
    <div className="w-full mb-8 min-w-0">
      <div className="flex items-center justify-between mb-2 min-w-0">
        {steps.map((s, i) => (
          <div key={s.full} className="flex items-center flex-1 min-w-0 last:flex-none">
            <div className={cn(
              "w-8 h-8 shrink-0 rounded-full flex items-center justify-center text-xs font-black transition-all duration-300",
              i < step  ? "bg-blue-600 text-white" :
              i === step ? "bg-blue-600 text-white ring-4 ring-blue-100" :
                          "bg-gray-100 text-gray-400"
            )}>
              {i < step ? <Check className="w-4 h-4" /> : i + 1}
            </div>
            {i < steps.length - 1 && (
              <div className="flex-1 min-w-0 h-1 mx-1 sm:mx-1.5 rounded-full bg-gray-100 overflow-hidden">
                <div
                  className="h-full bg-blue-600 rounded-full transition-all duration-500"
                  style={{ width: i < step ? "100%" : "0%" }}
                />
              </div>
            )}
          </div>
        ))}
      </div>
      <div className="grid grid-cols-4 gap-1 text-[10px] font-bold text-gray-400 text-center">
        {steps.map((s) => (
          <span key={s.full} className="min-w-0 leading-tight">
            <span className="sm:hidden">{s.short}</span>
            <span className="hidden sm:inline">{s.full}</span>
          </span>
        ))}
      </div>
    </div>
  );
}

// ── Main Wizard ───────────────────────────────────────────────────────────────

export default function CarWizard() {
  const [step,        setStep]       = useState<Step>(0);
  const [budget,      setBudget]     = useState<typeof BUDGET_OPTIONS[0] | null>(null);
  const [fuels,       setFuels]      = useState<string[]>([]);
  const [bodies,      setBodies]     = useState<string[]>([]);
  const [familySize,  setFamilySize] = useState<number>(4);
  const [loading,     setLoading]    = useState(false);
  const [result,      setResult]     = useState<WizardResult | null>(null);
  const [error,       setError]      = useState<string | null>(null);
  const topRef = useRef<HTMLDivElement>(null);

  function scrollTop() {
    topRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
  }

  function toggleFuel(k: string) {
    setFuels((prev) => prev.includes(k) ? prev.filter((f) => f !== k) : [...prev, k]);
  }
  function toggleBody(k: string) {
    setBodies((prev) => prev.includes(k) ? prev.filter((b) => b !== k) : [...prev, k]);
  }

  function canAdvance() {
    if (step === 0) return budget !== null;
    return true; // fuel, body, family all optional (selecting "any" is valid)
  }

  function advance() {
    if (!canAdvance()) return;
    if (step < 3) {
      setStep((s) => (s + 1) as Step);
      scrollTop();
    } else {
      submit();
    }
  }
  function back() {
    if (step > 0) {
      setStep((s) => (s - 1) as Step);
      scrollTop();
    }
  }

  function reset() {
    setBudget(null);
    setFuels([]);
    setBodies([]);
    setFamilySize(4);
    setStep(0);
    setResult(null);
    setError(null);
    scrollTop();
  }

  async function submit() {
    if (!budget) return;
    setLoading(true);
    setError(null);
    try {
      const input: WizardInput = {
        budgetMin:  budget.min,
        budgetMax:  budget.max,
        fuelTypes:  fuels,
        bodyTypes:  bodies,
        familySize,
      };
      const res = await wizardRecommend(input);
      setResult(res);
      scrollTop();
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  }

  // ── LOADING ────────────────────────────────────────────────────────────────
  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[60vh] gap-6 min-w-0 px-4">
        <div className="relative w-20 h-20">
          <div className="absolute inset-0 rounded-full border-4 border-blue-100" />
          <div className="absolute inset-0 rounded-full border-4 border-blue-600 border-t-transparent animate-spin" />
          <Sparkles className="absolute inset-0 m-auto w-7 h-7 text-blue-600" />
        </div>
        <div className="text-center">
          <p className="text-xl font-black text-gray-900">Analysing your needs…</p>
          <p className="text-sm text-gray-400 mt-1">Finding the perfect car for you…</p>
        </div>
      </div>
    );
  }

  // ── RESULTS ────────────────────────────────────────────────────────────────
  if (result) {
    return (
      <div ref={topRef} className="w-full max-w-7xl mx-auto min-w-0">
        <WizardResults
          result={result}
          budgetMin={budget!.min}
          budgetMax={budget!.max}
          fuelTypes={fuels}
          bodyTypes={bodies}
          familySize={familySize}
          onReset={reset}
        />
      </div>
    );
  }

  // ── WIZARD STEPS ───────────────────────────────────────────────────────────
  return (
    <div ref={topRef} className="w-full max-w-2xl mx-auto min-w-0 rounded-[36px] bg-white border border-gray-200/60 shadow-[0_20px_60px_rgba(0,0,0,0.08)] p-4 sm:p-6 md:p-10">
      <ProgressBar step={step} />

      {/* ── STEP 0: Budget ── */}
      {step === 0 && (
        <div>
          <h2 className="text-2xl font-black text-gray-900 mb-1">What&apos;s your budget?</h2>
          <p className="text-sm text-gray-400 mb-6">We&apos;ll filter by ex-showroom price</p>
          <div className="grid grid-cols-1 xs:grid-cols-2 sm:grid-cols-3 gap-3 min-w-0">
            {BUDGET_OPTIONS.map((opt) => {
              const sel = budget?.key === opt.key;
              return (
                <button
                  key={opt.key}
                  onClick={() => setBudget(opt)}
                  className={cn(
                    "min-w-0 rounded-2xl border-2 p-4 text-left transition-all duration-200",
                    sel
                      ? "border-blue-500 bg-blue-50 shadow-lg shadow-blue-100"
                      : "border-gray-100 bg-white hover:border-blue-200 hover:shadow-md"
                  )}
                >
                  <div className="flex items-center justify-between mb-1">
                    <IndianRupee className={cn("w-4 h-4", sel ? "text-blue-600" : "text-gray-400")} />
                    {sel && <Check className="w-4 h-4 text-blue-600" />}
                  </div>
                  <p className={cn("text-base font-black break-words", sel ? "text-blue-700" : "text-gray-900")}>
                    {opt.label}
                  </p>
                  <p className="text-[11px] text-gray-400 mt-0.5">{opt.sub}</p>
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* ── STEP 1: Fuel type ── */}
      {step === 1 && (
        <div>
          <h2 className="text-2xl font-black text-gray-900 mb-1">Preferred fuel type?</h2>
          <p className="text-sm text-gray-400 mb-6">Select all that work for you · skip to see all</p>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 min-w-0">
            {FUEL_OPTIONS.map(({ key, label, icon: Icon, color, desc }) => {
              const sel = fuels.includes(key);
              return (
                <button
                  key={key}
                  onClick={() => toggleFuel(key)}
                  className={cn(
                    "min-w-0 rounded-2xl border-2 p-4 text-left transition-all duration-200 shadow-sm",
                    sel ? COLOR_SEL[color] : `${COLOR[color]} hover:shadow-md`
                  )}
                >
                  <div className="flex items-center justify-between mb-2">
                    <div className={cn(
                      "w-9 h-9 rounded-xl flex items-center justify-center",
                      sel ? "bg-white/20" : "bg-white"
                    )}>
                      <Icon className="w-5 h-5" />
                    </div>
                    {sel && <Check className="w-4 h-4" />}
                  </div>
                  <p className="font-black text-base break-words">{label}</p>
                  <p className={cn("text-[11px] mt-0.5 break-words", sel ? "opacity-80" : "opacity-60")}>{desc}</p>
                </button>
              );
            })}
          </div>
          <p className="text-[11px] text-gray-400 text-center mt-4">
            Nothing selected = show all fuel types
          </p>
        </div>
      )}

      {/* ── STEP 2: Body type ── */}
      {step === 2 && (
        <div>
          <h2 className="text-2xl font-black text-gray-900 mb-1">What type of car?</h2>
          <p className="text-sm text-gray-400 mb-6">Select one or more · skip for any</p>
          <div className="grid grid-cols-1 xs:grid-cols-2 sm:grid-cols-3 gap-3 min-w-0">
            {BODY_OPTIONS.map(({ key, label, desc, emoji }) => {
              const sel = bodies.includes(key);
              return (
                <button
                  key={key}
                  onClick={() => toggleBody(key)}
                  className={cn(
                    "min-w-0 rounded-2xl border-2 p-4 text-left transition-all duration-200",
                    sel
                      ? "border-blue-500 bg-blue-50 shadow-lg shadow-blue-100"
                      : "border-gray-100 bg-white hover:border-blue-200 hover:shadow-md"
                  )}
                >
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-2xl">{emoji}</span>
                    {sel && <Check className="w-4 h-4 text-blue-600" />}
                  </div>
                  <p className={cn("font-black text-sm break-words", sel ? "text-blue-700" : "text-gray-900")}>
                    {label}
                  </p>
                  <p className="text-[11px] text-gray-400 mt-0.5 break-words">{desc}</p>
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* ── STEP 3: Family size ── */}
      {step === 3 && (
        <div>
          <h2 className="text-2xl font-black text-gray-900 mb-1">How big is your family?</h2>
          <p className="text-sm text-gray-400 mb-6">We&apos;ll recommend cars with adequate seating</p>
          <div className="grid grid-cols-1 xs:grid-cols-2 sm:grid-cols-3 gap-3 min-w-0">
            {FAMILY_OPTIONS.map(({ size, label, sub, icon }) => {
              const sel = familySize === size;
              return (
                <button
                  key={size}
                  onClick={() => setFamilySize(size)}
                  className={cn(
                    "min-w-0 rounded-2xl border-2 p-5 text-left transition-all duration-200",
                    sel
                      ? "border-blue-500 bg-blue-50 shadow-lg shadow-blue-100"
                      : "border-gray-100 bg-white hover:border-blue-200 hover:shadow-md"
                  )}
                >
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-3xl">{icon}</span>
                    {sel && <Check className="w-4 h-4 text-blue-600" />}
                  </div>
                  <p className={cn("font-black break-words", sel ? "text-blue-700" : "text-gray-900")}>
                    {label}
                  </p>
                  <p className="text-[11px] text-gray-400 mt-0.5 break-words">{sub}</p>
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* Error */}
      {error && (
        <div className="mt-4 rounded-2xl bg-red-50 border border-red-200 px-4 py-3 text-sm text-red-700 flex items-start gap-2 min-w-0">
          <XIcon className="w-4 h-4 shrink-0 mt-0.5" />
          <span className="min-w-0 break-words">{error}</span>
        </div>
      )}

      {/* ── Navigation buttons ── */}
      <div className="flex items-center justify-between gap-2 mt-8 pt-6 border-t border-gray-100 min-w-0">
        <button
          onClick={back}
          disabled={step === 0}
          className={cn(
            "flex items-center gap-2 px-4 sm:px-5 py-3 rounded-2xl font-bold text-sm transition-all shrink-0",
            step === 0
              ? "opacity-0 pointer-events-none"
              : "border border-gray-200 text-gray-600 hover:border-gray-300 hover:bg-gray-50"
          )}
        >
          <ChevronLeft className="w-4 h-4" />
          Back
        </button>

        <button
          onClick={advance}
          disabled={!canAdvance()}
          className={cn(
            "flex items-center gap-2 px-4 sm:px-7 py-3 rounded-2xl font-black text-sm transition-all shadow-lg min-w-0",
            canAdvance()
              ? "bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-blue-200 hover:shadow-blue-300 hover:scale-[1.02]"
              : "bg-gray-100 text-gray-400 cursor-not-allowed shadow-none"
          )}
        >
          {step === 3 ? (
            <><Sparkles className="w-4 h-4" /> Find My Car</>
          ) : (
            <>Next <ChevronRight className="w-4 h-4" /></>
          )}
        </button>
      </div>

      {/* Skip hint for optional steps */}
      {step > 0 && step < 3 && (
        <p className="text-center text-[11px] text-gray-400 mt-3">
          No preference? Just click <strong>Next</strong> to skip this step
        </p>
      )}
    </div>
  );
}
