import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import {
  Check,
  ImageOff,
  MapPin,
  Megaphone,
  Pencil,
  Trash2,
  User,
} 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
  onPromote: (id: string) => void
  onChangeStatus: (id: string) => void
  onRemove: (id: string) => void
  busyAction?: 'remove' | 'promote' | 'status' | null
}

export function UserProductCard({
  product,
  to,
  onEdit,
  onPromote,
  onChangeStatus,
  onRemove,
  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 owner = isFa ? product.ownerNameFa || product.ownerName : product.ownerName
  const imageSrc = product.imageUrl?.trim() || ''
  const [imageFailed, setImageFailed] = useState(false)
  const showImage = Boolean(imageSrc) && !imageFailed
  const isBusy = busyAction != null
  const currency = (product.priceCurrency || 'IRT').toUpperCase()
  const priceLabel =
    product.price == null
      ? t('customerProducts.priceUnavailable')
      : currency === 'IRT'
        ? formatIrtPrice(product.price)
        : `${product.price.toLocaleString('en-US')} ${currency}`

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

  const statusLabel =
    product.status === 'published'
      ? t('customerProducts.status.published')
      : product.status === 'archived'
        ? t('customerProducts.status.archived')
        : product.status === 'rejected'
          ? t('customerProducts.status.rejected')
          : t('customerProducts.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('customerProducts.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}
        {owner ? (
          <p className={styles.owner}>
            <User size={12} aria-hidden="true" />
            <span>{owner}</span>
          </p>
        ) : 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
      )}

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