import { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from "@/components/ui/sheet";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { ShoppingCart, Plus, Minus, Trash2, Star, CreditCard, Building2, Smartphone, Loader2, CheckCircle2, Truck } from "lucide-react";
import { toast } from "sonner";
import { useNavigate } from "@tanstack/react-router";
import { useStore, fmt, type Address } from "@/lib/store";
import { usePaystackPayment } from "react-paystack";

export function SignInModal({ open, onOpenChange }: { open: boolean; onOpenChange: (o: boolean) => void }) {
  const { user, signIn, signOut } = useStore();
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");

  if (user) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[420px]">
          <DialogHeader>
            <DialogTitle>Signed in as {user.name}</DialogTitle>
            <DialogDescription>{user.email} · Role: {user.role}</DialogDescription>
          </DialogHeader>
          <div className="flex gap-2 pt-2">
            <Button variant="outline" onClick={() => onOpenChange(false)} className="flex-1">Close</Button>
            <Button onClick={() => { signOut(); onOpenChange(false); toast("Signed out"); }} className="flex-1 bg-orange-500 hover:bg-orange-600">Sign out</Button>
          </div>
        </DialogContent>
      </Dialog>
    );
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[420px]">
        <DialogHeader>
          <div className="flex items-center gap-2 mb-2">
            <Star className="w-6 h-6 text-orange-500 fill-orange-500" />
            <span className="text-xl font-extrabold">SULEJA<span className="text-neutral-800">MARKET</span></span>
          </div>
          <DialogTitle className="text-2xl">Welcome back</DialogTitle>
          <DialogDescription>Sign in to see personalized deals and track your orders.</DialogDescription>
        </DialogHeader>
        <form className="space-y-3 pt-2" onSubmit={(e) => { e.preventDefault(); signIn(email, name || undefined); onOpenChange(false); toast.success(`Welcome, ${name || email.split("@")[0]}`); }}>
          <div className="space-y-1.5">
            <label className="text-sm font-medium">Full name</label>
            <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Jane Doe" />
          </div>
          <div className="space-y-1.5">
            <label className="text-sm font-medium">Email</label>
            <Input value={email} onChange={(e) => setEmail(e.target.value)} type="email" placeholder="you@example.com" required />
          </div>
          <div className="space-y-1.5">
            <label className="text-sm font-medium">Password</label>
            <Input type="password" placeholder="••••••••" required />
          </div>
          <Button type="submit" className="w-full bg-orange-500 hover:bg-orange-600 h-11">Sign in</Button>
          <button type="button" onClick={() => onOpenChange(false)} className="w-full text-sm text-neutral-500 hover:text-neutral-800">
            Continue as guest
          </button>
        </form>
      </DialogContent>
    </Dialog>
  );
}

export function CartDrawer({ open, onOpenChange, onCheckout }: { open: boolean; onOpenChange: (o: boolean) => void; onCheckout: () => void }) {
  const { cart, updateQty, removeItem } = useStore();
  const subtotal = cart.reduce((s, x) => s + x.price * x.qty, 0);
  const shipping = cart.length === 0 ? 0 : subtotal > 100000 ? 0 : 1500;
  const vat = cart.length === 0 ? 0 : subtotal * 0.01;
  const total = subtotal + shipping + vat;

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-full sm:max-w-md flex flex-col p-0">
        <SheetHeader className="px-5 py-4 border-b">
          <SheetTitle className="flex items-center gap-2">
            <ShoppingCart className="w-5 h-5 text-orange-500" />
            Your Cart ({cart.reduce((s, x) => s + x.qty, 0)})
          </SheetTitle>
        </SheetHeader>
        <div className="flex-1 overflow-y-auto px-5 py-4 space-y-4">
          {cart.length === 0 ? (
            <div className="text-center text-neutral-500 py-16">
              <ShoppingCart className="w-12 h-12 mx-auto mb-3 text-neutral-300" />
              <p className="text-sm">Your cart is empty</p>
            </div>
          ) : (
            cart.map((item) => (
              <div key={item.id} className="flex gap-3 pb-4 border-b last:border-0">
                <img src={(item.images?.[0] || `https://picsum.photos/seed/${item.seed}/120/120`)} alt={item.name} className="w-20 h-20 object-cover rounded" />
                <div className="flex-1 min-w-0">
                  <div className="text-sm text-neutral-800 line-clamp-2">{item.name}</div>
                  <div className="text-sm font-bold mt-1">₦ {fmt(item.price)}</div>
                  <div className="flex items-center justify-between mt-2">
                    <div className="flex items-center border rounded">
                      <button onClick={() => updateQty(item.id, -1)} className="w-7 h-7 flex items-center justify-center hover:bg-neutral-100">
                        <Minus className="w-3 h-3" />
                      </button>
                      <span className="w-8 text-center text-sm">{item.qty}</span>
                      <button onClick={() => updateQty(item.id, +1)} className="w-7 h-7 flex items-center justify-center hover:bg-neutral-100">
                        <Plus className="w-3 h-3" />
                      </button>
                    </div>
                    <button onClick={() => removeItem(item.id)} className="text-neutral-400 hover:text-red-500">
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </div>
            ))
          )}
        </div>
        {cart.length > 0 && (
          <SheetFooter className="border-t px-5 py-4 flex-col gap-3 sm:flex-col">
            <div className="w-full space-y-1.5 text-sm">
              <div className="flex justify-between text-neutral-600"><span>Subtotal</span><span>₦ {fmt(subtotal)}</span></div>
              <div className="flex justify-between text-neutral-600"><span>Shipping</span><span>{shipping === 0 ? "Free" : `₦ ${fmt(shipping)}`}</span></div>
              <div className="flex justify-between text-neutral-600"><span>VAT (1%)</span><span>₦ {fmt(vat)}</span></div>
              <div className="flex justify-between font-bold text-base pt-2 border-t"><span>Total</span><span>₦ {fmt(total)}</span></div>
            </div>
            <Button onClick={onCheckout} className="w-full h-11 bg-orange-500 hover:bg-orange-600">Checkout</Button>
          </SheetFooter>
        )}
      </SheetContent>
    </Sheet>
  );
}

type Step = "address" | "payment";

export function CheckoutFlow({ open, onOpenChange }: { open: boolean; onOpenChange: (o: boolean) => void }) {
  const { cart, addresses, addAddress, placeOrder, clearCart, user, paystackKey } = useStore();
  const [step, setStep] = useState<Step>("address");
  const [selectedAddrId, setSelectedAddrId] = useState<string>("");
  const [newAddr, setNewAddr] = useState({ name: "", phone: "", street: "", city: "", state: "" });
  const [method, setMethod] = useState<"paystack" | "pod">("paystack");
  const navigate = useNavigate();

  const subtotal = cart.reduce((s, x) => s + x.price * x.qty, 0);
  const shipping = cart.length === 0 ? 0 : subtotal > 100000 ? 0 : 1500;
  const vat = cart.length === 0 ? 0 : subtotal * 0.01;
  const total = subtotal + shipping + vat;

  const close = (o: boolean) => {
    onOpenChange(o);
    if (!o) setStep("address");
  };

  const submitAddress = (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedAddrId && (!newAddr.name || !newAddr.phone || !newAddr.street || !newAddr.city)) return;
    setStep("payment");
  };

  const activeCity = selectedAddrId ? addresses.find(a => a.id === selectedAddrId)?.city : newAddr.city;
  const normalizedCity = activeCity?.toLowerCase().trim() || "";
  const podEligible = ["suleja", "zuba", "madella", "madalla", "deidei", "kubwa"].includes(normalizedCity);

  const handlePlaceOrder = (paymentMethod: string, paymentRef: string) => {
    let addr: Address | undefined = addresses.find((a) => a.id === selectedAddrId);
    if (!addr) addr = addAddress(newAddr);
    const order = placeOrder({
      items: cart,
      subtotal,
      shipping,
      total,
      address: addr,
      paymentMethod,
      paymentRef,
    });
    clearCart();
    close(false);
    toast.success("Order placed successfully", { description: `Ref ${order.paymentRef}` });
    navigate({ to: "/orders/$id", params: { id: order.id } });
  };

  const config = {
    reference: `PSK_${Math.random().toString(36).slice(2, 10).toUpperCase()}`,
    email: user?.email || "guest@example.com",
    amount: total * 100, // in kobo
    publicKey: paystackKey,
  };
  const initializePayment = usePaystackPayment(config);

  const onSuccess = (reference: any) => {
    handlePlaceOrder("Paystack", reference.reference);
  };
  const onClose = () => {
    // user closed the popup
  };

  const pay = () => {
    if (method === "paystack") {
      if (!paystackKey) {
        toast.error("Paystack API Key is not configured. Please contact the administrator.");
        return;
      }
      initializePayment({ onSuccess, onClose });
    } else {
      handlePlaceOrder("Pay on Delivery", `POD_${Math.random().toString(36).slice(2, 10).toUpperCase()}`);
    }
  };

  return (
    <Dialog open={open} onOpenChange={close}>
      <DialogContent className="sm:max-w-[520px]">
        {step === "address" && (
          <>
            <DialogHeader>
              <DialogTitle>Shipping address</DialogTitle>
              <DialogDescription>Total: <b className="text-neutral-900">₦ {fmt(total)}</b></DialogDescription>
            </DialogHeader>
            <form onSubmit={submitAddress} className="space-y-3">
              {addresses.length > 0 && (
                <div className="space-y-2">
                  <div className="text-xs font-medium text-neutral-600">Saved addresses</div>
                  {addresses.map((a) => (
                    <label key={a.id} className="flex items-start gap-2 border rounded-md p-2.5 cursor-pointer hover:border-orange-400">
                      <input type="radio" name="addr" checked={selectedAddrId === a.id} onChange={() => setSelectedAddrId(a.id)} className="mt-1 accent-orange-500" />
                      <div className="text-sm">
                        <div className="font-medium">{a.name} · {a.phone}</div>
                        <div className="text-neutral-500 text-xs">{a.street}, {a.city}, {a.state}</div>
                      </div>
                    </label>
                  ))}
                  <div className="text-xs text-neutral-500 pt-1">Or add a new address below.</div>
                </div>
              )}
              <div className="grid grid-cols-2 gap-2">
                <Input placeholder="Full name" value={newAddr.name} onChange={(e) => setNewAddr({ ...newAddr, name: e.target.value })} />
                <Input placeholder="Phone" value={newAddr.phone} onChange={(e) => setNewAddr({ ...newAddr, phone: e.target.value })} />
              </div>
              <Input placeholder="Street address" value={newAddr.street} onChange={(e) => setNewAddr({ ...newAddr, street: e.target.value })} />
              <div className="grid grid-cols-2 gap-2">
                <Input placeholder="City" value={newAddr.city} onChange={(e) => setNewAddr({ ...newAddr, city: e.target.value })} required={!selectedAddrId} />
                <Input placeholder="State" value={newAddr.state} onChange={(e) => setNewAddr({ ...newAddr, state: e.target.value })} required={!selectedAddrId} />
              </div>
              <DialogFooter><Button type="submit" className="bg-orange-500 hover:bg-orange-600">Continue to payment</Button></DialogFooter>
            </form>
          </>
        )}

        {step === "payment" && (
          <>
            <DialogHeader>
              <DialogTitle>Payment method</DialogTitle>
              <DialogDescription>Total: <b className="text-neutral-900">₦ {fmt(total)}</b></DialogDescription>
            </DialogHeader>
            <div className="grid grid-cols-1 gap-2">
              <button
                type="button"
                onClick={() => setMethod("paystack")}
                className="flex flex-col items-center gap-2 border border-[#0ba4db] bg-sky-50 text-[#0ba4db] rounded-md py-4 text-sm font-medium"
              >
                <div className="w-8 h-8 rounded bg-[#0ba4db] flex items-center justify-center text-white font-black text-sm">P</div>
                Paystack
              </button>
            </div>
            
            <div className="space-y-2 pt-2">
              <div className="text-sm text-neutral-500 text-center py-2">
                To complete your payment securely.
              </div>
            </div>
            <DialogFooter className="gap-2 pt-2 mt-4">
              <Button variant="outline" onClick={() => setStep("address")}>Back</Button>
              <Button onClick={pay} className="bg-[#0ba4db] hover:bg-[#0993c4]">
                Pay ₦ {fmt(total)}
              </Button>
            </DialogFooter>
          </>
        )}
      </DialogContent>
    </Dialog>
  );
}
