"use client";

import { useState } from "react";

import { CheckCircle2, CreditCard, Loader2, MessageCircle, Monitor, X } from "lucide-react";

import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { useT } from "@/lib/i18n";
import type { OrderCharges } from "@/lib/order/types";
import { SectionHeader } from "./section-header";

interface TotalsSectionProps {
  charges: OrderCharges;
  /** Pass order context so Paylink WhatsApp and Card terminal can work */
  orderId?: string;
  customerMo?: string;
  customerNa?: string;
  stage?: string;
  readOnly?: boolean;
  onSave?: () => void;
  onRepeat?: () => void;
  onCancel?: () => void;
  onMarkPaid?: () => void;
}

// Payment labels are now provided via useT() inside the component

const PAYMENT_COLORS: Record<string, string> = {
  card: "bg-blue-500/10 text-blue-700 border-blue-200",
  cash: "bg-green-500/10 text-green-700 border-green-200",
  paylink: "bg-violet-500/10 text-violet-700 border-violet-200",
};

const PAYMENT_STATUS_COLORS: Record<string, string> = {
  paid: "bg-green-500/10 text-green-700 border-green-200",
  unpaid: "bg-red-500/10 text-red-700 border-red-200",
};

export function TotalsSection({ charges, orderId, customerMo, customerNa, stage, readOnly = false, onSave, onRepeat, onCancel, onMarkPaid }: TotalsSectionProps) {
  const isCompleted = stage === "completed";
  const [terminalState, setTerminalState] = useState<"idle" | "waiting" | "approved" | "declined">("idle");
  const t = useT();

  const PAYMENT_LABELS: Record<string, string> = {
    card: t.pay_card,
    cash: t.pay_cash,
    paylink: t.pay_paylink,
  };

  // Build WhatsApp deep-link with pre-composed payment message
  const whatsappPaylink = (() => {
    if (charges.paymentMethod !== "paylink" || !customerMo) return null;
    const phone = customerMo.replace(/[^0-9]/g, ""); // strip + and spaces
    const payUrl = `https://pay.orderos.app/${orderId ?? "ORDER"}`;
    const msg = [
      `Hello${customerNa ? ` ${customerNa}` : ""}! 🍜`,
      `Your order *${orderId ?? "ORDER"}* from Haka Bracknell is ready for payment.`,
      ``,
      `💰 Amount due: *£${charges.total.toFixed(2)}*`,
      ``,
      `Please complete your payment using the link below:`,
      `👉 ${payUrl}`,
      ``,
      `Thank you for ordering with us! 🙏`,
    ].join("\n");
    return `https://wa.me/${phone}?text=${encodeURIComponent(msg)}`;
  })();

  const discountAmt = charges.discountPct
    ? (charges.subtotal * (charges.discountPct / 100)).toFixed(2)
    : null;

  const initiateTerminal = () => {
    setTerminalState("waiting");
    // Simulate terminal interaction — auto-approve after 3 s for POC demo
    setTimeout(() => setTerminalState("approved"), 3000);
  };

  return (
    <Collapsible defaultOpen>
      <CollapsibleTrigger className="w-full">
        <SectionHeader icon={CreditCard} label={t.sec_totals} />
      </CollapsibleTrigger>
      <CollapsibleContent>
        <div className="space-y-0.5 px-3 py-2 text-sm">
          <ChargeRow label={t.totals_subtotal} value={`£${charges.subtotal.toFixed(2)}`} />

          {charges.discountPct !== undefined && discountAmt && (
            <ChargeRow
              label={t.totals_discount(charges.discountPct)}
              value={`-£${discountAmt}`}
              valueClassName="text-green-700 dark:text-green-400"
            />
          )}

          {charges.voucherAmt !== undefined && (
            <ChargeRow
              label="Voucher"
              value={`-£${charges.voucherAmt.toFixed(2)}`}
              valueClassName="text-green-700 dark:text-green-400"
            />
          )}

          {charges.serviceFee !== undefined && (
            <ChargeRow label="Service Fee" value={`£${charges.serviceFee.toFixed(2)}`} />
          )}

          {charges.bagFee !== undefined && (
            <ChargeRow label="Bag Fee" value={`£${charges.bagFee.toFixed(2)}`} />
          )}

          {charges.extraFee !== undefined && (
            <ChargeRow label="Extra Fee" value={`£${charges.extraFee.toFixed(2)}`} />
          )}

          {charges.deliveryFee !== undefined && (
            <ChargeRow label={t.totals_delivery_fee} value={`£${charges.deliveryFee.toFixed(2)}`} />
          )}

          <div className="border-t pt-1.5">
            <div className="flex items-center justify-between">
              <span className="font-bold text-base">{t.totals_total}</span>
              <span className="font-bold text-base tabular-nums">£{charges.total.toFixed(2)}</span>
            </div>
          </div>

          {/* Payment method + status */}
          <div className="flex items-center gap-2 pt-1 flex-wrap">
            <span className="text-[11px] text-muted-foreground">{t.pay_method_label}</span>
            <span
              className={`inline-flex items-center rounded border px-2 py-0.5 font-medium text-[11px] ${PAYMENT_COLORS[charges.paymentMethod]}`}
            >
              {PAYMENT_LABELS[charges.paymentMethod]}
            </span>
            <span
              className={`inline-flex items-center rounded border px-2 py-0.5 font-medium text-[11px] uppercase ${PAYMENT_STATUS_COLORS[charges.paymentStatus]}`}
            >
              {charges.paymentStatus === "paid" ? t.pay_paid : t.pay_unpaid}
            </span>

            {/* WhatsApp Paylink button */}
            {whatsappPaylink && (
              <a
                href={whatsappPaylink}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-1 rounded border border-green-300 bg-green-50 px-2 py-0.5 text-[11px] font-medium text-green-700 hover:bg-green-100 transition-colors"
                title="Send payment link via WhatsApp"
              >
                <MessageCircle className="size-3" />
                {t.totals_send_paylink}
              </a>
            )}

            {/* Card terminal button — only for card payment on open orders */}
            {charges.paymentMethod === "card" && !readOnly && !isCompleted && terminalState === "idle" && (
              <button
                type="button"
                onClick={initiateTerminal}
                className="flex items-center gap-1 rounded border border-blue-300 bg-blue-50 px-2 py-0.5 text-[11px] font-medium text-blue-700 hover:bg-blue-100 transition-colors"
              >
                <Monitor className="size-3" />
                {t.totals_initiate_term}
              </button>
            )}
          </div>

          {/* Mark Paid — cash collected at counter */}
          {!readOnly && !isCompleted && onMarkPaid && charges.paymentMethod === "cash" && charges.paymentStatus === "unpaid" && (
            <button
              type="button"
              onClick={onMarkPaid}
              className="mt-2 flex w-full items-center justify-center gap-1.5 rounded-md border-2 border-green-500 bg-green-50 py-2 font-semibold text-green-800 text-sm hover:bg-green-100 active:bg-green-200 transition-colors"
            >
                <CheckCircle2 className="size-4" />
                {t.totals_mark_paid}
            </button>
          )}

          {/* Card terminal mock dialog */}
          {charges.paymentMethod === "card" && terminalState !== "idle" && (
            <div className="mt-2 rounded-lg border-2 border-blue-200 bg-blue-50 p-3">
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center gap-2 text-blue-800 font-semibold text-[12px]">
                  <Monitor className="size-4" />
                  Card Terminal
                </div>
                {terminalState !== "waiting" && (
                  <button
                    type="button"
                    onClick={() => setTerminalState("idle")}
                    className="text-muted-foreground hover:text-foreground"
                  >
                    <X className="size-3.5" />
                  </button>
                )}
              </div>

              {terminalState === "waiting" && (
                <div className="flex flex-col items-center gap-2 py-2">
                  <Loader2 className="size-6 animate-spin text-blue-600" />
                  <p className="text-[12px] text-blue-700 font-medium">
                    Waiting for card…
                  </p>
                  <p className="text-[11px] text-blue-500">
                    Please insert or tap card on terminal
                  </p>
                  <p className="font-bold text-blue-800 text-base">£{charges.total.toFixed(2)}</p>
                </div>
              )}

              {terminalState === "approved" && (
                <div className="flex flex-col items-center gap-1.5 py-2">
                  <CheckCircle2 className="size-7 text-green-600" />
                  <p className="text-[13px] font-bold text-green-700">APPROVED</p>
                  <p className="text-[11px] text-green-600">£{charges.total.toFixed(2)} — Visa •••• 4242</p>
                  <p className="text-[10px] text-muted-foreground">Auth code: 123456 · Ref: TRM-{Date.now().toString().slice(-6)}</p>
                </div>
              )}

              {terminalState === "declined" && (
                <div className="flex flex-col items-center gap-1.5 py-2">
                  <X className="size-7 text-red-600" />
                  <p className="text-[13px] font-bold text-red-700">DECLINED</p>
                  <p className="text-[11px] text-red-600">Please try another card or payment method</p>
                  <button
                    type="button"
                    onClick={initiateTerminal}
                    className="mt-1 rounded border border-blue-300 px-3 py-1 text-[11px] text-blue-700 hover:bg-blue-50"
                  >
                    Retry
                  </button>
                </div>
              )}
            </div>
          )}

          {/* Action buttons — hidden for completed orders */}
          {!readOnly && !isCompleted && (
            <div className="space-y-1.5 border-t pt-3 mt-1">
              <button
                type="button"
                onClick={onSave}
                className="w-full rounded border border-primary bg-primary/5 py-1.5 text-center font-bold text-primary text-sm hover:bg-primary/10 transition-colors"
              >
                {t.totals_save}
              </button>
              <div className="grid grid-cols-2 gap-1.5">
                <button
                  type="button"
                  onClick={onRepeat}
                  className="rounded border py-1.5 text-center text-[12px] text-muted-foreground hover:border-primary/40 hover:text-primary transition-colors"
                >
                  {t.totals_repeat}
                </button>
                <button
                  type="button"
                  onClick={onCancel}
                  className="rounded border border-destructive/30 py-1.5 text-center text-[12px] text-destructive/70 hover:bg-destructive/5 transition-colors"
                >
                  {t.totals_cancel}
                </button>
              </div>
            </div>
          )}
        </div>
      </CollapsibleContent>
    </Collapsible>
  );
}

function ChargeRow({
  label,
  value,
  valueClassName = "",
}: {
  label: string;
  value: string;
  valueClassName?: string;
}) {
  return (
    <div className="flex items-center justify-between text-[13px]">
      <span className="text-muted-foreground">{label}</span>
      <span className={`tabular-nums ${valueClassName}`}>{value}</span>
    </div>
  );
}
