import React, { useMemo, useState, useEffect } from "react";
import { useSearchParams, Link } from "react-router-dom";
import { 
  Calendar, MapPin, Users, Luggage, ShieldCheck, 
  ArrowLeft, Info, CheckCircle2, Loader2, X, 
  ChevronRight, ArrowRight, User, Phone 
} from "lucide-react";
import Navbar from "../components/Navbar/Navbar";
import Footer from "../components/Footer/Footer";
import { api } from "../lib/api";

// Import local assets
import innovaCrystaImg from "../assets/vehicles/innova_crysta.png";
import innovaImg from "../assets/vehicles/innova.png";
import fortunerImg from "../assets/vehicles/fortuner.png";
import dzireImg from "../assets/vehicles/dzire.png"; 
import etiosImg from "../assets/vehicles/etios.png"; 
import audiA6Img from "../assets/vehicles/audi_a6.png";
import audiQ7Img from "../assets/vehicles/audi_q7.png";
import bmw5Img from "../assets/vehicles/bmw_5_series.png";
import bmw7Img from "../assets/vehicles/bmw_7_series.png";
import camryImg from "../assets/vehicles/camry.png";
import corollaImg from "../assets/vehicles/corolla_altis.png";
import mercEImg from "../assets/vehicles/mercedes_e_class.png";
import mercSImg from "../assets/vehicles/mercedes_s_class.png";
import commuterImg from "../assets/vehicles/toyota_commuter.png";

const carImages = {
  innova_crysta: innovaCrystaImg,
  innova: innovaImg,
  fortuner: fortunerImg,
  dzire: dzireImg,
  etios: etiosImg,
  audi_a6: audiA6Img,
  audi_q7: audiQ7Img,
  bmw_5_series: bmw5Img,
  bmw_7_series: bmw7Img,
  camry: camryImg,
  corolla_altis: corollaImg,
  mercedes_e_class: mercEImg,
  mercedes_s_class: mercSImg,
  toyota_commuter: commuterImg,
  ertiga: dzireImg, // Fallback
};

const LeadCaptureModal = ({ isOpen, onSubmit, searchData }) => {
  const [name, setName] = useState("");
  const [mobile, setMobile] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  if (!isOpen) return null;

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    try {
      await api.post("/api/leads", {
        name,
        mobile_number: mobile,
        tripType: searchData.tripType,
        pickupLocation: searchData.pickup,
        dropLocation: searchData.drop
      });
      onSubmit();
    } catch (err) {
      console.error("Lead Error:", err);
      // Still allow them to see results even if lead fails, or show error
      onSubmit();
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[150] flex items-center justify-center p-4 bg-dark-900/40 backdrop-blur-md animate-fadeIn">
      <div className="bg-white rounded-3xl p-8 max-w-md w-full shadow-2xl animate-scaleIn">
        <div className="text-center mb-8">
          <div className="w-16 h-16 bg-primary-50 rounded-2xl flex items-center justify-center mx-auto mb-4">
            <User className="w-8 h-8 text-primary-600" />
          </div>
          <h2 className="text-2xl font-black text-dark-900 mb-2">Check Special Prices</h2>
          <p className="text-gray-500 text-sm">Enter your details to view exclusive discounted rates for your trip.</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="relative">
            <User className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              required
              type="text"
              placeholder="Your Full Name"
              className="w-full pl-12 pr-4 py-4 bg-gray-50 border border-gray-100 rounded-2xl outline-none focus:border-primary-600 focus:bg-white transition-all font-semibold"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </div>
          <div className="relative">
            <Phone className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              required
              type="tel"
              placeholder="Mobile Number"
              className="w-full pl-12 pr-4 py-4 bg-gray-50 border border-gray-100 rounded-2xl outline-none focus:border-primary-600 focus:bg-white transition-all font-semibold"
              value={mobile}
              onChange={(e) => setMobile(e.target.value)}
            />
          </div>
          
          <button
            type="submit"
            disabled={isSubmitting}
            className="w-full bg-primary-600 hover:bg-primary-700 text-white font-black py-4 rounded-2xl transition-all shadow-lg shadow-primary-600/20 flex items-center justify-center gap-2 group"
          >
            {isSubmitting ? <Loader2 className="w-5 h-5 animate-spin" /> : (
              <>
                View Deals 
                <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
              </>
            )}
          </button>
        </form>
        
        <p className="text-center text-[10px] text-gray-400 mt-6 font-bold uppercase tracking-widest">
          No spam. Only trip updates.
        </p>
      </div>
    </div>
  );
};

const SearchPage = ({ onLoginClick, user }) => {
  const [searchParams] = useSearchParams();
  const [isBooking, setIsBooking] = useState(false);
  const [bookingSuccess, setBookingSuccess] = useState(null);
  const [showLeadModal, setShowLeadModal] = useState(!user); // Don't show if user logged in
  const [cars, setCars] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  
  // Extract search details
  const tripType = searchParams.get("tripType") || "round";
  const pickupLocation = searchParams.get("pickup") || "Not Specified";
  const dropLocation = searchParams.get("drop") || "";
  const pickupDateStr = searchParams.get("pickupDate");
  const returnDateStr = searchParams.get("returnDate");
  const packageType = searchParams.get("package") || "";

  const pickupDate = pickupDateStr ? new Date(pickupDateStr) : new Date();
  const returnDate = returnDateStr ? new Date(returnDateStr) : null;

  useEffect(() => {
    fetchPricing();
  }, [tripType, pickupDateStr, returnDateStr, packageType]);

  const fetchPricing = async () => {
    setIsLoading(true);
    try {
      const response = await api.post("/api/pricing/calculate", {
        tripType,
        pickupDate: pickupDateStr,
        returnDate: returnDateStr,
        packageType
      });
      setCars(response.data);
    } catch (err) {
      console.error("Pricing Fetch Error:", err);
    } finally {
      setIsLoading(false);
    }
  };

  const handleBookNow = async (car) => {
    // If not logged in, ask for lead first (Leads-first flow)
    if (!user && showLeadModal) {
      // Modal is already handling this or will appear
      return;
    }

    setIsBooking(true);
    try {
      const response = await api.post("/api/bookings", {
        tripType,
        pickupLocation,
        dropLocation,
        pickupDateTime: pickupDate.toISOString(),
        returnDateTime: returnDate ? returnDate.toISOString() : null,
        packageType,
        carName: car.name,
        totalAmount: car.calc.grandTotal
      });

      setBookingSuccess(response.bookingId);
    } catch (err) {
      alert("Failed to create booking: " + err.message);
    } finally {
      setIsBooking(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      <Navbar onLoginClick={onLoginClick} user={user} />
      
      {/* Lead Capture Modal */}
      <LeadCaptureModal 
        isOpen={showLeadModal} 
        onSubmit={() => setShowLeadModal(false)}
        searchData={{ tripType, pickup: pickupLocation, drop: dropLocation }}
      />

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10 pt-28 flex-grow">
        
        {/* Search Summary Header */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 mb-8 flex flex-col md:flex-row md:items-center justify-between gap-6 animate-fadeIn">
          <div className="flex flex-col gap-4">
            <Link to="/" className="flex items-center gap-2 text-primary-600 font-bold text-sm hover:translate-x-[-4px] transition-transform w-fit uppercase tracking-wider">
              <ArrowLeft className="w-4 h-4" />
              Modify Search
            </Link>
            <div className="flex flex-wrap items-center gap-y-3 gap-x-6">
              <div className="flex items-center gap-2">
                <div className="bg-primary-50 p-2 rounded-lg text-primary-600 font-bold">
                  <MapPin className="w-4 h-4" />
                </div>
                <div>
                  <p className="text-[10px] text-gray-400 font-bold uppercase tracking-widest">Pickup</p>
                  <p className="text-sm font-bold text-dark-900">{pickupLocation}</p>
                </div>
              </div>
              {dropLocation && (
                <div className="flex items-center gap-2">
                  <div className="bg-red-50 p-2 rounded-lg text-red-500 font-bold">
                    <MapPin className="w-4 h-4" />
                  </div>
                  <div>
                    <p className="text-[10px] text-gray-400 font-bold uppercase tracking-widest">Drop Location</p>
                    <p className="text-sm font-bold text-dark-900">{dropLocation}</p>
                  </div>
                </div>
              )}
              <div className="flex items-center gap-2">
                <div className="bg-orange-50 p-2 rounded-lg text-orange-600 font-bold">
                  <Calendar className="w-4 h-4" />
                </div>
                <div>
                  <p className="text-[10px] text-gray-400 font-bold uppercase tracking-widest">Schedule</p>
                  <p className="text-sm font-bold text-dark-900">
                    {pickupDate.toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' })}
                    {returnDate && ` - ${returnDate.toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' })}`}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 pb-20">
          
          {/* Main Listings */}
          <div className="lg:col-span-2 space-y-6">
            <div className="flex items-center justify-between mb-2">
              <h2 className="text-xl font-black text-dark-900 uppercase tracking-tight">Available Fleets</h2>
              <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest bg-white px-3 py-1.5 rounded-full border border-gray-100 shadow-sm">
                Found {cars.length} Options
              </p>
            </div>
            
            {isLoading ? (
              <div className="bg-white rounded-3xl p-20 flex flex-col items-center justify-center shadow-sm border border-gray-100">
                <Loader2 className="w-10 h-10 text-primary-600 animate-spin mb-4" />
                <p className="text-gray-500 font-bold animate-pulse uppercase tracking-widest text-xs">Finding Best Fares...</p>
              </div>
            ) : cars.map((car) => (
              <div key={car.id} className="bg-white rounded-3xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-2xl hover:shadow-primary-600/5 transition-all duration-500 group">
                <div className="flex flex-col xl:flex-row p-6 gap-8">
                  {/* Car Image Wrapper */}
                  <div className="xl:w-[280px] bg-gray-50 rounded-2xl flex items-center justify-center p-6 relative overflow-hidden group-hover:bg-primary-50/30 transition-colors">
                    <img src={carImages[car.image]} alt={car.name} className="w-full h-auto object-contain transform group-hover:scale-110 transition-transform duration-700 drop-shadow-xl" />
                    
                    {/* Badge */}
                    {car.badge && (
                      <div className="absolute top-4 left-4 bg-primary-600 text-white text-[9px] font-black px-3 py-1.5 rounded-full shadow-lg uppercase tracking-widest animate-bounceIn">
                        {car.badge}
                      </div>
                    )}
                    
                    <div className="absolute bottom-4 right-4 bg-white/90 backdrop-blur-sm px-2.5 py-1.5 rounded-xl border border-white flex items-center gap-1.5 shadow-sm">
                      <span className="text-yellow-500 font-black tracking-tighter">★★★★★</span>
                      <span className="text-[10px] font-black text-dark-900">Top Rated</span>
                    </div>
                  </div>

                  {/* Car Details */}
                  <div className="flex-1 flex flex-col justify-between">
                    <div>
                      <div className="flex justify-between items-start mb-4">
                        <div>
                          <h3 className="text-2xl font-black text-dark-900 group-hover:text-primary-600 transition-colors">{car.name}</h3>
                          <div className="flex items-center gap-4 mt-1.5">
                            <span className="text-[10px] font-black text-primary-600 bg-primary-50 px-2.5 py-1 rounded-lg uppercase tracking-widest">{car.type}</span>
                            <div className="flex items-center gap-3 text-gray-400">
                                <div className="flex items-center gap-1.5">
                                    <Users className="w-3.5 h-3.5" />
                                    <span className="text-[11px] font-bold">{car.seats}</span>
                                </div>
                                <div className="flex items-center gap-1.5">
                                    <Luggage className="w-3.5 h-3.5" />
                                    <span className="text-[11px] font-bold">{car.luggage}</span>
                                </div>
                            </div>
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="text-3xl font-black text-dark-900 leading-none">₹{car.calc.grandTotal}</p>
                          <p className="text-[9px] font-black text-gray-400 mt-2 uppercase tracking-widest border-t border-gray-50 pt-2 inline-block">Final Amount</p>
                        </div>
                      </div>

                      {/* Transparency Math Block */}
                      <div className="bg-primary-50/50 rounded-2xl p-4 mb-6 border border-primary-100/30">
                        <div className="flex items-center justify-between mb-2">
                           <span className="text-[10px] font-black text-primary-900 uppercase tracking-widest flex items-center gap-1.5">
                             <Info className="w-3.5 h-3.5" />
                             Transparent Breakdown
                           </span>
                           <span className="text-[11px] font-black text-primary-600">{car.calc.math}</span>
                        </div>
                        <div className="flex items-center justify-between">
                           <span className="text-[10px] font-bold text-gray-500 uppercase tracking-widest font-mono">20% Booking Advance</span>
                           <span className="text-sm font-black text-primary-600">Pay ₹{car.calc.advancePayment} to Confirm</span>
                        </div>
                      </div>

                      {/* Inclusions / Exclusions */}
                      <div className="grid grid-cols-2 gap-4 pb-6 border-b border-gray-50">
                        <div>
                          <p className="text-[10px] font-black text-green-600 uppercase tracking-widest mb-2 flex items-center gap-1.5">
                             <CheckCircle2 className="w-3 h-3" /> Included
                          </p>
                          <ul className="space-y-1.5">
                            {car.inclusions.map((inc, i) => (
                              <li key={i} className="text-[11px] font-bold text-gray-500 flex items-center gap-1.5">
                                <div className="w-1 h-1 bg-green-500 rounded-full" /> {inc}
                              </li>
                            ))}
                          </ul>
                        </div>
                        <div>
                          <p className="text-[10px] font-black text-red-500 uppercase tracking-widest mb-2 flex items-center gap-1.5">
                             <X className="w-3 h-3" /> Excluded
                          </p>
                          <ul className="space-y-1.5">
                            {car.exclusions.map((exc, i) => (
                              <li key={i} className="text-[11px] font-bold text-gray-400 flex items-center gap-1.5 line-through decoration-red-200">
                                {exc}
                              </li>
                            ))}
                          </ul>
                        </div>
                      </div>
                    </div>

                    <div className="mt-6 flex items-center justify-between">
                      <div className="flex flex-col">
                        <span className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Available Distance</span>
                        <span className="text-sm font-black text-dark-900">{car.calc.totalKmIncluded} Km Included</span>
                      </div>
                      <button 
                        onClick={() => handleBookNow(car)}
                        disabled={isBooking}
                        className="bg-dark-900 hover:bg-primary-600 text-white font-black text-xs px-8 py-4 rounded-2xl transition-all duration-300 shadow-xl shadow-dark-900/10 hover:shadow-primary-600/30 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 group"
                      >
                        {isBooking ? <Loader2 className="w-4 h-4 animate-spin text-white" /> : (
                          <>
                            Book for ₹{car.calc.advancePayment} <ChevronRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
                          </>
                        )}
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* Pricing Summary Sidebar */}
          <div className="lg:col-span-1">
            <div className="sticky top-28 space-y-6">
               <div className="bg-white rounded-3xl shadow-sm border border-gray-100 p-8 overflow-hidden relative group">
                  {/* Decorative element */}
                  <div className="absolute -top-10 -right-10 w-32 h-32 bg-primary-50 rounded-full opacity-50 blur-3xl group-hover:bg-primary-100 transition-colors duration-500" />
                  
                  <h2 className="text-xl font-black text-dark-900 mb-8 flex items-center gap-3 relative z-10">
                    Terms & Policy
                    < ShieldCheck className="w-5 h-5 text-green-500" />
                  </h2>

                  <div className="space-y-5 relative z-10">
                    <div className="flex items-start gap-3">
                      <div className="mt-1 w-5 h-5 bg-green-50 rounded-lg flex items-center justify-center flex-shrink-0">
                        <CheckCircle2 className="w-3 h-3 text-green-600" />
                      </div>
                      <div>
                        <p className="text-xs font-black text-dark-900 mb-0.5">Toll & State Permits</p>
                        <p className="text-[11px] font-bold text-gray-500 leading-relaxed">To be paid by traveller as per actuals during the trip.</p>
                      </div>
                    </div>
                    <div className="flex items-start gap-3">
                      <div className="mt-1 w-5 h-5 bg-primary-50 rounded-lg flex items-center justify-center flex-shrink-0">
                        <Info className="w-3 h-3 text-primary-600" />
                      </div>
                      <div>
                        <p className="text-xs font-black text-dark-900 mb-0.5">Extra Kilimoteres</p>
                        <p className="text-[11px] font-bold text-gray-500 leading-relaxed">Charged at standard base rates mentioned on the car cards.</p>
                      </div>
                    </div>
                    <div className="flex items-start gap-3">
                      <div className="mt-1 w-5 h-5 bg-orange-50 rounded-lg flex items-center justify-center flex-shrink-0">
                        <Calendar className="w-3 h-3 text-orange-600" />
                      </div>
                      <div>
                        <p className="text-xs font-black text-dark-900 mb-0.5">Night Charge</p>
                        <p className="text-[11px] font-bold text-gray-500 leading-relaxed">Driver night allowance applicable after 10:00 PM.</p>
                      </div>
                    </div>
                  </div>

                  <div className="mt-10 p-5 bg-gray-50 rounded-2xl border border-gray-100 text-center">
                    <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1.5">Need Custom Help?</p>
                    <a href="tel:+917975942520" className="text-sm font-black text-dark-900 hover:text-primary-600 transition-colors">+91 7975942520</a>
                  </div>
               </div>
               
               <div className="bg-dark-900 rounded-3xl p-8 text-white relative overflow-hidden shadow-2xl">
                  <div className="absolute top-0 right-0 w-32 h-32 bg-primary-600/20 rounded-full blur-3xl" />
                  <h3 className="text-lg font-black mb-4 flex items-center gap-2">
                    <ShieldCheck className="w-5 h-5 text-primary-400" />
                    Refund Guarantee
                  </h3>
                  <p className="text-xs font-bold text-gray-400 leading-relaxed">
                    Cancel up to 24 hours in advance and receive a full refund of your 20% booking deposit.
                  </p>
               </div>
            </div>
          </div>
        </div>
      </main>

      {/* Success Modal */}
      {bookingSuccess && (
        <div className="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-dark-900/60 backdrop-blur-sm animate-fadeIn">
          <div className="bg-white rounded-[40px] p-10 max-w-sm w-full text-center shadow-3xl animate-scaleIn border border-white">
            <div className="w-24 h-24 bg-green-50 rounded-[35px] flex items-center justify-center mx-auto mb-8 shadow-inner">
              <CheckCircle2 className="w-12 h-12 text-green-600" />
            </div>
            <h2 className="text-3xl font-black text-dark-900 mb-3 tracking-tighter">Trip Confirmed!</h2>
            <p className="text-gray-500 text-sm mb-10 leading-relaxed px-2 font-bold">
              We've received your booking. Our professional driver will reach out to you shortly.
            </p>
            <div className="bg-gray-50/80 rounded-[28px] p-6 mb-10 border border-gray-100">
              <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2">Booking Transaction ID</p>
              <p className="text-2xl font-black text-dark-900 tracking-tighter">#RR-{bookingSuccess}</p>
            </div>
            <button 
              onClick={() => setBookingSuccess(null)}
              className="w-full bg-dark-900 hover:bg-black text-white font-black py-5 rounded-2xl transition-all shadow-xl shadow-dark-900/20 active:scale-95"
            >
              Done & Back to Home
            </button>
          </div>
        </div>
      )}
      
      <Footer />
    </div>
  );
};

export default SearchPage;
