"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { MessageCircle } from "lucide-react";
import { Card } from "@/components/ui";
import { MERCHANT } from "@/lib/merchant";
import { ticketWhatsAppMessage, whatsAppLink } from "@/lib/whatsapp";

type Delivery = "sent" | "failed" | "not_configured" | "skipped";

const DELIVERY_TEXT: Record<Delivery, string> = {
  sent: "sent",
  failed: "failed to send",
  not_configured: "not sent — not set up on the Secrets page",
  skipped: "not sent",
};

export default function OrderAdminActions({
  orderId,
  status,
  paymentMethod,
  canQueryMpesa,
  hasPendingItems,
  ticketCount,
  buyerEmail,
  buyerPhone,
  buyerName,
  eventTitle,
}: {
  orderId: string;
  status: "pending" | "paid" | "cancelled" | "refunded";
  paymentMethod: string;
  canQueryMpesa: boolean;
  hasPendingItems: boolean;
  ticketCount: number;
  buyerEmail: string;
  buyerPhone: string | null;
  buyerName: string | null;
  eventTitle: string;
}) {
  const router = useRouter();
  const [busy, setBusy] = useState<string | null>(null);
  const [message, setMessage] = useState<{ tone: "ok" | "warn" | "danger"; text: string } | null>(null);
  const [sendEmail, setSendEmail] = useState(true);
  const [sendSms, setSendSms] = useState(Boolean(buyerPhone));
  const [sendWa, setSendWa] = useState(false);
  const [receipt, setReceipt] = useState("");
  const [note, setNote] = useState("");
  const [manualOpen, setManualOpen] = useState(false);

  async function post(path: string, body: unknown, label: string) {
    setBusy(label);
    setMessage(null);
    const res = await fetch(`/api/admin/orders/${orderId}/${path}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    }).catch(() => null);
    const data = res ? await res.json().catch(() => ({})) : {};
    setBusy(null);
    if (!res || !res.ok) {
      setMessage({ tone: "danger", text: data.error || "Action failed" });
      return null;
    }
    return data;
  }

  async function checkMpesa() {
    const data = await post("verify-payment", { mode: "mpesa_query", receipt }, "check");
    if (!data) return;
    if (!data.ok) {
      setMessage({ tone: data.state === "processing" ? "warn" : "danger", text: data.message });
      return;
    }
    setMessage({ tone: "ok", text: data.message });
    router.refresh();
  }

  async function checkPaystack() {
    const data = await post("verify-payment", { mode: "paystack_query" }, "paystack");
    if (!data) return;
    setMessage({ tone: data.ok ? "ok" : data.state === "pending" ? "warn" : "danger", text: data.message });
    if (data.ok) router.refresh();
  }

  async function confirmManually(e: React.FormEvent) {
    e.preventDefault();
    if (!confirm("Mark this order as paid and issue the tickets? Only do this after you've seen the money arrive.")) return;
    const data = await post("verify-payment", { mode: "manual", receipt, note }, "manual");
    if (!data) return;
    setMessage({ tone: "ok", text: data.message });
    setManualOpen(false);
    router.refresh();
  }

  async function resend() {
    const data = await post("resend", { email: sendEmail, sms: sendSms, whatsapp: sendWa }, "resend");
    if (!data) return;
    const parts = [
      sendEmail && `Email to ${buyerEmail}: ${DELIVERY_TEXT[data.email as Delivery]}`,
      sendSms && `SMS to ${buyerPhone}: ${DELIVERY_TEXT[data.sms as Delivery]}${data.smsError ? ` (${data.smsError})` : ""}`,
      sendWa &&
        `WhatsApp to ${buyerPhone}: ${DELIVERY_TEXT[data.whatsapp as Delivery]}${data.whatsappError ? ` (${data.whatsappError})` : ""}`,
    ].filter(Boolean);
    const allSent =
      (!sendEmail || data.email === "sent") && (!sendSms || data.sms === "sent") && (!sendWa || data.whatsapp === "sent");
    setMessage({ tone: allSent ? "ok" : "warn", text: `${parts.join(". ")}.` });
  }

  // Opens WhatsApp with the ticket message prefilled; the admin presses send
  // from the VibePass WhatsApp account signed in on this device.
  function openWhatsApp() {
    const site = process.env.NEXT_PUBLIC_SITE_URL || window.location.origin;
    const link = buyerPhone
      ? whatsAppLink(
          buyerPhone,
          ticketWhatsAppMessage({ buyerName, eventTitle, ticketCount, ticketUrl: `${site}/orders/${orderId}/success` })
        )
      : null;
    if (!link) {
      setMessage({ tone: "danger", text: `${buyerPhone ?? "No phone"} doesn't look like a valid WhatsApp number.` });
      return;
    }
    window.open(link, "_blank", "noopener,noreferrer");
    fetch(`/api/admin/orders/${orderId}/whatsapp`, { method: "POST" }).catch(() => {});
    setMessage({ tone: "ok", text: "WhatsApp opened with the message ready. Press send there to deliver it." });
  }

  const unpaid = status === "pending" || status === "cancelled";

  return (
    <Card className="space-y-5 self-start">
      {status === "paid" && (
        <section className="space-y-3">
          <h2 className="text-sm font-semibold text-be-text">Resend tickets</h2>
          {ticketCount === 0 ? (
            <p className="text-xs text-be-muted">This order has no tickets to send.</p>
          ) : (
            <>
              <p className="text-xs text-be-muted">
                Sends the link to all {ticketCount} QR code{ticketCount === 1 ? "" : "s"} to the buyer&apos;s details on this order.
              </p>
              <label className="flex items-center gap-2 text-sm text-be-text">
                <input type="checkbox" checked={sendEmail} onChange={(e) => setSendEmail(e.target.checked)} />
                Email <span className="truncate text-be-muted">{buyerEmail}</span>
              </label>
              <label className="flex items-center gap-2 text-sm text-be-text">
                <input
                  type="checkbox"
                  checked={sendSms}
                  disabled={!buyerPhone}
                  onChange={(e) => setSendSms(e.target.checked)}
                />
                SMS <span className="text-be-muted">{buyerPhone || "no phone on this order"}</span>
              </label>
              <label className="flex items-center gap-2 text-sm text-be-text">
                <input
                  type="checkbox"
                  checked={sendWa}
                  disabled={!buyerPhone}
                  onChange={(e) => setSendWa(e.target.checked)}
                />
                WhatsApp (automatic) <span className="text-be-muted">{buyerPhone || "no phone on this order"}</span>
              </label>
              <button
                type="button"
                onClick={resend}
                disabled={busy !== null || (!sendEmail && !sendSms && !sendWa)}
                className="be-act be-act-primary"
              >
                {busy === "resend" ? "Sending…" : "Resend tickets"}
              </button>

              <div className="space-y-1.5 border-t border-be-border pt-3">
                <button
                  type="button"
                  onClick={openWhatsApp}
                  disabled={!buyerPhone}
                  className="be-act be-act-ghost inline-flex items-center gap-1.5"
                >
                  <MessageCircle className="h-4 w-4" /> Send on WhatsApp
                </button>
                <p className="text-xs text-be-muted">
                  {buyerPhone
                    ? `Opens a chat to ${buyerPhone} with the ticket link ready. Make sure WhatsApp on this device is signed in as VibePass (${MERCHANT.phoneIntl}).`
                    : "No phone number on this order."}
                </p>
              </div>
            </>
          )}
        </section>
      )}

      {unpaid && (
        <section className="space-y-3">
          <h2 className="text-sm font-semibold text-be-text">Buyer says they paid?</h2>
          {!hasPendingItems ? (
            <p className="text-xs text-be-muted">
              This order has no saved ticket selection, so tickets can&apos;t be issued from here.
            </p>
          ) : (
            <>
              <label className="block">
                <span className="mb-1 block text-xs text-be-muted">M-Pesa receipt from the buyer&apos;s SMS (optional for the check)</span>
                <input
                  value={receipt}
                  onChange={(e) => setReceipt(e.target.value.toUpperCase())}
                  placeholder="e.g. SIT4ABC12D"
                  className="be-input w-full font-mono"
                />
              </label>
              {paymentMethod === "card" && (
                <div className="space-y-1">
                  <button type="button" onClick={checkPaystack} disabled={busy !== null} className="be-act be-act-primary">
                    {busy === "paystack" ? "Asking Paystack…" : "Check card payment with Paystack"}
                  </button>
                  <p className="text-xs text-be-muted">
                    If Paystack confirms the charge (and the amount matches), tickets are issued and emailed automatically.
                  </p>
                </div>
              )}
              {canQueryMpesa && (
                <div className="space-y-1">
                  <button type="button" onClick={checkMpesa} disabled={busy !== null} className="be-act be-act-primary">
                    {busy === "check" ? "Asking M-Pesa…" : "Check payment with M-Pesa"}
                  </button>
                  <p className="text-xs text-be-muted">
                    If Safaricom confirms it, tickets are issued and sent by email and SMS automatically.
                  </p>
                </div>
              )}
              {!manualOpen ? (
                <button type="button" onClick={() => setManualOpen(true)} className="be-act be-act-ghost">
                  Confirm manually…
                </button>
              ) : (
                <form onSubmit={confirmManually} className="space-y-2 border-t border-be-border pt-3">
                  <p className="text-xs text-be-muted">
                    Only after you&apos;ve found this payment on the KCB statement or M-Pesa portal
                    {paymentMethod !== "mpesa" ? " (or the card/PayPal dashboard)" : ""}. Recorded in the audit log.
                  </p>
                  <textarea
                    required
                    minLength={3}
                    maxLength={500}
                    value={note}
                    onChange={(e) => setNote(e.target.value)}
                    placeholder="Where you saw it, e.g. KCB statement 29 Sep, KES 1,500 from J. Mwangi"
                    className="be-input w-full text-sm"
                    rows={2}
                  />
                  <button type="submit" disabled={busy !== null || !receipt} className="be-act be-act-warn">
                    {busy === "manual" ? "Issuing…" : "Mark paid & issue tickets"}
                  </button>
                  {!receipt && <p className="text-xs text-be-muted">Enter the receipt number above first.</p>}
                </form>
              )}
            </>
          )}
        </section>
      )}

      {status === "refunded" && <p className="text-sm text-be-muted">This order was refunded; its tickets are void.</p>}

      {message && (
        <p
          className={`text-xs ${
            message.tone === "ok"
              ? "text-[color:var(--pill-ok-fg)]"
              : message.tone === "warn"
                ? "text-[color:var(--pill-warn-fg)]"
                : "text-[color:var(--pill-danger-fg)]"
          }`}
        >
          {message.text}
        </p>
      )}
    </Card>
  );
}
