'use client'

import { useEffect, useState } from 'react'
import dayjs from 'dayjs'
import { formatCurrency } from '@rentaldrivego/types'
import { apiFetch } from '@/lib/api'

interface OfferRow {
  id: string
  title: string
  type: string
  discountValue: number
  isActive: boolean
  isPublic: boolean
  isFeatured: boolean
  validUntil: string
  promoCode: string | null
}

export default function OffersPage() {
  const [rows, setRows] = useState<OfferRow[]>([])
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    apiFetch<OfferRow[]>('/offers')
      .then(setRows)
      .catch((err) => setError(err.message))
  }, [])

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-xl font-semibold text-slate-900">Offers</h2>
        <p className="text-sm text-slate-500 mt-1">Promotions shown on your site and optionally on the marketplace.</p>
      </div>
      <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
        {rows.map((offer) => (
          <div key={offer.id} className="card p-5">
            <div className="flex items-start justify-between gap-3">
              <div>
                <h3 className="text-base font-semibold text-slate-900">{offer.title}</h3>
                <p className="text-sm text-slate-500 mt-1">{offer.type} · ends {dayjs(offer.validUntil).format('MMM D, YYYY')}</p>
              </div>
              <span className={offer.isActive ? 'badge-green' : 'badge-gray'}>{offer.isActive ? 'Active' : 'Inactive'}</span>
            </div>
            <div className="mt-4 flex flex-wrap gap-2">
              {offer.isPublic && <span className="badge-blue">Marketplace</span>}
              {offer.isFeatured && <span className="badge-purple">Featured</span>}
              {offer.promoCode && <span className="badge-amber">{offer.promoCode}</span>}
            </div>
            <p className="mt-4 text-2xl font-bold text-slate-900">
              {offer.type === 'PERCENTAGE' ? `${offer.discountValue}%` : formatCurrency(offer.discountValue, 'MAD')}
            </p>
          </div>
        ))}
        {rows.length === 0 && !error && (
          <div className="card p-8 text-sm text-slate-400">No offers created yet.</div>
        )}
      </div>
      {error && <div className="card p-6 text-sm text-red-600">{error}</div>}
    </div>
  )
}
