'use client'

import { useEffect, useState } from 'react'
import Image from 'next/image'
import { Star, ImageOff } from 'lucide-react'
import { useLocale, useTranslations } from 'next-intl'
import { Link } from '@/i18n/navigation'
import { getApiErrorMessage } from '@/lib/utils/apiError'

interface MyReview {
  id: string
  rating: number
  title: string | null
  content: string
  status: 'pending' | 'approved' | 'rejected'
  isVerified: boolean
  createdAt: string
  product: { id: string; name: string; slug: string | null; imageUrl: string | null }
}

const STATUS_COLORS: Record<MyReview['status'], string> = {
  pending: 'bg-yellow-100 text-yellow-700',
  approved: 'bg-green-100 text-green-700',
  rejected: 'bg-red-100 text-red-700',
}

// A customer's own reviews with their moderation state. Reviews land as
// `pending` (POST /api/frontend/reviews) and only show on the product page
// once an admin approves them — this is the one place the customer can see
// that a review they wrote is waiting, live, or was rejected.
export default function MyReviewsList() {
  const t = useTranslations('Account.reviews')
  const locale = useLocale()
  const [reviews, setReviews] = useState<MyReview[] | null>(null)
  const [error, setError] = useState('')

  useEffect(() => {
    let cancelled = false
    fetch(`/api/frontend/reviews/mine?locale=${encodeURIComponent(locale)}`, { credentials: 'include' })
      .then((res) => res.json())
      .then((data) => {
        if (cancelled) return
        if (data.success) setReviews(data.data)
        else setError(getApiErrorMessage(data, t('loadFailed')))
      })
      .catch(() => {
        if (!cancelled) setError(t('loadFailed'))
      })
    return () => {
      cancelled = true
    }
  }, [locale, t])

  if (error) {
    return <p className="text-center text-red-500 py-12">{error}</p>
  }

  if (reviews === null) {
    return (
      <div className="space-y-4" role="status" aria-busy="true">
        {Array.from({ length: 3 }, (_, i) => (
          <div key={i} className="h-32 rounded-xl bg-gray-100 animate-pulse" />
        ))}
      </div>
    )
  }

  if (reviews.length === 0) {
    return (
      <div className="text-center py-16 bg-white rounded-xl border border-gray-100">
        <Star size={40} className="mx-auto text-gray-300 mb-3" />
        <h3 className="font-semibold text-dark mb-1">{t('emptyTitle')}</h3>
        <p className="text-sm text-gray-custom">{t('emptyDescription')}</p>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {reviews.map((review) => (
        <div key={review.id} className="bg-white rounded-xl border border-gray-100 shadow-sm p-5 flex gap-4">
          <div className="relative w-20 h-20 shrink-0 rounded-lg overflow-hidden bg-gray-100 flex items-center justify-center">
            {review.product.imageUrl ? (
              <Image src={review.product.imageUrl} alt={review.product.name} fill sizes="80px" className="object-cover" />
            ) : (
              <ImageOff size={24} className="text-gray-300" />
            )}
          </div>

          <div className="flex-1 min-w-0">
            <div className="flex flex-wrap items-start justify-between gap-2">
              <div className="min-w-0">
                {review.product.slug ? (
                  <Link href={`/product/${review.product.slug}`} className="font-semibold text-dark hover:text-primary transition-colors">
                    {review.product.name}
                  </Link>
                ) : (
                  <span className="font-semibold text-dark">{review.product.name}</span>
                )}
                <div className="flex items-center gap-2 mt-1">
                  <div className="flex gap-0.5" aria-label={t('ratingLabel', { rating: review.rating })}>
                    {[1, 2, 3, 4, 5].map((n) => (
                      <Star
                        key={n}
                        size={14}
                        className={n <= review.rating ? 'text-yellow-400 fill-yellow-400' : 'text-gray-300'}
                      />
                    ))}
                  </div>
                  <span className="text-xs text-gray-custom">{new Date(review.createdAt).toLocaleDateString(locale)}</span>
                  {review.isVerified && (
                    <span className="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded-full">{t('verified')}</span>
                  )}
                </div>
              </div>
              <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${STATUS_COLORS[review.status]}`}>
                {t(`status.${review.status}`)}
              </span>
            </div>

            {review.title && <p className="text-dark font-medium mt-2">{review.title}</p>}
            <p className="text-sm text-gray-custom mt-1 whitespace-pre-line break-words">{review.content}</p>
            <p className="text-xs text-gray-custom mt-3">{t(`statusHint.${review.status}`)}</p>
          </div>
        </div>
      ))}
    </div>
  )
}
