import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { useIsMobile } from "@/hooks/use-mobile";
import { useCurrentLocation } from "@/hooks/useCurrentLocation";
import { useAutoSave } from "@/hooks/useAutoSave";
import { base44 } from "@/api/base44Client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { ShoppingCart, Plus, Minus, X, ShoppingBag, Clock, MapPin, ChevronLeft, CheckCircle, Search, Store, Share2, ExternalLink } from "lucide-react";
import CancellationPolicyBanner from "@/components/CancellationPolicyBanner";
import SuspendedAccountGate from "@/components/SuspendedAccountGate";
import { Link } from "react-router-dom";
import { motion, AnimatePresence } from "framer-motion";
import { toast } from "sonner";
import SEOSchema from "@/components/SEOSchema";
import PullToRefresh from "@/components/PullToRefresh";
import ErrorReporter from "@/components/ErrorReporter";
import FavoritesManager from "@/components/FavoritesManager";

const SHOP_TYPE_LABELS = {
  supermarket: "🏪 Supermarket",
  market_stall: "🛒 Market Stall",
  butcher: "🥩 Butcher",
  bakery: "🥐 Bakery",
  pharmacy: "💊 Pharmacy",
  hardware: "🔧 Hardware",
  general: "🏬 General Store",
};

const toRad = (v) => (v * Math.PI) / 180;
const getDistanceKm = (lat1, lon1, lat2, lon2) => {
  const R = 6371;
  const dLat = toRad(lat2 - lat1);
  const dLon = toRad(lon2 - lon1);
  const a = Math.sin(dLat/2)**2 + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon/2)**2;
  return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
};

export default function OrderGroceries() {
  return <SuspendedAccountGate><OrderGroceriesInner /></SuspendedAccountGate>;
}

function OrderGroceriesInner() {
  const navigate = useNavigate();
  const isMobile = useIsMobile();
  const [shops, setShops] = useState([]);
  const [selected, setSelected] = useState(null);
  const [items, setItems] = useState([]);
  const [cart, setCart] = useState({});
  const [showCart, setShowCart] = useState(false);
  const [loading, setLoading] = useState(true);
  const [userCoords, setUserCoords] = useState(null);
  const [placing, setPlacing] = useState(false);
  const [success, setSuccess] = useState(null);
  const [isAuthed, setIsAuthed] = useState(false);
  const [searchText, setSearchText] = useState("");
  const [filterType, setFilterType] = useState("");
  const [menuSearch, setMenuSearch] = useState("");
  const { address: currentAddress } = useCurrentLocation();
  const [form, setForm] = useState({ customer_name: "", customer_phone: "", customer_email: "", delivery_address: "", notes: "", payment_method: "cash" });
  const { isSaving, clearDraft } = useAutoSave(form, "GroceryOrder", "draft_grocery_order_id");
  const [error, setError] = useState(null);

  // Auto-prefill delivery address with current GPS address
  useEffect(() => {
    if (currentAddress) {
      setForm(prev => ({ ...prev, delivery_address: prev.delivery_address || currentAddress }));
    }
  }, [currentAddress]);

  // Pre-fill user data
  useEffect(() => {
    base44.auth.me()
      .then(u => {
        if (u) setForm(f => ({ ...f, customer_name: u.full_name || "", customer_email: u.email || "" }));
      })
      .catch(() => {});
  }, []);

  useEffect(() => {
    base44.entities.GroceryShop.filter({ status: "active" }).then(s => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          ({ coords }) => {
            const { latitude, longitude } = coords;
            setUserCoords({ latitude, longitude });
            const sorted = [...s].sort((a, b) => {
              const distA = a.latitude && a.longitude ? Math.hypot(a.latitude - latitude, a.longitude - longitude) : 999;
              const distB = b.latitude && b.longitude ? Math.hypot(b.latitude - latitude, b.longitude - longitude) : 999;
              return distA - distB;
            });
            setShops(sorted);
            setLoading(false);
          },
          () => { setShops(s); setLoading(false); }
        );
      } else {
        setShops(s);
        setLoading(false);
      }
    }).catch(() => setLoading(false));
  }, []);

  const selectShop = async (shop) => {
    setSelected(shop);
    setCart({});
    // Only show items that are in stock (quantity > 0)
    const shopItems = await base44.entities.GroceryItem.filter({ shop_id: shop.id });
    const availableItems = shopItems.filter(i => i.quantity > 0);
    setItems(availableItems);
  };

  const addToCart = (item) => setCart(c => ({ ...c, [item.id]: { ...item, qty: (c[item.id]?.qty || 0) + 1 } }));
  const removeFromCart = (item) => setCart(c => {
    const qty = (c[item.id]?.qty || 0) - 1;
    if (qty <= 0) { const n = { ...c }; delete n[item.id]; return n; }
    return { ...c, [item.id]: { ...item, qty } };
  });

  const cartItems = Object.values(cart).filter(i => i.qty > 0);
  const subtotal = cartItems.reduce((s, i) => s + i.price * i.qty, 0);
  const total = subtotal + (selected?.delivery_fee || 0);

  const placeOrder = async () => {
    if (!form.customer_name?.trim()) { toast.error("Please enter your name."); return; }
    if (!form.customer_phone?.trim()) { toast.error("Please enter your phone number."); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.customer_email)) { toast.error("Please enter a valid email."); return; }
    if (!form.delivery_address?.trim()) { toast.error("Please enter your delivery address."); return; }
    if (!cartItems.length) { toast.error("Please add items to your cart."); return; }
    setPlacing(true);
    const authed = await base44.auth.isAuthenticated();
    setIsAuthed(authed);
    
    try {
    const order = await base44.entities.GroceryOrder.create({
      shop_id: selected.id,
      shop_name: selected.shop_name,
      items: JSON.stringify(cartItems.map(i => ({ id: i.id, name: i.name, price: i.price, qty: i.qty, unit: i.unit }))),
      subtotal,
      delivery_fee: selected.delivery_fee,
      total,
      ...form,
      status: "pending",
    });

    // Send emails to customer and shop
    if (form.customer_email) {
      base44.functions.invoke("sendBookingEmail", {
        email: form.customer_email, name: form.customer_name, type: "grocery",
        orderId: order.id, from: selected.shop_name, to: form.delivery_address, cost: total,
      }).catch(() => {});
    }
    
    // Notify shop via WhatsApp and email
    if (selected.phone) {
      const itemList = cartItems.map(i => `• ${i.qty}x ${i.name} (GYD ${i.price})`).join("\n");
      const msg = `🛒 New Grocery Order!\n\nCustomer: ${form.customer_name}\nPhone: ${form.customer_phone}\nDeliver to: ${form.delivery_address}\n\nItems:\n${itemList}\n\nTotal: GYD ${total}\nOrder ID: ${order.id}\n\nManage on ZIP.GY dashboard.`;
      base44.functions.invoke("sendWhatsApp", { to: selected.phone, message: msg }).catch(() => {});
    }
    
    if (selected.owner_email) {
      base44.functions.invoke("notifyRestaurant", {
        restaurantEmail: selected.owner_email, restaurantName: selected.shop_name,
        orderId: order.id, customerName: form.customer_name,
        total: total, items: order.items, deliveryAddress: form.delivery_address,
        restaurantPhone: selected.phone,
      }).catch(() => {});
    }

    clearDraft();
    // Silently invite guest users — they'll see the "Sign Up" prompt on the confirmation screen
    if (!authed && form.customer_email) {
      base44.users.inviteUser(form.customer_email, "user").catch(() => {});
    }
    setSuccess(order);
    setPlacing(false);
    } catch (err) {
      toast.error("Something went wrong. Please try again.");
      setPlacing(false);
    }
    };

  if (success) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background px-4">
        <motion.div initial={{ scale: 0.9, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} className="text-center max-w-sm w-full">
          <div className="w-20 h-20 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
            <CheckCircle className="w-10 h-10 text-primary" />
          </div>
          <h2 className="font-heading font-bold text-2xl mb-2">Order Placed!</h2>
          <p className="text-muted-foreground mb-1">Your order has been sent to <strong>{selected.shop_name}</strong>.</p>
          <p className="text-muted-foreground text-sm mb-6">Pay <strong className="text-foreground">GYD {total.toLocaleString()}</strong> {form.payment_method === 'mmg' ? 'via MMG Mobile Money.' : form.payment_method === 'card' ? 'by card on delivery.' : 'cash to the driver on delivery.'}</p>
          <div className="bg-muted rounded-xl p-3 mb-6 text-left text-sm">
            <p className="text-xs text-muted-foreground mb-1">Order ID</p>
            <p className="font-mono font-semibold">{success.id}</p>
          </div>
          <CancellationPolicyBanner
            orderId={success.id}
            orderType="grocery"
            bookedAt={success.created_date || new Date().toISOString()}
            userEmail={form.customer_email}
            onEntityUpdate={(id, data) => base44.entities.GroceryOrder.update(id, data)}
            onCancelled={() => {}}
          />
          <a href={`/track-grocery?id=${success.id}`}>
            <Button className="w-full rounded-full mb-3 mt-3">Track My Order</Button>
          </a>
          {isAuthed && (
            <>
              <Button variant="outline" className="w-full rounded-full mb-2" onClick={() => { setSuccess(null); setSelected(null); setCart({}); setForm({ customer_name: "", customer_phone: "", customer_email: "", delivery_address: "", notes: "", payment_method: "cash" }); }}>
                Order More
              </Button>
              <a href="/dashboard"><Button variant="outline" className="w-full rounded-full">Go to Dashboard</Button></a>
            </>
          )}
          {!isAuthed && (
            <div className="mt-4 p-4 bg-primary border border-primary/80 rounded-2xl text-left">
              <p className="font-heading font-bold text-sm text-primary-foreground mb-1">⚡ One last step — create your free account</p>
              <p className="text-xs text-primary-foreground/80 mb-3">Required to track your order, receive updates, and get your GYD 1,000 welcome bonus.</p>
              <button onClick={() => base44.auth.redirectToLogin(`/track-grocery?id=${success.id}`)} className="w-full py-2.5 rounded-xl bg-white text-primary text-sm font-heading font-bold hover:bg-white/90 transition-colors">
                Create Free Account →
              </button>
            </div>
          )}
        </motion.div>
      </div>
    );
  }

  // Shop list view (when no shop selected)
  const handleRefresh = async () => {
    const s = await base44.entities.GroceryShop.filter({ status: "active" });
    setShops(s);
  };

  if (!selected) {
    const filtered = shops.filter(s => {
      const matchSearch = s.shop_name.toLowerCase().includes(searchText.toLowerCase()) || s.area?.toLowerCase().includes(searchText.toLowerCase());
      const matchType = !filterType || s.shop_type === filterType;
      return matchSearch && matchType;
    });
    const shopTypes = [...new Set(shops.map(s => s.shop_type).filter(Boolean))];

    return (
      <>
      <SEOSchema page="groceries" />
      <div className={`bg-background ${isMobile ? "flex flex-col" : "min-h-screen"}`} style={isMobile ? { minHeight: "100dvh", maxWidth: "100vw", overflow: "hidden" } : {}}>
        <PullToRefresh onRefresh={handleRefresh}>
          <div className={isMobile ? "flex-1 flex flex-col h-full overflow-hidden" : ""}>
            {isMobile && (
            <div className="sticky top-0 z-50 bg-white border-b border-gray-100 px-4 py-3 flex-shrink-0 pt-[max(12px,env(safe-area-inset-top,12px))]">
              <div className="flex items-center gap-3">
                <button onClick={() => navigate("/home-new-mobile")} className="p-3 hover:bg-gray-100 rounded-full transition-colors" aria-label="Go back">
                  <ChevronLeft className="w-6 h-6 text-gray-700" />
                </button>
                <div className="flex items-center gap-2 flex-1">
                  <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-emerald-500 to-teal-500 flex items-center justify-center">
                    <span className="text-white font-bold text-sm">Z</span>
                  </div>
                  <span className="font-bold text-lg text-gray-900">ZIP.GY</span>
                </div>
              </div>
            </div>
            )}
            
            <div className={`${isMobile ? "flex-1 overflow-y-auto" : ""} px-4 py-6 max-w-5xl mx-auto w-full`}>
              {/* Search & Filters */}
              <div className="mb-6 space-y-3">
                <div className="flex items-center gap-2 bg-card border border-border rounded-xl px-3 py-2">
                  <Search className="w-4 h-4 text-muted-foreground" />
                  <input
                    placeholder="Search shops or area..."
                    value={searchText}
                    onChange={(e) => setSearchText(e.target.value)}
                    className="flex-1 bg-transparent outline-none text-sm"
                  />
                </div>
                <div className="flex gap-2 overflow-x-auto pb-2">
                  <button
                    onClick={() => setFilterType("")}
                    className={`px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-colors ${
                      !filterType
                        ? "bg-primary text-white"
                        : "bg-muted text-muted-foreground hover:bg-muted/80"
                    }`}
                  >
                    All Types
                  </button>
                  {shopTypes.map(type => (
                    <button
                      key={type}
                      onClick={() => setFilterType(type)}
                      className={`px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-colors ${
                        filterType === type
                          ? "bg-primary text-white"
                          : "bg-muted text-muted-foreground hover:bg-muted/80"
                      }`}
                    >
                      {SHOP_TYPE_LABELS[type] || type}
                    </button>
                  ))}
                </div>
              </div>

              {loading ? (
                <div className="grid grid-cols-1 gap-4">
                  {[1,2,3,4,5,6].map(i => (
                    <div key={i} className="bg-card border border-border rounded-2xl overflow-hidden">
                      <div className="h-36 bg-muted animate-pulse" />
                      <div className="p-4 space-y-2">
                        <div className="h-4 bg-muted animate-pulse rounded w-3/4" />
                        <div className="h-3 bg-muted animate-pulse rounded w-1/2" />
                      </div>
                    </div>
                  ))}
                </div>
              ) : filtered.length === 0 ? (
                <div className="text-center py-20 text-muted-foreground">
                  <ShoppingBag className="w-12 h-12 mx-auto mb-3 opacity-30" />
                  <p>No shops found. Try adjusting your filters.</p>
                </div>
              ) : (
                <div className="grid grid-cols-1 gap-4">
                  {filtered.map(s => (
                    <motion.button key={s.id} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}
                      onClick={() => selectShop(s)}
                      className="w-full text-left bg-card border border-border rounded-2xl overflow-hidden hover:shadow-lg transition-all hover:border-primary/40 group">
                      <div className="h-36 bg-muted relative overflow-hidden">
                        {s.cover_url
                          ? <img src={s.cover_url} alt={s.shop_name} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" />
                          : <div className="w-full h-full flex items-center justify-center"><ShoppingBag className="w-10 h-10 text-muted-foreground/30" /></div>}
                      </div>
                      <div className="p-4">
                        <div className="flex items-start justify-between gap-2">
                          <div>
                            <h3 className="font-heading font-bold text-base">{s.shop_name}</h3>
                            <p className="text-sm text-muted-foreground">{SHOP_TYPE_LABELS[s.shop_type] || s.shop_type}</p>
                          </div>
                          {s.logo_url ? (
                            <img src={s.logo_url} alt="" className="w-10 h-10 rounded-xl object-cover flex-shrink-0" />
                          ) : (
                            <div className="w-10 h-10 rounded-xl bg-muted flex items-center justify-center flex-shrink-0">
                              <ShoppingBag className="w-5 h-5 text-muted-foreground opacity-40" />
                            </div>
                          )}
                        </div>
                        <div className="flex items-center gap-3 mt-2 text-xs text-muted-foreground flex-wrap">
                          <span className="flex items-center gap-1"><MapPin className="w-3 h-3" />{s.area}</span>
                          <span className="flex items-center gap-1"><Clock className="w-3 h-3" />{s.hours_start}–{s.hours_end}</span>
                          {userCoords && s.latitude && s.longitude && (() => {
                            const km = getDistanceKm(userCoords.latitude, userCoords.longitude, s.latitude, s.longitude);
                            return <span className="flex items-center gap-1 text-primary font-medium">📍 {km < 1 ? `${Math.round(km * 1000)}m` : `${km.toFixed(1)}km`} away</span>;
                          })()}
                        </div>
                        <p className="text-xs text-muted-foreground mt-1">Delivery: GYD {s.delivery_fee?.toLocaleString()}</p>
                      </div>
                    </motion.button>
                  ))}
                </div>
              )}
              <ErrorReporter error={error} page="grocery" orderId={success?.id} onClose={() => setError(null)} />
            </div>
          </div>
        </PullToRefresh>
      </div>
      </>
    );
  }
  
  // Selected shop - item selection view
  return (
    <>
    <SEOSchema page="groceries" />
    <PullToRefresh onRefresh={handleRefresh}>
      <div className={isMobile ? "flex-1 flex flex-col h-full overflow-hidden" : "min-h-screen bg-background"}>
      {isMobile && (
      <div className="sticky top-0 z-50 bg-white border-b border-gray-100 px-4 py-3 flex-shrink-0 pt-[max(12px,env(safe-area-inset-top,12px))]">
        <div className="flex items-center gap-3">
          <button 
            onClick={() => {
              setSelected(null);
              setMenuSearch("");
            }} 
            className="p-3 hover:bg-gray-100 rounded-full transition-colors"
            aria-label="Go back"
          >
            <ChevronLeft className="w-6 h-6 text-gray-700" />
          </button>
          <div className="flex items-center gap-2 flex-1">
            <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-emerald-500 to-teal-500 flex items-center justify-center">
              <span className="text-white font-bold text-sm">Z</span>
            </div>
            <span className="font-bold text-lg text-gray-900 truncate">{selected.shop_name}</span>
          </div>
          <button onClick={() => setShowCart(!showCart)} className="relative flex items-center gap-1.5 bg-emerald-600 text-white rounded-full px-3 py-1.5 text-xs font-semibold">
            <ShoppingCart className="w-3.5 h-3.5" />
            {cartItems.length > 0 && <span className="absolute -top-0.5 -right-0.5 w-4 h-4 bg-orange-500 rounded-full text-[10px] flex items-center justify-center font-bold">{cartItems.reduce((s, i) => s + i.qty, 0)}</span>}
          </button>
        </div>
      </div>
      )}

      <div className={`${isMobile ? "flex-1 overflow-y-auto" : ""} px-4 py-6 max-w-5xl mx-auto w-full`}>
        {/* Search box */}
        <div className="mb-6 sticky top-16 z-20 bg-background pb-4">
          <div className="flex items-center gap-2 bg-card border border-border rounded-xl px-3 py-2.5">
            <Search className="w-4 h-4 text-muted-foreground" />
            <input
              placeholder="Search items..."
              value={menuSearch}
              onChange={(e) => setMenuSearch(e.target.value)}
              className="flex-1 bg-transparent outline-none text-sm"
            />
            {menuSearch && (
              <button onClick={() => setMenuSearch("")} className="text-muted-foreground hover:text-foreground">
                <X className="w-4 h-4" />
              </button>
            )}
          </div>
        </div>
        
        {items.length === 0 ? (
          <div className="text-center py-20 text-muted-foreground">No items listed yet for this shop.</div>
        ) : (() => {
          const filteredItems = items.filter(i => i.name.toLowerCase().includes(menuSearch.toLowerCase()));
          const categories = [...new Set(filteredItems.map(i => i.category || "Other"))];
          return categories.length === 0 ? (
            <div className="text-center py-20 text-muted-foreground">
              <p className="font-semibold">No items found for "{menuSearch}"</p>
              <p className="text-sm mt-1">Try a different search term</p>
            </div>
          ) : (
            categories.map(cat => {
              const catItems = filteredItems.filter(i => i.category === cat);
              if (catItems.length === 0) return null;
              return (
                <div key={cat} className="mb-8">
                  <h3 className="font-heading font-bold text-lg mb-3 border-b border-border pb-2">{cat}</h3>
                  <div className="space-y-3">
                    {catItems.map(item => (
                      <div key={item.id} className="flex gap-3 bg-card border border-border rounded-xl p-3">
                        {item.photo_url && <img src={item.photo_url} alt={item.name} className="w-20 h-20 rounded-lg object-cover flex-shrink-0" />}
                        <div className="flex-1 min-w-0">
                          <p className="font-semibold text-sm">{item.name}</p>
                          {item.description && <p className="text-xs text-muted-foreground mt-0.5">{item.description}</p>}
                          <p className="text-primary font-bold text-sm mt-1">GYD {item.price.toLocaleString()} {item.unit ? `/ ${item.unit}` : ""}</p>
                        </div>
                        <div className="flex items-center gap-2 flex-shrink-0">
                          {cart[item.id]?.qty > 0 ? (
                            <div className="flex items-center gap-2">
                              <button onClick={() => removeFromCart(item)} className="w-7 h-7 rounded-full bg-muted flex items-center justify-center"><Minus className="w-3.5 h-3.5" /></button>
                              <span className="font-bold text-sm w-4 text-center">{cart[item.id].qty}</span>
                              <button onClick={() => addToCart(item)} className="w-7 h-7 rounded-full bg-primary text-white flex items-center justify-center"><Plus className="w-3.5 h-3.5" /></button>
                            </div>
                          ) : (
                            <button onClick={() => addToCart(item)} className="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center"><Plus className="w-4 h-4" /></button>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              );
            })
          );
        })()}
        <ErrorReporter error={error} page="grocery" orderId={success?.id} onClose={() => setError(null)} />
        </div>
      </div>
    </PullToRefresh>
    </>
  );
}