import { useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { FileDown } from 'lucide-react'
import meshkeeLogo from '../assets/meshkee-logo.png'
import { isEmptyRichText } from '../components/RichTextEditor'
import { useToast } from '../context/ToastContext'
import { ApiError, isAbortError } from '../lib/api'
import { getPlatformMarketingUrl } from '../lib/config'
import { getPublicInvoice } from '../services/invoiceService'
import type { PublicInvoice } from '../types/invoice'
import { formatIrtPrice } from '../utils/irtPrice'
import styles from './PublicInvoicePage.module.css'

type InvoiceLocale = 'en' | 'fa'

const COPY: Record<
  InvoiceLocale,
  {
    loading: string
    loadError: string
    issued: string
    items: string
    subtotal: string
    total: string
    keyPoints: string
    accounts: string
    card: string
    iban: string
    issuedBy: string
    printHint: string
    print: string
    invoiceFallback: string
    copiedCard: string
    copiedIban: string
    copyFailed: string
    copyCardAria: string
    copyIbanAria: string
  }
> = {
  en: {
    loading: 'Loading invoice…',
    loadError: 'Unable to load invoice.',
    issued: 'Issued',
    items: 'Items',
    subtotal: 'Subtotal',
    total: 'Total',
    keyPoints: 'Key points',
    accounts: 'Account numbers',
    card: 'Card',
    iban: 'IBAN',
    issuedBy: 'Issued by',
    printHint: 'Save as PDF from the print dialog (Destination → Save as PDF).',
    print: 'Print to PDF',
    invoiceFallback: 'Invoice',
    copiedCard: 'Card number copied.',
    copiedIban: 'IBAN copied.',
    copyFailed: 'Unable to copy.',
    copyCardAria: 'Copy card number',
    copyIbanAria: 'Copy IBAN',
  },
  fa: {
    loading: 'در حال بارگذاری فاکتور…',
    loadError: 'بارگذاری فاکتور ممکن نشد.',
    issued: 'صادر شده',
    items: 'آیتم‌ها',
    subtotal: 'جمع جزء',
    total: 'مبلغ کل',
    keyPoints: 'نکات کلیدی',
    accounts: 'شماره حساب‌ها',
    card: 'کارت',
    iban: 'شبا',
    issuedBy: 'صادر شده توسط',
    printHint: 'از پنجره چاپ، مقصد را روی «ذخیره به‌صورت PDF» بگذارید.',
    print: 'چاپ / ذخیره PDF',
    invoiceFallback: 'فاکتور',
    copiedCard: 'شماره کارت کپی شد.',
    copiedIban: 'شماره شبا کپی شد.',
    copyFailed: 'کپی ممکن نشد.',
    copyCardAria: 'کپی شماره کارت',
    copyIbanAria: 'کپی شماره شبا',
  },
}

function formatDate(value: string, locale: InvoiceLocale) {
  const d = new Date(value)
  if (Number.isNaN(d.getTime())) return value
  return d.toLocaleDateString(locale === 'fa' ? 'fa-IR' : 'en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  })
}

export function PublicInvoicePage() {
  const { invoiceId = '' } = useParams()
  const { showToast } = useToast()
  const [invoice, setInvoice] = useState<PublicInvoice | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const marketingUrl = getPlatformMarketingUrl()

  const locale: InvoiceLocale = invoice?.locale === 'en' ? 'en' : 'fa'
  const isRtl = locale === 'fa'
  const t = COPY[locale]

  const businessLabel = useMemo(() => {
    if (!invoice?.business) return ''
    return (
      invoice.business.displayName?.trim() ||
      (locale === 'fa'
        ? invoice.business.nameFa?.trim() || invoice.business.name
        : invoice.business.name) ||
      ''
    )
  }, [invoice, locale])

  useEffect(() => {
    if (!invoiceId) return
    const controller = new AbortController()
    setLoading(true)
    setError('')
    void getPublicInvoice(invoiceId, controller.signal)
      .then((data) => setInvoice(data))
      .catch((err) => {
        if (isAbortError(err)) return
        setError(err instanceof ApiError ? err.message : COPY.fa.loadError)
        setInvoice(null)
      })
      .finally(() => setLoading(false))
    return () => controller.abort()
  }, [invoiceId])

  useEffect(() => {
    if (!invoice) return
    const previous = document.title
    document.title =
      invoice.name?.trim() ||
      `${t.invoiceFallback} ${invoice.publicId}`
    return () => {
      document.title = previous
    }
  }, [invoice, t.invoiceFallback])

  function handlePrint() {
    window.print()
  }

  async function copyValue(value: string, successMessage: string) {
    const text = value.trim()
    if (!text || text === '—') return
    try {
      await navigator.clipboard.writeText(text)
      showToast(successMessage, 'success')
    } catch {
      showToast(t.copyFailed, 'error')
    }
  }

  return (
    <div className={styles.page} lang={locale} dir={isRtl ? 'rtl' : 'ltr'}>
      <div className={styles.sheet}>
        {loading ? <p className={styles.muted}>{t.loading}</p> : null}
        {error ? <p className={styles.error}>{error}</p> : null}

        {invoice ? (
          <>
            <header className={styles.header}>
              <h1 className={styles.title}>
                {invoice.name || `${t.invoiceFallback} ${invoice.publicId}`}
              </h1>
              <p className={styles.meta}>
                {t.issued} {formatDate(invoice.issuedAt, locale)}
                {businessLabel ? ` · ${businessLabel}` : ''}
              </p>
            </header>

            {invoice.topText && !isEmptyRichText(invoice.topText) ? (
              <div
                className={styles.topText}
                dangerouslySetInnerHTML={{ __html: invoice.topText }}
              />
            ) : null}

            <section className={styles.section}>
              <h2 className={styles.sectionTitle}>{t.items}</h2>
              <div className={styles.items}>
                {(invoice.items ?? []).map((item) => {
                  const effective =
                    item.discountedPrice !== null &&
                    item.discountedPrice !== undefined &&
                    item.discountedPrice < item.price
                      ? item.discountedPrice
                      : item.price
                  return (
                    <article key={item.id} className={styles.item}>
                      <div className={styles.itemMain}>
                        <h3 className={styles.itemTitle}>{item.title}</h3>
                        {item.description ? (
                          <p className={styles.itemDesc}>{item.description}</p>
                        ) : null}
                      </div>
                      <div className={styles.itemPrice}>
                        {(item.duration || item.worktime) ? (
                          <div className={styles.itemMeta}>
                            {item.duration ? <span>{item.duration}</span> : null}
                            {item.worktime ? <span>{item.worktime}</span> : null}
                          </div>
                        ) : null}
                        {item.discountedPrice !== null &&
                        item.discountedPrice !== undefined &&
                        item.discountedPrice < item.price ? (
                          <span className={styles.priceWas}>{formatIrtPrice(item.price)}</span>
                        ) : null}
                        <span>{formatIrtPrice(effective)}</span>
                      </div>
                    </article>
                  )
                })}
              </div>
              <div className={styles.totals}>
                <div>
                  <span>{t.subtotal}</span>
                  <strong>{formatIrtPrice(invoice.subtotal ?? 0)}</strong>
                </div>
                <div className={styles.totalRow}>
                  <span>{t.total}</span>
                  <strong>{formatIrtPrice(invoice.total ?? 0)}</strong>
                </div>
              </div>
            </section>

            {(invoice.keyPoints?.length ?? 0) > 0 ? (
              <section className={styles.section}>
                <h2 className={styles.sectionTitle}>{t.keyPoints}</h2>
                <ul className={styles.keyPoints}>
                  {invoice.keyPoints!.map((kp) => (
                    <li key={kp.id}>{kp.text}</li>
                  ))}
                </ul>
              </section>
            ) : null}

            {(invoice.accounts?.length ?? 0) > 0 ? (
              <section className={styles.section}>
                <h2 className={styles.sectionTitle}>{t.accounts}</h2>
                <div className={styles.accounts}>
                  {invoice.accounts!.map((acc) => (
                    <div key={acc.id} className={styles.account}>
                      <span className={styles.accountBank}>{acc.bankName}</span>
                      <span className={styles.accountHolder}>
                        {acc.accountHolderName || '—'}
                      </span>
                      {acc.cardNumber ? (
                        <button
                          type="button"
                          className={styles.accountNumValue}
                          dir="ltr"
                          onClick={() => void copyValue(acc.cardNumber!, t.copiedCard)}
                          aria-label={t.copyCardAria}
                        >
                          {acc.cardNumber}
                        </button>
                      ) : (
                        <span className={styles.accountNumValue} dir="ltr">
                          —
                        </span>
                      )}
                      {acc.iban ? (
                        <button
                          type="button"
                          className={styles.accountNumValue}
                          dir="ltr"
                          onClick={() => void copyValue(acc.iban!, t.copiedIban)}
                          aria-label={t.copyIbanAria}
                        >
                          {acc.iban}
                        </button>
                      ) : (
                        <span className={styles.accountNumValue} dir="ltr">
                          —
                        </span>
                      )}
                    </div>
                  ))}
                </div>
              </section>
            ) : null}

            <footer className={styles.footer}>
              <a
                className={styles.footerLink}
                href={marketingUrl}
                target="_blank"
                rel="noreferrer"
              >
                <img src={meshkeeLogo} alt="" className={styles.footerLogo} />
                <span className={styles.footerLabel}>{t.issuedBy}</span>
                <span className={styles.footerName}>Meshkee E-Commerce Group</span>
              </a>
            </footer>
          </>
        ) : null}
      </div>

      {invoice ? (
        <div className={styles.toolbar}>
          <p className={styles.toolbarHint}>{t.printHint}</p>
          <button type="button" className={styles.printBtn} onClick={handlePrint}>
            <FileDown size={16} aria-hidden />
            {t.print}
          </button>
        </div>
      ) : null}
    </div>
  )
}
