'use client'

import { useTranslations, useLocale } from 'next-intl'
import { useCurrencyStore } from '@/store/currencyStore'

export interface ReceiptStore {
  name: string
  logoUrl: string | null
  address: string | null
  phone: string | null
  email: string | null
}

export interface ReceiptItem {
  id: string
  product_name: string
  variant_name: string | null
  sku?: string | null
  quantity: number
  unit_price: number
  total_price: number
}

export interface ReceiptOrder {
  order_number: string
  payment_status: string
  delivery_fee: number
  tax_amount: number
  tax_percentage: number
  coupon_discount_amount: number
  shipping_full_name: string
  shipping_phone: string
  shipping_address_line1: string
  shipping_address_line2: string | null
  shipping_city: string
  shipping_landmark: string | null
  created_at: string
}

interface OrderPrintReceiptProps {
  order: ReceiptOrder
  items: ReceiptItem[]
  store: ReceiptStore
  customerEmail: string | null
  paymentLabel: string
  subtotal: number
  total: number
}

// The printable receipt for "Print Receipt" on the order-confirmation page.
// Hidden on screen. While printing, globals.css (`@media print`,
// `.print-receipt-root`) hides everything that is not this receipt or one of
// its ancestors, and flattens those ancestors, so the header, footer, buttons
// and on-screen cards never reach the paper. It stays inside the
// [data-storefront] root (no portal) to keep the theme colors, fonts and RTL.
export default function OrderPrintReceipt({
  order,
  items,
  store,
  customerEmail,
  paymentLabel,
  subtotal,
  total,
}: OrderPrintReceiptProps) {
  const t = useTranslations('OrderConfirmation')
  const tPayment = useTranslations('TrackOrder.paymentStatus')
  const locale = useLocale()
  const formatAmount = useCurrencyStore((s) => s.formatAmount)
  const orderDate = new Date(order.created_at)
  const dateText = orderDate.toLocaleDateString(locale, { year: 'numeric', month: 'long', day: 'numeric' })
  const timeText = orderDate.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' })
  const paymentStatusText = tPayment.has(order.payment_status) ? tPayment(order.payment_status) : order.payment_status
  const isPaid = order.payment_status === 'paid'

  const address = [
    order.shipping_address_line1,
    order.shipping_address_line2,
    order.shipping_city,
    order.shipping_landmark,
  ].filter(Boolean).join(', ')

  return (
    <div className="print-receipt-root hidden print:block bg-white text-[#111827] text-[12px] leading-relaxed">
      {/* Header */}
      <div className="flex items-start justify-between gap-6 pb-5 border-b-2 border-primary">
        <div>
          {store.logoUrl ? (
            // eslint-disable-next-line @next/next/no-img-element -- print-only; next/image lazy-loading can leave it blank on paper
            <img src={store.logoUrl} alt={store.name} className="h-12 w-auto object-contain mb-2" />
          ) : (
            <p className="text-2xl font-bold text-primary mb-1">{store.name}</p>
          )}
          <div className="text-[11px] text-[#4b5563] space-y-0.5">
            {store.address && <p>{store.address}</p>}
            {store.phone && <p>{t('phone')}: {store.phone}</p>}
            {store.email && <p>{store.email}</p>}
          </div>
        </div>
        <div className="text-end">
          <p className="text-3xl font-bold tracking-wide uppercase text-[#111827]">{t('receipt.title')}</p>
          <table className="mt-2 ms-auto text-[11px]">
            <tbody>
              <tr>
                <td className="pe-3 text-[#6b7280]">{t('receipt.orderNo')}</td>
                <td className="font-semibold">{order.order_number}</td>
              </tr>
              <tr>
                <td className="pe-3 text-[#6b7280]">{t('receipt.date')}</td>
                <td>{dateText}, {timeText}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      {/* Bill to / payment */}
      <div className="grid grid-cols-2 gap-6 py-5">
        <div>
          <p className="text-[10px] font-semibold uppercase tracking-wider text-[#6b7280] mb-1.5">{t('receipt.billTo')}</p>
          <p className="font-semibold text-[13px]">{order.shipping_full_name}</p>
          <p className="text-[#374151]">{address}</p>
          <p className="text-[#374151]">{t('phone')}: {order.shipping_phone}</p>
          {customerEmail && <p className="text-[#374151]">{customerEmail}</p>}
        </div>
        <div className="text-end">
          <p className="text-[10px] font-semibold uppercase tracking-wider text-[#6b7280] mb-1.5">{t('receipt.payment')}</p>
          <p className="font-semibold text-[13px]">{paymentLabel}</p>
          <span
            className={`inline-block mt-1 rounded-full border px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${
              isPaid ? 'border-green-600 text-green-700' : 'border-amber-500 text-amber-700'
            }`}
          >
            {paymentStatusText}
          </span>
        </div>
      </div>

      {/* Items */}
      <table className="w-full border-collapse">
        <thead>
          <tr className="bg-[#f3f4f6] text-[10px] uppercase tracking-wider text-[#4b5563]">
            <th className="py-2 px-3 text-start font-semibold w-8">#</th>
            <th className="py-2 px-3 text-start font-semibold">{t('receipt.item')}</th>
            <th className="py-2 px-3 text-center font-semibold w-14">{t('receipt.qty')}</th>
            <th className="py-2 px-3 text-end font-semibold w-28">{t('receipt.unitPrice')}</th>
            <th className="py-2 px-3 text-end font-semibold w-28">{t('receipt.amount')}</th>
          </tr>
        </thead>
        <tbody>
          {items.map((item, index) => (
            <tr key={item.id} className="border-b border-[#e5e7eb] break-inside-avoid">
              <td className="py-2.5 px-3 align-top text-[#6b7280]">{index + 1}</td>
              <td className="py-2.5 px-3 align-top">
                <p className="font-medium">{item.product_name}</p>
                {(item.variant_name || item.sku) && (
                  <p className="text-[10px] text-[#6b7280]">
                    {[item.variant_name, item.sku && `SKU: ${item.sku}`].filter(Boolean).join(' · ')}
                  </p>
                )}
              </td>
              <td className="py-2.5 px-3 align-top text-center">{item.quantity}</td>
              <td className="py-2.5 px-3 align-top text-end whitespace-nowrap">{formatAmount(item.unit_price)}</td>
              <td className="py-2.5 px-3 align-top text-end whitespace-nowrap font-medium">{formatAmount(item.total_price)}</td>
            </tr>
          ))}
        </tbody>
      </table>

      {/* Totals */}
      <div className="flex justify-end pt-4 break-inside-avoid">
        <table className="w-72 text-[12px]">
          <tbody>
            <tr>
              <td className="py-1 text-[#4b5563]">{t('subtotal')}</td>
              <td className="py-1 text-end whitespace-nowrap">{formatAmount(subtotal)}</td>
            </tr>
            <tr>
              <td className="py-1 text-[#4b5563]">{t('deliveryFee')}</td>
              <td className="py-1 text-end whitespace-nowrap">
                {order.delivery_fee === 0 ? t('free') : formatAmount(order.delivery_fee)}
              </td>
            </tr>
            {order.tax_amount > 0 && (
              <tr>
                <td className="py-1 text-[#4b5563]">{t('tax', { percentage: order.tax_percentage })}</td>
                <td className="py-1 text-end whitespace-nowrap">{formatAmount(order.tax_amount)}</td>
              </tr>
            )}
            {order.coupon_discount_amount > 0 && (
              <tr>
                <td className="py-1 text-[#4b5563]">{t('discount')}</td>
                <td className="py-1 text-end whitespace-nowrap">- {formatAmount(order.coupon_discount_amount)}</td>
              </tr>
            )}
            <tr className="border-t-2 border-[#111827]">
              <td className="pt-2 text-[14px] font-bold">{t('total')}</td>
              <td className="pt-2 text-end text-[14px] font-bold text-primary whitespace-nowrap">{formatAmount(total)}</td>
            </tr>
          </tbody>
        </table>
      </div>

      {/* Footer */}
      <div className="mt-10 pt-4 border-t border-[#e5e7eb] text-center break-inside-avoid">
        <p className="text-[13px] font-semibold">{t('receipt.thanks', { siteName: store.name })}</p>
        <p className="mt-1 text-[10px] text-[#6b7280]">{t('receipt.computerGenerated')}</p>
      </div>
    </div>
  )
}
