'use client'

import { useState, useEffect } from 'react'
import Image from 'next/image'
import { useI18n } from '@/lib/i18n'

interface PastDrop {
  id: number
  item: string
  size: number
  fill: number
  unit: string
  ppu: number
  image_url: string | null
  images?: string[] // Array of image URLs (up to 4)
  created_at: string
  soldOutInHours: number
}

interface PastDropsProps {
  limit?: number
  showMoreLink?: boolean
}

export default function PastDrops({ limit, showMoreLink = false }: PastDropsProps = {}) {
  const { t } = useI18n()
  const [drops, setDrops] = useState<PastDrop[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetchPastDrops()

    // Poll past drops every 30 seconds
    const interval = setInterval(() => {
      fetchPastDrops()
    }, 30000) // 30 seconds

    return () => clearInterval(interval)
  }, [])

  const fetchPastDrops = async () => {
    try {
      const response = await fetch('/api/drops/past', {
        // Add cache control to prevent stale data
        cache: 'no-store',
      })
      if (response.ok) {
        const data = await response.json()
        setDrops(data)
      }
    } catch (error) {
      console.error('Error fetching past drops:', error)
    } finally {
      setLoading(false)
    }
  }

  const formatSoldOutTime = (hours: number) => {
    if (hours < 1) {
      return `${t('pastDrops.soldOutIn')} ${t('pastDrops.lessThan1h')}`
    } else if (hours === 1) {
      return `${t('pastDrops.soldOutIn')} ${t('pastDrops.1h')}`
    } else if (hours < 24) {
      return `${t('pastDrops.soldOutIn')} ${t('pastDrops.hours', { hours })}`
    } else {
      const days = Math.floor(hours / 24)
      const remainingHours = hours % 24
      if (remainingHours === 0) {
        return days === 1 
          ? `${t('pastDrops.soldOutIn')} ${t('pastDrops.1day')}` 
          : `${t('pastDrops.soldOutIn')} ${t('pastDrops.days', { days })}`
      } else {
        return `${t('pastDrops.soldOutIn')} ${t('pastDrops.daysHours', { days, hours: remainingHours })}`
      }
    }
  }

  const formatDateAndTime = (dateString: string) => {
    const date = new Date(dateString)
    const day = date.getDate()
    const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    const month = monthNames[date.getMonth()]
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    return `${day} ${month} · ${hours}:${minutes}`
  }

  const formatQuantity = (size: number, unit: string) => {
    return `${size}${unit}`
  }

  if (loading) {
    return (
      <div className="past">
        <p style={{ color: 'var(--muted)', textAlign: 'center' }}>{t('pastDrops.loading')}</p>
      </div>
    )
  }

  if (drops.length === 0) {
    return (
      <div className="past">
        <p style={{ color: 'var(--muted)', textAlign: 'center' }}>
          {t('pastDrops.noDrops')}
        </p>
      </div>
    )
  }

  const displayedDrops = limit ? drops.slice(0, limit) : drops
  const hasMore = limit && drops.length > limit

  return (
    <>
      <div className="past">
        {displayedDrops.map((drop) => {
          // Get images array (prioritize new images array, fallback to legacy image_url)
          const images = drop.images && drop.images.length > 0 
            ? drop.images 
            : (drop.image_url ? [drop.image_url] : [])
          
          return (
            <div key={drop.id} className="card">
              {images.length > 0 ? (
                <div style={{ marginBottom: '12px', display: 'grid', gridTemplateColumns: images.length > 1 ? '1fr 1fr' : '1fr', gap: '4px' }}>
                  {images.slice(0, 4).map((imgUrl, index) => (
                    <Image
                      key={index}
                      src={imgUrl}
                      alt={`${drop.item} - Image ${index + 1}`}
                      width={300}
                      height={300}
                      style={{
                        width: '100%',
                        height: '200px',
                        borderRadius: '12px',
                        objectFit: 'cover',
                      }}
                    />
                  ))}
                </div>
              ) : (
                <div
                  style={{
                    width: '100%',
                    height: '200px',
                    background: 'var(--bg-soft)',
                    borderRadius: '12px',
                    marginBottom: '12px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: 'var(--muted)',
                  }}
                >
                  {t('common.noImage')}
                </div>
              )}
              <strong>{drop.item}</strong>
              <br />
              <span className="meta">{formatSoldOutTime(drop.soldOutInHours)}</span>
              <br />
              <span className="meta" style={{ fontSize: '13px', marginTop: '4px', display: 'block' }}>
                {formatQuantity(drop.size, drop.unit)} · {formatDateAndTime(drop.created_at)}
              </span>
            </div>
          )
        })}
      </div>
      {showMoreLink && hasMore && (
        <div style={{ textAlign: 'center', marginTop: '30px' }}>
          <a
            href="/past-drops"
            style={{
              color: 'var(--accent)',
              textDecoration: 'none',
              fontSize: '14px',
              fontWeight: 500,
            }}
          >
            {t('pastDrops.more')}
          </a>
        </div>
      )}
    </>
  )
}

