'use client'

import { useState, useEffect } from 'react'
import * as motion from 'framer-motion/m'
import Link from 'next/link'
import { Zap, Clock, Shield, ArrowRight } from 'lucide-react'
import ProductCard from '@/components/frontend/ProductCard'
import type { FlashSaleData } from '@/lib/db/queries/getFlashSale'

interface FlashSaleClientProps {
  data: FlashSaleData
  labels: {
    title: string
    subtitle: string
    hours: string
    mins: string
    secs: string
    priceGuaranteed: string
    endingSoon: string
    footerNote: string
    // Already formatted server-side (t('viewAll', { count })) — only
    // present when there are more products than this preview shows.
    viewAll: string | null
  }
}

function secondsToParts(totalSeconds: number) {
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  const seconds = totalSeconds % 60
  return { hours, minutes, seconds }
}

// Client-only for the live countdown and add-to-cart interactivity — data
// (coupon, products, translated copy) is fetched server-side by
// FlashSale.tsx, see DATA_FETCHING_PATTERN.md.
export default function FlashSaleClient({ data, labels }: FlashSaleClientProps) {
  const [secondsLeft, setSecondsLeft] = useState(data.secondsRemaining)

  useEffect(() => {
    const timer = setInterval(() => {
      setSecondsLeft((prev) => (prev > 0 ? prev - 1 : 0))
    }, 1000)
    return () => clearInterval(timer)
  }, [])

  if (data.products.length === 0) return null

  const { hours, minutes, seconds } = secondsToParts(secondsLeft)

  return (
    <section className="my-16">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        whileInView={{ opacity: 1, y: 0 }}
        viewport={{ once: true }}
        className="bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-100"
      >
        {/* Header */}
        <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-2xl font-bold text-white">
                  {data.title ?? labels.title}
                  {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 ?? labels.subtitle}</p>
              </div>
            </div>

            <div className="flex gap-3">
              <div className="bg-white/20 backdrop-blur rounded-xl px-4 py-2 text-center">
                <div className="text-2xl font-bold text-white tabular-nums">
                  {String(hours).padStart(2, '0')}
                </div>
                <div className="text-white/70 text-xs">{labels.hours}</div>
              </div>
              <div className="text-white text-2xl font-bold self-center">:</div>
              <div className="bg-white/20 backdrop-blur rounded-xl px-4 py-2 text-center">
                <div className="text-2xl font-bold text-white tabular-nums">
                  {String(minutes).padStart(2, '0')}
                </div>
                <div className="text-white/70 text-xs">{labels.mins}</div>
              </div>
              <div className="text-white text-2xl font-bold self-center">:</div>
              <div className="bg-white/20 backdrop-blur rounded-xl px-4 py-2 text-center">
                <div className="text-2xl font-bold text-white tabular-nums">
                  {String(seconds).padStart(2, '0')}
                </div>
                <div className="text-white/70 text-xs">{labels.secs}</div>
              </div>
            </div>
          </div>
        </div>

        {/* Stats Bar */}
        <div className="bg-light-gray px-6 py-3 flex flex-wrap justify-between items-center gap-3 border-b border-gray-100">
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-1">
              <Shield className="w-4 h-4 text-primary" />
              <span className="text-sm text-gray-custom">{labels.priceGuaranteed}</span>
            </div>
          </div>
          <div className="flex items-center gap-1">
            <Clock className="w-4 h-4 text-primary" />
            <span className="text-sm font-medium text-primary">{labels.endingSoon}</span>
          </div>
        </div>

        {/* Products */}
        <div className="p-6">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {data.products.map((product, index) => (
              <motion.div
                key={product.id}
                initial={{ opacity: 0, y: 20 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true }}
                transition={{ delay: index * 0.1 }}
              >
                <ProductCard
                  id={product.id}
                  title={product.title}
                  price={product.price}
                  oldPrice={product.oldPrice}
                  discount={product.discountPercent}
                  image={product.imageUrl ?? '📦'}
                  slug={product.slug}
                  productType={product.type}
                />
              </motion.div>
            ))}
          </div>
        </div>

        {labels.viewAll && (
          <div className="px-6 pb-6 text-center">
            <Link
              href="/offers/flash-sale"
              className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full text-sm font-semibold text-white hover:opacity-90 transition-opacity"
              style={{ background: 'var(--primary)' }}
            >
              {labels.viewAll}
              <ArrowRight size={16} />
            </Link>
          </div>
        )}

        {/* Footer Note */}
        <div className="bg-light-gray px-6 py-3 text-center border-t border-gray-100">
          <p className="text-xs text-gray-custom">{labels.footerNote}</p>
        </div>
      </motion.div>
    </section>
  )
}
