"use client"

import Image from "next/image"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { rackListings, vendors, beaches, getInventoryForVendor, RackListing } from "@/lib/mock-data"
import { useAuth } from "@/lib/auth-context"
import { loginHrefWithRedirect } from "@/lib/auth-redirect"
import { Sparkles, Percent, ChevronRight } from "lucide-react"

interface TheRackProps {
  beachId?: string
  limit?: number
}

export function TheRack({ beachId, limit = 4 }: TheRackProps) {
  const today = new Date().toISOString().split("T")[0]
  let listings = rackListings.filter((l) => l.validDate === today)
  if (beachId) listings = listings.filter((l) => l.beachId === beachId)
  listings = listings.slice(0, limit)

  if (listings.length === 0) return null

  return (
    <section className="mb-8">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="w-11 h-11 rounded-xl bg-gradient-to-br from-[var(--beach-gold)]/20 to-[var(--beach-cyan)]/20 flex items-center justify-center border border-[var(--beach-gold)]/30">
            <Sparkles className="w-5 h-5 text-[var(--beach-gold)]" />
          </div>
          <div>
            <h2 className="text-xl font-bold text-foreground tracking-tight">The Rack</h2>
            <p className="text-sm text-muted-foreground">Today&apos;s featured deals</p>
          </div>
        </div>
        <Link href="/rack">
          <Button variant="ghost" size="sm" className="gap-1 text-primary font-medium">
            View all
            <ChevronRight className="w-4 h-4" />
          </Button>
        </Link>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {listings.map((listing) => (
          <RackCard key={listing.id} listing={listing} />
        ))}
      </div>
    </section>
  )
}

function RackCard({ listing }: { listing: RackListing }) {
  const { user, isLoading: authLoading } = useAuth()
  const vendor = vendors.find((v) => v.id === listing.vendorId)
  const beach = beaches.find((b) => b.id === listing.beachId)
  const primaryItem = getInventoryForVendor(listing.vendorId)[0]
  const discount = Math.round(((listing.originalPrice - listing.rackPrice) / listing.originalPrice) * 100)
  const checkoutPath = primaryItem ? `/item/${primaryItem.id}/checkout` : null
  const bookHref = checkoutPath ? (user ? checkoutPath : loginHrefWithRedirect(checkoutPath)) : null

  return (
    <article className="explore-card flex flex-col hover:-translate-y-0.5 group/card">
      <div className="relative h-40 overflow-hidden bg-muted rounded-t-[1.25rem]">
        <Image
          src={listing.image}
          alt={listing.title}
          fill
          className="object-cover transition-transform duration-500 ease-out group-hover/card:scale-105"
          sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw"
        />
        <div className="absolute inset-0 bg-gradient-to-t from-black/75 via-black/20 to-transparent" />
        {/* Diagonal save ribbon */}
        <div className="absolute top-0 right-0">
          <div
            className="flex items-center gap-1 px-4 py-1.5 text-xs font-bold text-white shadow-lg"
            style={{
              background: "linear-gradient(135deg, var(--beach-gold), var(--beach-cyan))",
              transform: "translate(12px, -2px) rotate(45deg)",
              boxShadow: "0 2px 8px rgba(0,0,0,0.2)",
            }}
          >
            <Percent className="w-3.5 h-3.5" />
            {discount}% OFF
          </div>
        </div>
        {beach && (
          <div className="absolute bottom-2 left-2">
            <span className="rounded-md bg-black/50 backdrop-blur-sm text-white text-[10px] font-medium px-2 py-1">
              {beach.name}
            </span>
          </div>
        )}
      </div>

      <div className="flex-1 flex flex-col p-5 border-t border-border/60">
        <h3 className="font-semibold text-foreground text-sm leading-snug line-clamp-2 mb-1">
          {listing.title}
        </h3>
        <p className="text-xs text-muted-foreground line-clamp-2 mb-3">{listing.description}</p>

        <div className="flex items-end justify-between gap-3 mt-auto">
          <div className="flex items-baseline gap-2">
            <span className="text-xl font-bold text-primary">${listing.rackPrice}</span>
            <span className="text-sm text-muted-foreground line-through">${listing.originalPrice}</span>
          </div>
          {primaryItem ? (
            authLoading ? (
              <Button size="sm" className="rounded-lg h-9 text-xs shrink-0" disabled>
                …
              </Button>
            ) : (
              <Button size="sm" className="rounded-lg h-9 text-xs font-semibold shrink-0" asChild>
                <Link href={bookHref ?? "#"}>{user ? "Book" : "Sign in to book"}</Link>
              </Button>
            )
          ) : vendor ? (
            <Button size="sm" className="rounded-lg h-9 text-xs font-semibold shrink-0" asChild>
              <Link href={`/vendor/${vendor.id}`}>Book</Link>
            </Button>
          ) : (
            <Button size="sm" className="rounded-lg h-9 text-xs shrink-0" disabled>
              Book
            </Button>
          )}
        </div>

        {vendor && (
          <Link
            href={`/vendor/${vendor.id}`}
            className="text-[11px] text-muted-foreground hover:text-primary mt-2 block truncate"
          >
            by {vendor.name}
          </Link>
        )}
      </div>
    </article>
  )
}
