'use client'

import { useState } from 'react'
import { Zap, Clock } from 'lucide-react'
import ProductCard from '@/components/frontend/ProductCard'
import Pagination from '@/components/frontend/Pagination'
import FlashSaleTimer from '@/components/frontend/offers/FlashSaleTimer'
import type { FlashSaleData } from '@/lib/db/queries/getFlashSale'

const PAGE_SIZE = 9

interface OfferSectionProps {
  data: FlashSaleData
  fallbackTitle: string
  fallbackSubtitle: string
  endsInLabel: string
}

// One coupon's ("offer") own card on the /offers/flash-sale listing — own
// countdown, own product grid, own pagination (client-side over the
// already-fetched up-to-FULL_PAGE_LIMIT product list, no re-fetch per page
// turn). See DATA_FETCHING_PATTERN.md and getFlashSale.ts's getAllOffers.
export default function OfferSection({ data, fallbackTitle, fallbackSubtitle, endsInLabel }: OfferSectionProps) {
  const [page, setPage] = useState(1)
  // A relative duration added to "now" at mount — not a DATETIME parsed
  // from the DB, so no timezone-conversion risk (DATA_FETCHING_PATTERN.md
  // point 5). Lazy initializer, not a direct Date.now() call in render,
  // which the react-hooks/purity rule flags.
  const [endTime] = useState(() => new Date(Date.now() + data.secondsRemaining * 1000))

  const totalPages = Math.ceil(data.products.length / PAGE_SIZE)
  const pageProducts = data.products.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE)

  return (
    <section id={data.couponId} className="bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-100 scroll-mt-24">
      <div
        className="px-6 py-4"
        style={{ background: `linear-gradient(to right, var(--primary), var(--secondary))` }}
      >
        <div className="flex flex-wrap justify-between items-center gap-4">
          <div className="flex items-center gap-3">
            <div className="bg-white/20 p-2 rounded-xl">
              <Zap className="w-6 h-6 text-white" />
            </div>
            <div>
              <h2 className="text-xl md:text-2xl font-bold text-white">
                {data.title ?? fallbackTitle}
                {data.badge && (
                  <span className="ml-2 align-middle text-xs font-semibold bg-white/25 px-2 py-1 rounded-full">
                    {data.badge}
                  </span>
                )}
              </h2>
              <p className="text-white/80 text-sm">{data.description ?? fallbackSubtitle}</p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-white/80" />
            <span className="text-white/90 text-sm font-medium">{endsInLabel}</span>
            <FlashSaleTimer endTime={endTime} />
          </div>
        </div>
      </div>

      <div className="p-6">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {pageProducts.map((product) => (
            <ProductCard
              key={product.id}
              id={product.id}
              title={product.title}
              price={product.price}
              oldPrice={product.oldPrice}
              discount={product.discountPercent}
              image={product.imageUrl ?? '📦'}
              slug={product.slug}
              productType={product.type}
            />
          ))}
        </div>

        <Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
      </div>
    </section>
  )
}
