import { useEffect, useMemo, useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { ImageOff, MapPin, Pencil, User } from 'lucide-react'
import { useLocale } from '@meshkee/dashboard-ui'
import { Breadcrumbs } from '../components/Breadcrumbs'
import { PageTitle } from '../components/PageTitle'
import { UserProductStatusModal } from '../components/UserProductStatusModal'
import { useToast } from '../context/ToastContext'
import { useT } from '../i18n/useT'
import { ApiError, isAbortError } from '../lib/api'
import {
  getUserProduct,
  getUserProductCategoryTechnicalForm,
  updateUserProductStatus,
  type TechnicalFormField,
  type UserProductDetail,
  type UserProductTechnicalValueInput,
} from '../services/userProductsService'
import type { UserProductStatus } from '../types/userProduct'
import { formatIrtPrice } from '../utils/irtPrice'
import pageStyles from '../components/PageContent.module.css'
import styles from './CustomerProductDetailsPage.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 CustomerProductDetailsPage() {
  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('')
  const [statusOpen, setStatusOpen] = useState(false)
  const [statusSaving, setStatusSaving] = useState(false)

  useEffect(() => {
    if (!id) return
    const controller = new AbortController()

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

        if (response.product.categoryId) {
          const formResponse = await getUserProductCategoryTechnicalForm(
            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('customerProducts.error.loadDetail')
        setError(message)
        setProduct(null)
      } finally {
        if (!controller.signal.aborted) setLoading(false)
      }
    }

    void load()
    return () => controller.abort()
  }, [id, 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])

  async function handleStatusSave(status: UserProductStatus) {
    if (!product) return
    setStatusSaving(true)
    try {
      const response = await updateUserProductStatus(product.id, status)
      setProduct((prev) => (prev ? { ...prev, ...response.product } : prev))
      showToast(t('customerProducts.statusSuccess'), 'success')
      setStatusOpen(false)
    } catch (err) {
      showToast(
        err instanceof ApiError
          ? err.message
          : t('customerProducts.error.status'),
        'error',
      )
    } finally {
      setStatusSaving(false)
    }
  }

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

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

  const title = isFa ? product.titleFa || product.title : product.titleEn || product.title
  const secondary = isFa ? product.titleEn || '' : product.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 owner = isFa ? product.ownerNameFa || product.ownerName : product.ownerName
  const imageSrc = product.imageUrl?.trim() || ''
  const galleryImages = (product.images ?? [])
    .map((item) => item.url?.trim())
    .filter((url): url is string => Boolean(url))
  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 currency = (product.priceCurrency || 'IRT').toUpperCase()
  const priceLabel =
    product.price == null
      ? t('customerProducts.priceUnavailable')
      : currency === 'IRT'
        ? formatIrtPrice(product.price)
        : `${Number(product.price).toLocaleString('en-US')} ${currency}`
  const conditionLabel =
    product.condition === 'new'
      ? t('customerProducts.form.condition.new')
      : product.condition === 'stock'
        ? t('customerProducts.form.condition.stock')
        : product.condition === 'needs_repair'
          ? t('customerProducts.form.condition.needs_repair')
          : product.condition === 'scrap'
            ? t('customerProducts.form.condition.scrap')
            : '—'

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

      <div className={styles.headerRow}>
        <div>
          <PageTitle en="CUSTOMER PRODUCT">{t('customerProducts.detailsTitle')}</PageTitle>
          <p className={pageStyles.pageSubtitleContent}>{t('customerProducts.detailsSubtitle')}</p>
        </div>
        <div className={styles.actions}>
          <button
            type="button"
            className={styles.secondaryBtn}
            onClick={() => setStatusOpen(true)}
          >
            {t('customerProducts.statusChange')}
          </button>
          <button
            type="button"
            className={styles.editBtn}
            onClick={() => navigate(`/customer-products/${product.id}/edit`)}
          >
            <Pencil size={16} />
            {t('customerProducts.edit')}
          </button>
        </div>
      </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>
          </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'}>
              {owner ? (
                <span className={styles.metaItem}>
                  <User size={14} aria-hidden />
                  {owner}
                </span>
              ) : null}
              <span className={styles.metaItem}>
                <MapPin size={14} aria-hidden />
                {[city, country].filter(Boolean).join(isFa ? '، ' : ', ') || '—'}
              </span>
            </div>
          </div>

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

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

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

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

          {technicalRows.length > 0 ? (
            <section className={styles.section}>
              <h3>{t('customerProducts.form.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>

      <UserProductStatusModal
        open={statusOpen}
        currentStatus={product.status}
        saving={statusSaving}
        onClose={() => setStatusOpen(false)}
        onSave={(status) => void handleStatusSave(status)}
      />
    </main>
  )
}
