import { createFileRoute, Link } from "@tanstack/react-router";
import { useState } from "react";
import { Header } from "@/components/site/Header";
import { SignInModal, CartDrawer, CheckoutFlow } from "@/components/site/Modals";
import { Store, ShoppingCart, MapPin, Mail, ExternalLink } from "lucide-react";
import { useStore, fmt, type Product } from "@/lib/store";
import { toast } from "sonner";

export const Route = createFileRoute("/$storeSlug")({
  head: ({ params }) => ({ meta: [{ title: `${params.storeSlug} — SulejaMarket` }] }),
  component: VendorStorefrontPage,
});

function VendorStorefrontPage() {
  const { storeSlug } = Route.useParams();
  const [signInOpen, setSignInOpen] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  
  const { vendors, getAllProducts } = useStore();
  
  const vendor = vendors.find(v => v.storeSlug === storeSlug && v.status === "approved");
  const products = vendor ? getAllProducts().filter(p => p.vendorEmail === vendor.contactEmail) : [];

  return (
    <div className="min-h-screen bg-neutral-50 flex flex-col">
      <SignInModal open={signInOpen} onOpenChange={setSignInOpen} />
      <CartDrawer open={cartOpen} onOpenChange={setCartOpen} onCheckout={() => { setCartOpen(false); setCheckoutOpen(true); }} />
      <CheckoutFlow open={checkoutOpen} onOpenChange={setCheckoutOpen} />
      <Header onOpenCart={() => setCartOpen(true)} onOpenSignIn={() => setSignInOpen(true)} />

      <main className="flex-1 max-w-[1200px] w-full mx-auto px-4 py-8 flex flex-col gap-8">
        {!vendor ? (
          <div className="flex-1 flex flex-col items-center justify-center text-center py-20">
            <Store className="w-16 h-16 text-neutral-300 mb-4" />
            <h1 className="text-3xl font-bold mb-2">Store Not Found</h1>
            <p className="text-neutral-500 mb-6">The store you are looking for does not exist or is pending approval.</p>
            <Link to="/" className="text-orange-500 font-medium hover:underline">Return to Marketplace</Link>
          </div>
        ) : (
          <>
            <div className="bg-white rounded-xl border overflow-hidden">
              <div 
                className="h-32 sm:h-48 bg-gradient-to-r from-orange-400 to-orange-600 bg-cover bg-center"
                style={vendor.banner ? { backgroundImage: `url(${vendor.banner})` } : {}}
              ></div>
              <div className="px-6 pb-6 sm:px-10 relative">
                <div className="w-24 h-24 sm:w-32 sm:h-32 bg-white rounded-xl border-4 border-white shadow-sm flex items-center justify-center -mt-12 sm:-mt-16 mb-4 bg-orange-50 overflow-hidden">
                  {vendor.logo ? (
                    <img src={vendor.logo} alt={vendor.businessName} className="w-full h-full object-cover" />
                  ) : (
                    <span className="text-3xl sm:text-5xl font-black text-orange-500">{vendor.businessName.charAt(0)}</span>
                  )}
                </div>
                <div className="flex flex-col sm:flex-row sm:items-end justify-between gap-4">
                  <div>
                    <h1 className="text-3xl font-bold">{vendor.businessName}</h1>
                    <p className="text-sm text-neutral-500 mt-1 flex items-center gap-2">
                      <Store className="w-4 h-4" /> Official SulejaMarket Vendor
                    </p>
                  </div>
                </div>
              </div>
            </div>

            <div className="flex flex-col md:flex-row gap-8">
              <div className="w-full md:w-64 flex-shrink-0 space-y-6">
                <div className="bg-white rounded-xl border p-5 space-y-4">
                  <h3 className="font-bold border-b pb-2">About Store</h3>
                  {vendor.businessType && <div className="text-sm text-neutral-600">{vendor.businessType}</div>}
                  {vendor.city && vendor.state && (
                    <div className="flex items-start gap-2 text-sm text-neutral-600">
                      <MapPin className="w-4 h-4 text-neutral-400 mt-0.5 shrink-0" />
                      <span>{vendor.address ? `${vendor.address}, ` : ""}{vendor.city}, {vendor.state}</span>
                    </div>
                  )}
                  {vendor.contactEmail && (
                    <div className="flex items-start gap-2 text-sm text-neutral-600 break-all">
                      <Mail className="w-4 h-4 text-neutral-400 mt-0.5 shrink-0" />
                      <span>{vendor.contactEmail}</span>
                    </div>
                  )}
                  {vendor.contactPhone && (
                    <div className="flex items-start gap-2 text-sm text-neutral-600 break-all">
                      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-4 h-4 text-neutral-400 mt-0.5 shrink-0"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
                      <span>{vendor.contactPhone} {vendor.altPhone ? ` / ${vendor.altPhone}` : ""}</span>
                    </div>
                  )}
                  {vendor.rcNumber && (
                    <div className="flex items-start gap-2 text-sm text-neutral-600 break-all">
                      <Store className="w-4 h-4 text-neutral-400 mt-0.5 shrink-0" />
                      <span>RC/BN: {vendor.rcNumber}</span>
                    </div>
                  )}
                  {vendor.website && (
                    <div className="flex items-start gap-2 text-sm text-neutral-600 break-all">
                      <ExternalLink className="w-4 h-4 text-neutral-400 mt-0.5 shrink-0" />
                      <a href={vendor.website.startsWith('http') ? vendor.website : `https://${vendor.website}`} target="_blank" rel="noreferrer" className="text-orange-500 hover:underline">
                        Website / Social
                      </a>
                    </div>
                  )}
                </div>
              </div>

              <div className="flex-1">
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-xl font-bold flex items-center gap-2">Products <span className="text-sm font-normal text-neutral-500">({products.length})</span></h2>
                </div>
                
                {products.length === 0 ? (
                  <div className="bg-white border border-dashed rounded-xl p-12 text-center text-neutral-500">
                    This store doesn't have any products listed yet.
                  </div>
                ) : (
                  <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">
                    {products.map((p) => (
                      <ProductCard key={p.id} p={p} />
                    ))}
                  </div>
                )}
              </div>
            </div>
          </>
        )}
      </main>
    </div>
  );
}

function ProductCard({ p }: { p: Product }) {
  const { addToCart } = useStore();
  return (
    <div className="bg-white rounded-lg border overflow-hidden hover:shadow-md transition group flex flex-col h-full">
      <Link to="/product/$id" params={{ id: p.id }} className="block aspect-square overflow-hidden relative bg-neutral-100">
        <img src={(p.images?.[0] || `https://picsum.photos/seed/${p.seed}/400/400`)} alt={p.name} className="w-full h-full object-cover group-hover:scale-105 transition duration-500" />
        {p.disc && <div className="absolute top-2 left-2 bg-orange-500 text-white text-[10px] font-bold px-2 py-1 rounded">{p.disc}</div>}
      </Link>
      <div className="p-3 flex flex-col flex-1">
        <div className="text-[10px] text-neutral-400 uppercase tracking-wider mb-1">{p.category}</div>
        <Link to="/product/$id" params={{ id: p.id }} className="font-medium text-sm leading-tight hover:text-orange-600 line-clamp-2 mb-2 flex-1">
          {p.name}
        </Link>
        <div className="flex items-center justify-between mt-auto pt-2">
          <div>
            <div className="font-bold text-sm">₦ {fmt(p.price)}</div>
            {p.old && <div className="text-xs text-neutral-400 line-through">₦ {fmt(p.old)}</div>}
          </div>
          <button
            onClick={() => {
              addToCart({ id: p.id, name: p.name, price: p.price, seed: p.seed });
              toast.success("Added to cart");
            }}
            className="w-8 h-8 rounded-full bg-neutral-100 flex items-center justify-center text-neutral-600 hover:bg-orange-50 hover:text-orange-600 transition"
          >
            <ShoppingCart className="w-4 h-4" />
          </button>
        </div>
      </div>
    </div>
  );
}
