import { useEffect, useMemo, useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { ImageOff, MapPin, Pencil } from 'lucide-react'
import { Breadcrumbs, useLocale, useToast } from '@meshkee/dashboard-ui'
import { useT } from '../i18n/useT'
import { ApiError, isAbortError } from '../lib/api'
import {
  getMyUserProduct,
  getMyUserProductCategoryTechnicalForm,
  type TechnicalFormField,
  type UserProductDetail,
  type UserProductTechnicalValueInput,
} from '../services/userProductsService'
import { formatIrtPrice } from '../utils/irtPrice'
import pageStyles from '../components/PageContent.module.css'
import styles from './MyProductDetailsPage.module.css'

function formatTechnicalValue(
  field: TechnicalFormField,
  value: UserProductTechnicalValueInput | undefined,
): string {
  if (!value) return '—'
  if (value.textValue != null && value.textValue.trim()) return value.textValue
  if (value.optionId) {
    return field.options.find((option) => option.id === value.optionId)?.label ?? value.optionId
  }
  if (value.optionIds?.length) {
    return value.optionIds
      .map(
        (optionId) =>
          field.options.find((option) => option.id === optionId)?.label ?? optionId,
      )
      .join(', ')
  }
  return '—'
}

export function MyProductDetailsPage() {
  const { id } = useParams<{ id: string }>()
  const t = useT()
  const { locale } = useLocale()
  const navigate = useNavigate()
  const { showToast } = useToast()
  const isFa = locale === 'fa'

  const [product, setProduct] = useState<UserProductDetail | null>(null)
  const [technicalFields, setTechnicalFields] = useState<TechnicalFormField[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!id) return

    const controller = new AbortController()

    async function load() {
      setLoading(true)
      setError('')
      try {
        const response = await getMyUserProduct(id!, controller.signal)
        if (controller.signal.aborted) return
        setProduct(response.product)

        if (response.product.categoryId) {
          const formResponse = await getMyUserProductCategoryTechnicalForm(
            response.product.categoryId,
            controller.signal,
          )
          if (controller.signal.aborted) return
          setTechnicalFields(formResponse.form?.fields ?? [])
        } else {
          setTechnicalFields([])
        }
      } catch (err) {
        if (isAbortError(err) || controller.signal.aborted) return
        const message =
          err instanceof ApiError ? err.message : t('myProducts.error.loadDetail')
        setError(message)
        setProduct(null)
        showToast(message, 'error')
      } finally {
        if (!controller.signal.aborted) setLoading(false)
      }
    }

    void load()
    return () => controller.abort()
  }, [id, showToast, t])

  const technicalRows = useMemo(() => {
    if (!product) return []
    const byField = new Map(
      (product.technicalValues ?? []).map((item) => [item.fieldId, item]),
    )
    return technicalFields.map((field) => ({
      id: field.id,
      label: field.label,
      value: formatTechnicalValue(field, byField.get(field.id)),
    }))
  }, [product, technicalFields])

  if (loading) {
    return (
      <main className={pageStyles.content}>
        <p className={styles.status}>{t('myProducts.loading')}</p>
      </main>
    )
  }

  if (error || !product) {
    return (
      <main className={pageStyles.content}>
        <p className={styles.error}>{error || t('myProducts.error.loadDetail')}</p>
        <Link to="/my-products" className={styles.backLink}>
          {t('myProducts.backToList')}
        </Link>
      </main>
    )
  }

  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 country = isFa
    ? product.countryNameFa || product.countryName
    : product.countryName
  const category = isFa
    ? product.categoryNameFa || product.categoryName
    : product.categoryName
  const location = [city, country].filter(Boolean).join(isFa ? '، ' : ', ')
  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 conditionLabel =
    product.condition === 'new'
      ? t('myProducts.condition.new')
      : product.condition === 'stock'
        ? t('myProducts.condition.stock')
        : product.condition === 'needs_repair'
          ? t('myProducts.condition.needs_repair')
          : product.condition === 'scrap'
            ? t('myProducts.condition.scrap')
            : '—'
  const imageSrc = product.imageUrl?.trim() || ''
  const galleryImages = (product.images ?? [])
    .map((item) => item.url?.trim())
    .filter((url): url is string => Boolean(url))
  const currency = (product.priceCurrency || 'IRT').toUpperCase()
  const priceLabel =
    product.price == null
      ? t('myProducts.priceUnavailable')
      : currency === 'IRT'
        ? formatIrtPrice(product.price)
        : `${Number(product.price).toLocaleString('en-US')} ${currency}`

  return (
    <main className={pageStyles.content}>
      <Breadcrumbs
        items={[
          { label: t('nav.home'), href: '/' },
          { label: t('myProducts.title'), href: '/my-products' },
          { label: title },
        ]}
      />

      <div className={styles.headerRow}>
        <div>
          <h2 className={pageStyles.pageTitle}>{t('myProducts.detailsTitle')}</h2>
          <p className={pageStyles.pageSubtitle}>{t('myProducts.detailsSubtitle')}</p>
        </div>
        <button
          type="button"
          className={styles.editBtn}
          onClick={() => navigate(`/my-products/${product.id}/edit`)}
        >
          <Pencil size={16} />
          {t('myProducts.edit')}
        </button>
      </div>

      <div className={styles.layout} dir={isFa ? 'rtl' : 'ltr'}>
        <div className={styles.gallery}>
          <div className={styles.mainImage}>
            {imageSrc ? (
              <img src={imageSrc} alt={title} className={styles.image} />
            ) : (
              <div className={styles.imagePlaceholder}>
                <ImageOff size={36} 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>
          {galleryImages.length > 0 ? (
            <div className={styles.galleryThumbs}>
              {galleryImages.map((url) => (
                <div key={url} className={styles.galleryThumb}>
                  <img src={url} alt="" />
                </div>
              ))}
            </div>
          ) : null}
        </div>

        <div className={styles.details}>
          {category ? <span className={styles.categoryChip}>{category}</span> : null}
          <h1 className={styles.title}>{title}</h1>
          {secondary ? <p className={styles.secondary}>{secondary}</p> : null}

          <div className={styles.summaryRow}>
            <p className={styles.price} dir="ltr">
              {priceLabel}
            </p>
            <div className={styles.summaryMeta} dir={isFa ? 'rtl' : 'ltr'}>
              <span className={styles.metaItem}>
                <MapPin size={14} aria-hidden />
                {location || '—'}
              </span>
            </div>
          </div>

          <dl className={styles.metaGrid}>
            <div>
              <dt>{t('myProducts.fields.country')}</dt>
              <dd>{country || '—'}</dd>
            </div>
            <div>
              <dt>{t('myProducts.fields.city')}</dt>
              <dd>{city || '—'}</dd>
            </div>
            <div>
              <dt>{t('myProducts.fields.condition')}</dt>
              <dd>{conditionLabel}</dd>
            </div>
            {product.priceByExpert ? (
              <div>
                <dt>{t('myProducts.fields.priceByExpert')}</dt>
                <dd>{t('myProducts.yes')}</dd>
              </div>
            ) : null}
          </dl>

          {product.description ? (
            <section className={styles.section}>
              <h3>{t('myProducts.fields.description')}</h3>
              <p className={styles.prose}>{product.description}</p>
            </section>
          ) : null}

          {product.deliveryNote ? (
            <section className={styles.section}>
              <h3>{t('myProducts.fields.deliveryNote')}</h3>
              <p className={styles.prose}>{product.deliveryNote}</p>
            </section>
          ) : null}

          {product.technicalNotes ? (
            <section className={styles.section}>
              <h3>{t('myProducts.fields.technicalNotes')}</h3>
              <p className={styles.prose}>{product.technicalNotes}</p>
            </section>
          ) : null}

          {technicalRows.length > 0 ? (
            <section className={styles.section}>
              <h3>{t('myProducts.technical.categoryForm')}</h3>
              <dl className={styles.techGrid}>
                {technicalRows.map((row) => (
                  <div key={row.id}>
                    <dt>{row.label}</dt>
                    <dd>{row.value}</dd>
                  </div>
                ))}
              </dl>
            </section>
          ) : null}
        </div>
      </div>
    </main>
  )
}
