import { useEffect, 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 { 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'

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

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

  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 : 'Unable to load invoice.')
        setInvoice(null)
      })
      .finally(() => setLoading(false))
    return () => controller.abort()
  }, [invoiceId])

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

  function handlePrint() {
    window.print()
  }

  return (
    <div className={styles.page} lang="en">
      <div className={styles.sheet}>
        {loading ? <p className={styles.muted}>Loading invoice…</p> : null}
        {error ? <p className={styles.error}>{error}</p> : null}

        {invoice ? (
          <>
            <header className={styles.header}>
              <h1 className={styles.title}>{invoice.name || `Invoice ${invoice.publicId}`}</h1>
              <p className={styles.meta}>
                Issued {formatDate(invoice.issuedAt)}
                {invoice.business?.name ? ` · ${invoice.business.name}` : ''}
              </p>
            </header>

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

            <section className={styles.section}>
              <h2 className={styles.sectionTitle}>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 className={styles.itemMeta}>
                          {item.duration ? <span>{item.duration}</span> : null}
                          {item.worktime ? <span>{item.worktime}</span> : null}
                        </div>
                      </div>
                      <div className={styles.itemPrice}>
                        {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>Subtotal</span>
                  <strong>{formatIrtPrice(invoice.subtotal ?? 0)}</strong>
                </div>
                <div className={styles.totalRow}>
                  <span>Total</span>
                  <strong>{formatIrtPrice(invoice.total ?? 0)}</strong>
                </div>
              </div>
            </section>

            {(invoice.keyPoints?.length ?? 0) > 0 ? (
              <section className={styles.section}>
                <h2 className={styles.sectionTitle}>Key points</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}>Account numbers</h2>
                <div className={styles.accounts}>
                  {invoice.accounts!.map((acc) => {
                    const details = [
                      acc.accountHolderName,
                      acc.cardNumber ? `Card: ${acc.cardNumber}` : null,
                      acc.iban ? `IBAN: ${acc.iban}` : null,
                    ].filter(Boolean)
                    return (
                      <div key={acc.id} className={styles.account}>
                        <strong className={styles.accountBank}>{acc.bankName}</strong>
                        {details.length > 0 ? (
                          <p className={styles.accountDetails}>{details.join(' · ')}</p>
                        ) : null}
                      </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}>Issued by</span>
                <span className={styles.footerName}>Meshkee E-Commerce Group</span>
              </a>
            </footer>
          </>
        ) : null}
      </div>

      {invoice ? (
        <div className={styles.toolbar}>
          <p className={styles.toolbarHint}>
            Save as PDF from the print dialog (Destination → Save as PDF).
          </p>
          <button type="button" className={styles.printBtn} onClick={handlePrint}>
            <FileDown size={16} aria-hidden />
            Print to PDF
          </button>
        </div>
      ) : null}
    </div>
  )
}
