import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import Link from "next/link";
import {
  MapPin,
  ArrowLeft,
  Phone,
  MessageCircle,
  X,
} from "lucide-react";

export default function ClassifiedDetailsPage() {
  const router = useRouter();
  const { id } = router.query;

  const [ad, setAd] = useState(null);
  const [loading, setLoading] = useState(true);
  const [activeImage, setActiveImage] = useState(0);
  const [showOrderModal, setShowOrderModal] = useState(false);
  const [placingOrder, setPlacingOrder] = useState(false);

  const [orderForm, setOrderForm] = useState({
    name: "",
    phone: "",
    message: "",
  });

  /* ---------------- Dummy Ads (fallback) ---------------- */
  const dummyADS = [
    {
      id: "1",
      title: "iPhone 15 Pro Max 256GB - Space Black",
      price: "850",
      condition: "Like New",
      city: "New York",
      createdAt: "2026-01-10T14:30:00Z",
      description:
        "Almost brand new iPhone 15 Pro Max. Used for only 1 month. No scratches, battery health 100%, box and accessories included.",
      features: [
        "256GB Storage",
        "Battery Health 100%",
        "Original Charger & Box",
        "Unlocked",
      ],
      images: [
        "https://images.unsplash.com/photo-1695048133142-1a20484d2569?w=1000&q=80",
        "https://images.unsplash.com/photo-1510557880182-3d4d3cba35a5?w=1000&q=80",
        "https://images.unsplash.com/photo-1511707171634-5f897ff02aa9?w=1000&q=80",
      ],
      seller: {
        name: "John Doe",
        phone: "+15551234567",
        whatsapp: "+15551234567",
      },
    },
  ];

  /* ---------------- Fetch Ad Details ---------------- */
  useEffect(() => {
    if (!id) return;

    const fetchAd = async () => {
      try {
        const res = await fetch(`/api/classifieds/ads/${id}`);

        if (!res.ok) throw new Error("API not found");

        const data = await res.json();
        setAd(data.ad);
      } catch (err) {
        console.warn("Using dummy ad fallback");
        const fallback = dummyADS.find((a) => a.id === id);
        setAd(fallback || null);
      } finally {
        setLoading(false);
      }
    };

    fetchAd();
  }, [id]);

  /* ---------------- Place Order ---------------- */
  const placeOrder = async () => {
    setPlacingOrder(true);
    try {
      const res = await fetch("/api/classifieds/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          adId: ad.id,
          ...orderForm,
        }),
      });

      if (!res.ok) throw new Error("Order failed");

      alert("Order placed successfully!");
      setShowOrderModal(false);
    } catch (err) {
      alert("Failed to place order. Please try again.");
    } finally {
      setPlacingOrder(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center text-gray-500">
        Loading ad details...
      </div>
    );
  }

  if (!ad) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center">
        <p className="text-gray-500 mb-4">Ad not found</p>
        <Link href="/classifieds" className="text-green-600 hover:underline">
          Back to classifieds
        </Link>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm">
        <div className="container mx-auto px-4 py-4">
          <button
            onClick={() => router.back()}
            className="flex items-center gap-1 text-green-600 hover:underline"
          >
            <ArrowLeft className="w-4 h-4" />
            Back to listings
          </button>
        </div>
      </header>

      <div className="container mx-auto px-4 py-8 grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Image Gallery */}
          <div className="bg-white rounded-lg shadow p-4">
            <img
              src={ad.images[activeImage]}
              className="w-full h-96 object-cover rounded-lg"
              alt={ad.title}
            />
            <div className="flex gap-3 mt-4">
              {ad.images.map((img, i) => (
                <img
                  key={i}
                  src={img}
                  onClick={() => setActiveImage(i)}
                  className={`w-20 h-20 object-cover rounded cursor-pointer border ${
                    activeImage === i
                      ? "border-green-600"
                      : "border-gray-300"
                  }`}
                />
              ))}
            </div>
          </div>

          {/* Description */}
          <div className="bg-white rounded-lg shadow p-6">
            <h1 className="text-2xl font-bold text-gray-800 mb-2">
              {ad.title}
            </h1>

            <div className="flex items-center text-gray-600 mb-4">
              <MapPin className="w-4 h-4 mr-1" />
              {ad.city}
            </div>

            <p className="text-gray-700 leading-relaxed mb-4">
              {ad.description}
            </p>

            {ad.features && (
              <>
                <h3 className="font-semibold mb-2">Features</h3>
                <ul className="list-disc list-inside text-gray-700 space-y-1">
                  {ad.features.map((f, i) => (
                    <li key={i}>{f}</li>
                  ))}
                </ul>
              </>
            )}
          </div>
        </div>

        {/* Right Sidebar */}
        <aside className="space-y-6">
          {/* Price Card */}
          <div className="bg-white rounded-lg shadow p-6">
            <p className="text-3xl font-bold text-green-600 mb-2">
              ${ad.price}
            </p>
            <span className="inline-block px-3 py-1 text-sm bg-green-100 text-green-700 rounded-full mb-4">
              {ad.condition}
            </span>

            <button
              onClick={() => setShowOrderModal(true)}
              className="w-full py-3 bg-green-600 text-white rounded-lg hover:bg-green-700"
            >
              Place Order
            </button>
          </div>

          {/* Contact Seller */}
          <div className="bg-white rounded-lg shadow p-6">
            <h3 className="font-bold mb-4">Contact Seller</h3>

            <a
              href={`tel:${ad.seller.phone}`}
              className="flex items-center gap-2 mb-3 text-green-600 hover:underline"
            >
              <Phone className="w-4 h-4" />
              Call Seller
            </a>

            <a
              href={`https://wa.me/${ad.seller.whatsapp}`}
              target="_blank"
              className="flex items-center gap-2 text-green-600 hover:underline"
            >
              <MessageCircle className="w-4 h-4" />
              WhatsApp Chat
            </a>
          </div>
        </aside>
      </div>

      {/* Order Modal */}
      {showOrderModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow w-full max-w-md p-6 relative">
            <button
              onClick={() => setShowOrderModal(false)}
              className="absolute right-3 top-3 text-gray-500"
            >
              <X />
            </button>

            <h2 className="text-xl font-bold mb-4">Place Order</h2>

            <input
              placeholder="Your Name"
              className="w-full mb-3 px-4 py-2 border rounded-lg"
              onChange={(e) =>
                setOrderForm({ ...orderForm, name: e.target.value })
              }
            />

            <input
              placeholder="Phone Number"
              className="w-full mb-3 px-4 py-2 border rounded-lg"
              onChange={(e) =>
                setOrderForm({ ...orderForm, phone: e.target.value })
              }
            />

            <textarea
              placeholder="Message"
              rows="3"
              className="w-full mb-4 px-4 py-2 border rounded-lg"
              onChange={(e) =>
                setOrderForm({ ...orderForm, message: e.target.value })
              }
            />

            <button
              onClick={placeOrder}
              disabled={placingOrder}
              className="w-full py-3 bg-green-600 text-white rounded-lg hover:bg-green-700"
            >
              {placingOrder ? "Placing Order..." : "Confirm Order"}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
