import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { ImageOff, MapPin, Megaphone, Pencil, Trash2 } from 'lucide-react'
import { useLocale } from '@meshkee/dashboard-ui'
import type { UserProductListItem } from '../types/userProduct'
import { formatIrtPrice } from '../utils/irtPrice'
import { useT } from '../i18n/useT'
import { Tooltip } from './Tooltip'
import styles from './UserProductCard.module.css'

interface UserProductCardProps {
  product: UserProductListItem
  to?: string
  onEdit?: (id: string) => void
  onRemove?: (id: string) => void
  onPromote?: (id: string) => void
  busyAction?: 'remove' | 'promote' | null
}

export function UserProductCard({
  product,
  to,
  onEdit,
  onRemove,
  onPromote,
  busyAction = null,
}: UserProductCardProps) {
  const t = useT()
  const { locale } = useLocale()
  const isFa = locale === 'fa'
  const titleFa = product.titleFa || product.title
  const titleEn = product.titleEn?.trim() || ''
  const title = isFa ? titleFa : titleEn || titleFa
  const secondary = isFa ? titleEn : titleEn ? titleFa : ''
  const city = isFa ? product.cityNameFa || product.cityName : product.cityName
  const category = isFa
    ? product.categoryNameFa || product.categoryName
    : product.categoryName
  const imageSrc = product.imageUrl?.trim() || ''
  const [imageFailed, setImageFailed] = useState(false)
  const showImage = Boolean(imageSrc) && !imageFailed
  const currency = (product.priceCurrency || 'IRT').toUpperCase()
  const priceLabel =
    product.price == null
      ? t('myProducts.priceUnavailable')
      : currency === 'IRT'
        ? formatIrtPrice(product.price)
        : `${product.price.toLocaleString('en-US')} ${currency}`
  const showControls = Boolean(onEdit || onRemove || onPromote)
  const isBusy = busyAction != null

  useEffect(() => {
    setImageFailed(false)
  }, [imageSrc])

  const statusLabel =
    product.status === 'published'
      ? t('myProducts.status.published')
      : product.status === 'archived'
        ? t('myProducts.status.archived')
        : product.status === 'rejected'
          ? t('myProducts.status.rejected')
          : t('myProducts.status.pending')

  const mediaAndBody = (
    <>
      <div className={styles.imageWrap}>
        {showImage ? (
          <img
            src={imageSrc}
            alt={title}
            className={styles.image}
            loading="lazy"
            onError={() => setImageFailed(true)}
          />
        ) : (
          <div className={styles.imagePlaceholder} aria-hidden="true">
            <ImageOff size={28} strokeWidth={1.5} />
          </div>
        )}
        <span className={styles.badge} data-status={product.status}>
          {statusLabel}
        </span>
        {product.promoted ? (
          <span className={styles.promotedBadge}>{t('myProducts.promoted')}</span>
        ) : null}
      </div>

      <div className={styles.body} dir={isFa ? 'rtl' : 'ltr'}>
        <h3 className={styles.title}>{title}</h3>
        {secondary ? <p className={styles.secondary}>{secondary}</p> : null}
        {category ? <span className={styles.categoryChip}>{category}</span> : null}
        <div className={styles.metaRow}>
          <p className={styles.price}>{priceLabel}</p>
          <p className={styles.location} dir={isFa ? 'rtl' : 'ltr'}>
            <MapPin size={12} aria-hidden="true" />
            <span>{city}</span>
          </p>
        </div>
      </div>
    </>
  )

  return (
    <article className={styles.card} data-card-hover>
      {to ? (
        <Link to={to} className={styles.mainLink}>
          {mediaAndBody}
        </Link>
      ) : (
        mediaAndBody
      )}

      {showControls ? (
        <div className={styles.controls}>
          {onEdit ? (
            <Tooltip label={t('myProducts.edit')}>
              <button
                type="button"
                onClick={() => onEdit(product.id)}
                aria-label={t('myProducts.edit')}
                disabled={isBusy}
              >
                <Pencil size={16} />
              </button>
            </Tooltip>
          ) : null}
          {onPromote ? (
            <Tooltip
              label={
                product.promoted ? t('myProducts.promoted') : t('myProducts.promote')
              }
            >
              <button
                type="button"
                onClick={() => onPromote(product.id)}
                aria-label={t('myProducts.promote')}
                disabled={isBusy || product.promoted}
              >
                <Megaphone size={16} />
              </button>
            </Tooltip>
          ) : null}
          {onRemove ? (
            <Tooltip label={t('myProducts.remove')}>
              <button
                type="button"
                className={styles.danger}
                onClick={() => onRemove(product.id)}
                aria-label={t('myProducts.remove')}
                disabled={isBusy}
              >
                <Trash2 size={16} />
              </button>
            </Tooltip>
          ) : null}
        </div>
      ) : null}
    </article>
  )
}
