"use client";

import { useLanguage } from "@/lib/language-context";
import type { Order } from "@/lib/order/types";
import { STAGE_LABELS } from "@/lib/order/types";

interface PrintViewProps {
  order: Order;
}

/**
 * 80mm thermal receipt layout.
 * Rendered inside a hidden div and triggered via window.print().
 * Add `@media print { body { visibility: hidden } #print-ticket { visibility: visible } }` in globals.css to isolate.
 */
export function PrintView({ order }: PrintViewProps) {
  const { lang } = useLanguage();
  const requestedTime = order.requestedAt
    ? new Date(order.requestedAt).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })
    : null;

  return (
    <div
      id="print-ticket"
      className="hidden print:block"
      style={{ fontFamily: "monospace", fontSize: 12, lineHeight: 1.4, width: 280 }}
    >
      {/* Header */}
      <div style={{ textAlign: "center", borderBottom: "1px dashed #000", paddingBottom: 4, marginBottom: 6 }}>
        <div style={{ fontWeight: "bold", fontSize: 16 }}>OrderOS</div>
        <div style={{ fontSize: 11 }}>{order.id}</div>
        <div style={{ fontWeight: "bold" }}>
          {order.type.toUpperCase()}
          {requestedTime ? ` — Ready: ${requestedTime}` : ""}
        </div>
        <div style={{ fontSize: 10 }}>{new Date(order.orderedAt).toLocaleString("en-GB")}</div>
      </div>

      {/* Address */}
      {order.type === "delivery" && order.address && (
        <div style={{ marginBottom: 6 }}>
          <div style={{ fontWeight: "bold" }}>DELIVER TO:</div>
          <div>{order.address.ad}</div>
          {order.address.an && <div>{order.address.an}</div>}
          {order.address.miles && <div>{order.address.miles} miles</div>}
        </div>
      )}

      {/* Customer */}
      <div style={{ marginBottom: 6 }}>
        <div>na: {order.customer.na}</div>
        <div>mo: {order.customer.mo}</div>
        {order.customer.cn && <div>Note: {order.customer.cn}</div>}
      </div>

      {/* Items */}
      <div style={{ borderTop: "1px dashed #000", borderBottom: "1px dashed #000", paddingTop: 4, paddingBottom: 4, marginBottom: 6 }}>
        {order.items.map((item, i) => (
          <div key={`${item.code}-${i}`} style={{ marginBottom: 4 }}>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                fontWeight: "bold",
                fontSize: 14,
              }}
            >
              <span>{lang === "zh" ? item.chineseName : item.description} ×{item.qty}</span>
              <span>£{(item.qty * item.unitPrice).toFixed(2)}</span>
            </div>
            <div style={{ fontSize: 10 }}>
              {item.description}
              {item.notes ? ` · ${item.notes}` : ""}
            </div>
          </div>
        ))}
      </div>

      {/* Totals */}
      <div style={{ marginBottom: 6 }}>
        <TotalRow label="Subtotal" value={`£${order.charges.subtotal.toFixed(2)}`} />
        {order.charges.discountPct && (
          <TotalRow
            label={`Discount ${order.charges.discountPct}%`}
            value={`-£${(order.charges.subtotal * (order.charges.discountPct / 100)).toFixed(2)}`}
          />
        )}
        {order.charges.deliveryFee && (
          <TotalRow label="Delivery" value={`£${order.charges.deliveryFee.toFixed(2)}`} />
        )}
        <div style={{ display: "flex", justifyContent: "space-between", fontWeight: "bold", fontSize: 14 }}>
          <span>TOTAL</span>
          <span>£{order.charges.total.toFixed(2)}</span>
        </div>
        <TotalRow label="Payment" value={order.charges.paymentMethod.toUpperCase()} />
        <TotalRow label="Status" value={order.charges.paymentStatus.toUpperCase()} />
      </div>

      {/* Stage */}
      <div style={{ textAlign: "center", borderTop: "1px dashed #000", paddingTop: 4 }}>
        <div style={{ fontWeight: "bold" }}>{STAGE_LABELS[order.stage]}</div>
        <div style={{ fontSize: 10, marginTop: 2 }}>Printed: {new Date().toLocaleString("en-GB")}</div>
      </div>
    </div>
  );
}

function TotalRow({ label, value }: { label: string; value: string }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11 }}>
      <span>{label}</span>
      <span>{value}</span>
    </div>
  );
}
