"use client";

import { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { Bot, ChevronRight, Loader2, Lightbulb, AlertCircle, Star, ShoppingCart, ArrowLeft, CheckCircle2 } from "lucide-react";
import { useCartStore } from "@/store/cart";
import { formatPrice } from "@/lib/utils";
import { cn } from "@/lib/utils";
import toast from "react-hot-toast";

const purposes = [
  { value: "student", label: "Student / General Use", emoji: "📚", desc: "Assignments, browsing, documents" },
  { value: "business", label: "Business & Office", emoji: "💼", desc: "Emails, spreadsheets, video calls" },
  { value: "programming", label: "Programming & Dev", emoji: "👨‍💻", desc: "Coding, virtual machines, Docker" },
  { value: "gaming", label: "Gaming", emoji: "🎮", desc: "AAA games, high frame rates" },
  { value: "design", label: "Graphic Design & Video", emoji: "🎨", desc: "Photoshop, Premiere, 3D rendering" },
  { value: "content", label: "Content Creation", emoji: "📸", desc: "Photo/video editing, streaming" },
];

const budgetOptions = [
  { value: 30000, label: "Under KES 30,000", sub: "Entry level" },
  { value: 50000, label: "KES 30,000 – 50,000", sub: "Mid-range" },
  { value: 80000, label: "KES 50,000 – 80,000", sub: "Upper mid-range" },
  { value: 120000, label: "KES 80,000 – 120,000", sub: "High-end" },
  { value: 200000, label: "KES 120,000 – 200,000", sub: "Premium" },
  { value: 999999, label: "Above KES 200,000", sub: "Flagship" },
];

const priorities = [
  { value: "performance", label: "Performance", emoji: "⚡" },
  { value: "battery", label: "Battery Life", emoji: "🔋" },
  { value: "portability", label: "Portability", emoji: "🎒" },
  { value: "display", label: "Display Quality", emoji: "🖥️" },
  { value: "storage", label: "Large Storage", emoji: "💾" },
  { value: "value", label: "Value for Money", emoji: "💰" },
];

type Step = "purpose" | "budget" | "priorities" | "result";

interface AIProduct {
  id: string;
  name: string;
  slug: string;
  price: number;
  images: string[];
  stock: number;
  brand: { name: string };
  reviews?: { rating: number }[];
}

interface Recommendation {
  topPick: { productId: string; reason: string } | null;
  alternatives: { productId: string; reason: string }[];
  explanation: string;
  tips: string[];
  warnings: string[];
}

export default function AIFinderPage() {
  const [step, setStep] = useState<Step>("purpose");
  const [purpose, setPurpose] = useState("");
  const [budget, setBudget] = useState(0);
  const [selectedPriorities, setSelectedPriorities] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [recommendation, setRecommendation] = useState<Recommendation | null>(null);
  const [products, setProducts] = useState<AIProduct[]>([]);
  const { addItem } = useCartStore();

  const togglePriority = (val: string) => {
    setSelectedPriorities((prev) =>
      prev.includes(val) ? prev.filter((p) => p !== val) : prev.length < 3 ? [...prev, val] : prev
    );
  };

  const handleSubmit = async () => {
    setLoading(true);
    setStep("result");
    try {
      const res = await fetch("/api/ai/recommend", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          purpose,
          budget,
          preferences: { priorities: selectedPriorities },
          sessionId: Math.random().toString(36).slice(2),
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error);
      setRecommendation(data.recommendation);
      setProducts(data.products || []);
    } catch (e) {
      const msg = (e as Error).message || "Failed to get recommendations. Please try again.";
      toast.error(msg);
      setStep("priorities");
    } finally {
      setLoading(false);
    }
  };

  const getProductById = (id: string) => products.find((p) => p.id === id);

  const handleAddToCart = (product: AIProduct) => {
    addItem({
      id: product.id,
      name: product.name,
      price: product.price,
      image: product.images[0] || "/images/placeholder.png",
      slug: product.slug,
      stock: product.stock,
    });
    toast.success("Added to cart!");
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-sky-50 via-white to-blue-50">
      <div className="max-w-3xl mx-auto px-4 py-12">
        {/* Header */}
        <div className="text-center mb-10">
          <div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-sky-500 to-blue-600 flex items-center justify-center mx-auto mb-4 shadow-xl shadow-sky-200">
            <Bot className="w-8 h-8 text-white" />
          </div>
          <h1 className="text-3xl sm:text-4xl font-black text-slate-900 mb-2">Smart Laptop Finder</h1>
          <p className="text-slate-500 max-w-lg mx-auto">
            Answer a few quick questions and we&apos;ll match the perfect laptop from our stock to your needs and budget.
          </p>
        </div>

        {/* Progress */}
        {step !== "result" && (
          <div className="flex items-center gap-2 mb-8 justify-center">
            {(["purpose", "budget", "priorities"] as Step[]).map((s, i) => (
              <div key={s} className="flex items-center gap-2">
                <div className={cn("w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold transition-all",
                  step === s ? "bg-sky-500 text-white shadow-lg shadow-sky-200" :
                  ["purpose", "budget", "priorities"].indexOf(step) > i ? "bg-sky-100 text-sky-600" : "bg-slate-100 text-slate-400"
                )}>
                  {["purpose", "budget", "priorities"].indexOf(step) > i ? <CheckCircle2 className="w-4 h-4" /> : i + 1}
                </div>
                {i < 2 && <div className={cn("w-16 h-0.5 rounded-full", ["purpose", "budget", "priorities"].indexOf(step) > i ? "bg-sky-300" : "bg-slate-200")} />}
              </div>
            ))}
          </div>
        )}

        {/* Step 1: Purpose */}
        {step === "purpose" && (
          <div className="bg-white rounded-3xl shadow-xl shadow-sky-100/50 p-6 sm:p-8 border border-sky-100">
            <h2 className="text-xl font-black text-slate-800 mb-2">What will you mainly use it for?</h2>
            <p className="text-slate-500 text-sm mb-6">Select the primary use case</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {purposes.map((p) => (
                <button
                  key={p.value}
                  onClick={() => setPurpose(p.value)}
                  className={cn("flex items-center gap-4 p-4 rounded-2xl border-2 text-left transition-all",
                    purpose === p.value
                      ? "border-sky-500 bg-sky-50 shadow-lg shadow-sky-100"
                      : "border-slate-100 hover:border-sky-200 hover:bg-sky-50/50"
                  )}
                >
                  <span className="text-3xl">{p.emoji}</span>
                  <div>
                    <p className="font-bold text-slate-800 text-sm">{p.label}</p>
                    <p className="text-slate-500 text-xs">{p.desc}</p>
                  </div>
                  {purpose === p.value && <CheckCircle2 className="w-5 h-5 text-sky-500 ml-auto shrink-0" />}
                </button>
              ))}
            </div>
            <button
              onClick={() => setStep("budget")}
              disabled={!purpose}
              className="mt-6 w-full bg-sky-500 hover:bg-sky-600 disabled:bg-slate-200 disabled:text-slate-400 text-white font-bold py-3.5 rounded-xl transition-all flex items-center justify-center gap-2"
            >
              Next: Set Budget <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        )}

        {/* Step 2: Budget */}
        {step === "budget" && (
          <div className="bg-white rounded-3xl shadow-xl shadow-sky-100/50 p-6 sm:p-8 border border-sky-100">
            <button onClick={() => setStep("purpose")} className="flex items-center gap-1 text-sky-600 text-sm font-medium mb-4 hover:text-sky-700">
              <ArrowLeft className="w-4 h-4" /> Back
            </button>
            <h2 className="text-xl font-black text-slate-800 mb-2">What is your budget?</h2>
            <p className="text-slate-500 text-sm mb-6">Select your price range in Kenyan Shillings</p>
            <div className="space-y-3">
              {budgetOptions.map((b) => (
                <button
                  key={b.value}
                  onClick={() => setBudget(b.value)}
                  className={cn("w-full flex items-center justify-between p-4 rounded-2xl border-2 text-left transition-all",
                    budget === b.value
                      ? "border-sky-500 bg-sky-50 shadow-lg shadow-sky-100"
                      : "border-slate-100 hover:border-sky-200 hover:bg-sky-50/50"
                  )}
                >
                  <div>
                    <p className="font-bold text-slate-800 text-sm">{b.label}</p>
                    <p className="text-slate-500 text-xs">{b.sub}</p>
                  </div>
                  {budget === b.value && <CheckCircle2 className="w-5 h-5 text-sky-500" />}
                </button>
              ))}
            </div>
            <button
              onClick={() => setStep("priorities")}
              disabled={!budget}
              className="mt-6 w-full bg-sky-500 hover:bg-sky-600 disabled:bg-slate-200 disabled:text-slate-400 text-white font-bold py-3.5 rounded-xl transition-all flex items-center justify-center gap-2"
            >
              Next: Priorities <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        )}

        {/* Step 3: Priorities */}
        {step === "priorities" && (
          <div className="bg-white rounded-3xl shadow-xl shadow-sky-100/50 p-6 sm:p-8 border border-sky-100">
            <button onClick={() => setStep("budget")} className="flex items-center gap-1 text-sky-600 text-sm font-medium mb-4 hover:text-sky-700">
              <ArrowLeft className="w-4 h-4" /> Back
            </button>
            <h2 className="text-xl font-black text-slate-800 mb-2">What matters most to you?</h2>
            <p className="text-slate-500 text-sm mb-6">Select up to 3 priorities (optional)</p>
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
              {priorities.map((p) => (
                <button
                  key={p.value}
                  onClick={() => togglePriority(p.value)}
                  className={cn("flex flex-col items-center gap-2 p-4 rounded-2xl border-2 transition-all",
                    selectedPriorities.includes(p.value)
                      ? "border-sky-500 bg-sky-50 shadow-lg shadow-sky-100"
                      : "border-slate-100 hover:border-sky-200"
                  )}
                >
                  <span className="text-2xl">{p.emoji}</span>
                  <span className="text-xs font-bold text-slate-700 text-center">{p.label}</span>
                </button>
              ))}
            </div>
            <div className="mt-6 p-4 bg-sky-50 rounded-xl border border-sky-100 flex gap-3">
              <Bot className="w-5 h-5 text-sky-500 shrink-0 mt-0.5" />
              <p className="text-sm text-sky-700">
                We&apos;ll match laptops from our live stock to your budget and preferences instantly.
              </p>
            </div>
            <button
              onClick={handleSubmit}
              className="mt-4 w-full bg-gradient-to-r from-sky-600 to-blue-600 hover:from-sky-500 hover:to-blue-500 text-white font-bold py-4 rounded-xl transition-all flex items-center justify-center gap-2 shadow-lg shadow-sky-200"
            >
              <Bot className="w-5 h-5" /> Find My Laptop
            </button>
          </div>
        )}

        {/* Step 4: Results */}
        {step === "result" && (
          <div className="space-y-6">
            {loading ? (
              <div className="bg-white rounded-3xl shadow-xl shadow-sky-100/50 p-12 border border-sky-100 text-center">
                <Loader2 className="w-12 h-12 text-sky-500 animate-spin mx-auto mb-4" />
                <h3 className="text-xl font-bold text-slate-800 mb-2">Finding your match...</h3>
                <p className="text-slate-500 text-sm">Searching our stock for laptops within your budget</p>
              </div>
            ) : recommendation ? (
              <>
                {/* Top Pick */}
                {recommendation.topPick && (() => {
                  const product = getProductById(recommendation.topPick.productId);
                  const avgRating = product?.reviews?.length
                    ? product.reviews.reduce((s, r) => s + r.rating, 0) / product.reviews.length
                    : null;
                  return (
                    <div className="bg-white rounded-3xl shadow-xl shadow-sky-100/50 border-2 border-sky-500 overflow-hidden">
                      <div className="bg-gradient-to-r from-sky-600 to-blue-600 px-6 py-3 flex items-center gap-2">
                        <Star className="w-4 h-4 text-yellow-300 fill-yellow-300" />
                        <span className="text-white font-bold text-sm">Top Pick — Best Match For Your Budget</span>
                      </div>
                      {product ? (
                        <div className="p-6 flex flex-col sm:flex-row gap-5">
                          <div className="relative w-full sm:w-40 h-40 rounded-2xl overflow-hidden bg-slate-50 shrink-0">
                            <Image
                              src={product.images[0] || "/images/placeholder.png"}
                              alt={product.name}
                              fill
                              className="object-cover"
                            />
                          </div>
                          <div className="flex-1">
                            <p className="text-xs text-sky-600 font-bold mb-1">{product.brand.name}</p>
                            <h3 className="text-lg font-black text-slate-900 mb-2">{product.name}</h3>
                            {avgRating && (
                              <div className="flex items-center gap-1 mb-2">
                                {[1,2,3,4,5].map((s) => (
                                  <Star key={s} className={cn("w-3.5 h-3.5", s <= Math.round(avgRating) ? "text-amber-400 fill-amber-400" : "text-slate-200")} />
                                ))}
                                <span className="text-xs text-slate-500">({product.reviews?.length})</span>
                              </div>
                            )}
                            <div className="bg-sky-50 rounded-xl p-3 mb-4">
                              <p className="text-sm text-sky-800 font-medium">
                                <Bot className="w-4 h-4 inline mr-1 text-sky-500" />
                                {recommendation.topPick.reason}
                              </p>
                            </div>
                            <div className="flex items-center gap-3 flex-wrap">
                              <span className="text-2xl font-black text-slate-900">{formatPrice(product.price)}</span>
                              <div className="flex gap-2">
                                <button
                                  onClick={() => handleAddToCart(product)}
                                  className="flex items-center gap-2 bg-sky-500 hover:bg-sky-600 text-white px-4 py-2 rounded-xl font-bold text-sm transition-all"
                                >
                                  <ShoppingCart className="w-4 h-4" /> Add to Cart
                                </button>
                                <Link href={`/products/${product.slug}`} className="flex items-center gap-2 border-2 border-sky-500 text-sky-600 px-4 py-2 rounded-xl font-bold text-sm hover:bg-sky-50 transition-all">
                                  View Details
                                </Link>
                              </div>
                            </div>
                          </div>
                        </div>
                      ) : (
                        <div className="p-6 text-center text-slate-500">
                          <p>Top pick details loading...</p>
                          <p className="text-sm mt-2">{recommendation.topPick.reason}</p>
                        </div>
                      )}
                    </div>
                  );
                })()}

                {/* Explanation */}
                <div className="bg-white rounded-3xl shadow-xl shadow-sky-100/50 p-6 border border-sky-100">
                  <div className="flex items-center gap-2 mb-3">
                    <Bot className="w-5 h-5 text-sky-500" />
                    <h3 className="font-bold text-slate-800">Match Summary</h3>
                  </div>
                  <p className="text-slate-600 text-sm leading-relaxed">{recommendation.explanation}</p>
                </div>

                {/* Tips */}
                {recommendation.tips?.length > 0 && (
                  <div className="bg-emerald-50 rounded-3xl p-6 border border-emerald-100">
                    <div className="flex items-center gap-2 mb-4">
                      <Lightbulb className="w-5 h-5 text-emerald-600" />
                      <h3 className="font-bold text-emerald-800">Expert Tips</h3>
                    </div>
                    <ul className="space-y-2">
                      {recommendation.tips.map((tip, i) => (
                        <li key={i} className="flex items-start gap-2 text-sm text-emerald-700">
                          <CheckCircle2 className="w-4 h-4 text-emerald-500 mt-0.5 shrink-0" />
                          {tip}
                        </li>
                      ))}
                    </ul>
                  </div>
                )}

                {/* Warnings */}
                {recommendation.warnings?.length > 0 && (
                  <div className="bg-amber-50 rounded-3xl p-6 border border-amber-100">
                    <div className="flex items-center gap-2 mb-4">
                      <AlertCircle className="w-5 h-5 text-amber-600" />
                      <h3 className="font-bold text-amber-800">Things to Consider</h3>
                    </div>
                    <ul className="space-y-2">
                      {recommendation.warnings.map((warning, i) => (
                        <li key={i} className="flex items-start gap-2 text-sm text-amber-700">
                          <AlertCircle className="w-4 h-4 text-amber-500 mt-0.5 shrink-0" />
                          {warning}
                        </li>
                      ))}
                    </ul>
                  </div>
                )}

                {/* Alternatives */}
                {recommendation.alternatives?.length > 0 && products.length > 1 && (
                  <div className="bg-white rounded-3xl shadow-xl shadow-sky-100/50 p-6 border border-sky-100">
                    <h3 className="font-black text-slate-800 mb-4">Alternative Options</h3>
                    <div className="space-y-4">
                      {recommendation.alternatives.map((alt) => {
                        const product = getProductById(alt.productId);
                        if (!product) return null;
                        return (
                          <div key={alt.productId} className="flex gap-4 p-4 bg-slate-50 rounded-2xl">
                            <div className="relative w-20 h-20 rounded-xl overflow-hidden bg-white shrink-0">
                              <Image src={product.images[0] || "/images/placeholder.png"} alt={product.name} fill className="object-cover" />
                            </div>
                            <div className="flex-1 min-w-0">
                              <p className="text-xs text-sky-600 font-bold">{product.brand.name}</p>
                              <h4 className="font-bold text-slate-800 text-sm line-clamp-1">{product.name}</h4>
                              <p className="text-xs text-slate-500 mt-1 line-clamp-2">{alt.reason}</p>
                              <div className="flex items-center gap-2 mt-2">
                                <span className="font-black text-slate-900 text-sm">{formatPrice(product.price)}</span>
                                <Link href={`/products/${product.slug}`} className="text-sky-600 text-xs font-bold hover:underline">View →</Link>
                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                <button
                  onClick={() => { setStep("purpose"); setPurpose(""); setBudget(0); setSelectedPriorities([]); setRecommendation(null); setProducts([]); }}
                  className="w-full border-2 border-sky-300 text-sky-600 py-3 rounded-xl font-bold hover:bg-sky-50 transition-colors"
                >
                  Start New Search
                </button>
              </>
            ) : null}
          </div>
        )}
      </div>
    </div>
  );
}
