"use client";

import { useCallback, useEffect, useState } from "react";
import { formatCop } from "@/data/products";
import { StatusPill } from "@/components/admin/NegocioShell";
import { useAdmin } from "@/context/AdminContext";

type OtOrder = {
  id: string;
  display_id?: number;
  email?: string;
  total?: number;
  created_at?: string;
  status?: string;
  medusa_status?: string;
  wompi_reference?: string | null;
  wompi_transaction_id?: string | null;
  notes?: string;
  cancel_reason?: string;
  canceled_at?: string | null;
  refund_status?: string;
  refund_note?: string;
  refunded_at?: string | null;
  shipping_address?: {
    first_name?: string;
    last_name?: string;
    phone?: string;
    address_1?: string;
    address_2?: string;
    city?: string;
    province?: string;
  } | null;
  items?: {
    id: string;
    title?: string;
    quantity?: number;
    variant_title?: string;
  }[];
};

type Counts = {
  cancelable: number;
  cancelado: number;
  all: number;
};

const TABS: { id: string; label: string }[] = [
  { id: "cancelable", label: "Pueden cancelarse" },
  { id: "cancelado", label: "Cancelados" },
  { id: "all", label: "Todos" },
];

const REFUND_LABEL: Record<string, string> = {
  none: "Sin reembolso",
  pending_manual: "Reembolso pendiente (Wompi)",
  done: "Reembolso registrado",
};

export default function NegocioCancelacionesPage() {
  const { authenticated, loading: authLoading } = useAdmin();
  const [tab, setTab] = useState("cancelable");
  const [orders, setOrders] = useState<OtOrder[]>([]);
  const [counts, setCounts] = useState<Counts | null>(null);
  const [loading, setLoading] = useState(false);
  const [busyId, setBusyId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [info, setInfo] = useState<string | null>(null);
  const [draft, setDraft] = useState<{
    id: string;
    reason: string;
    refund_note: string;
  } | null>(null);

  const load = useCallback(async (status: string) => {
    setLoading(true);
    setError(null);
    const res = await fetch(`/api/ops/orders?status=${status}`, {
      cache: "no-store",
    });
    if (res.ok) {
      const data = (await res.json()) as {
        orders?: OtOrder[];
        counts?: Counts;
      };
      setOrders(data.orders || []);
      setCounts(data.counts || null);
    } else {
      setError("No se pudieron cargar los pedidos.");
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    if (authenticated) load(tab);
  }, [authenticated, load, tab]);

  const openCancel = (order: OtOrder) => {
    setInfo(null);
    setError(null);
    setDraft({
      id: order.id,
      reason: "",
      refund_note: "",
    });
  };

  const confirmCancel = async () => {
    if (!draft) return;
    setBusyId(draft.id);
    setError(null);
    setInfo(null);
    const res = await fetch(`/api/ops/orders/${draft.id}/cancel`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        reason: draft.reason,
        refund_note: draft.refund_note,
      }),
    });
    const data = (await res.json().catch(() => ({}))) as {
      message?: string;
    };
    setBusyId(null);
    if (!res.ok) {
      setError(data.message || "No se pudo cancelar.");
      return;
    }
    setDraft(null);
    setInfo(
      data.message ||
        "Pedido cancelado. Recuerda reembolsar en Wompi y marcarlo aquí."
    );
    setTab("cancelado");
    await load("cancelado");
  };

  const markRefunded = async (id: string) => {
    setBusyId(id);
    setError(null);
    setInfo(null);
    const note = window.prompt(
      "Nota del reembolso (ej. ID de transacción Wompi):",
      "Reembolsado en panel Wompi"
    );
    if (note === null) {
      setBusyId(null);
      return;
    }
    const res = await fetch(`/api/ops/orders/${id}/refund`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ refund_note: note }),
    });
    const data = (await res.json().catch(() => ({}))) as { message?: string };
    setBusyId(null);
    if (!res.ok) {
      setError(data.message || "No se pudo marcar el reembolso.");
      return;
    }
    setInfo("Reembolso marcado como registrado.");
    await load(tab);
  };

  if (authLoading || !authenticated) return null;

  return (
    <div className="space-y-8">
      <div className="flex flex-wrap items-center gap-3">
        <p className="ot-eyebrow">Fase B</p>
        <StatusPill status="activo" />
      </div>
      <div>
        <h1 className="font-serif text-4xl">Cancelaciones y reembolsos</h1>
        <p className="text-sm text-ot-muted mt-2 max-w-2xl">
          Cancela pedidos que aún no se despacharon. Medusa libera el stock
          reservado. El dinero en Wompi se reembolsa a mano en el panel de Wompi
          y luego lo marcas aquí como hecho.
        </p>
      </div>

      <div className="flex flex-wrap gap-2">
        {TABS.map((t) => (
          <button
            key={t.id}
            type="button"
            onClick={() => setTab(t.id)}
            className={`px-4 py-2 text-xs tracking-[0.14em] uppercase border ${
              tab === t.id
                ? "border-ot-green bg-ot-green text-ot-cream"
                : "border-black/15 bg-white"
            }`}
          >
            {t.label}
            {counts ? (
              <span className="ml-2 opacity-80">
                (
                {t.id === "cancelable"
                  ? counts.cancelable
                  : t.id === "cancelado"
                    ? counts.cancelado
                    : counts.all}
                )
              </span>
            ) : null}
          </button>
        ))}
      </div>

      {error ? <p className="text-sm text-red-700">{error}</p> : null}
      {info ? <p className="text-sm text-ot-green">{info}</p> : null}

      {draft ? (
        <div className="border border-black/10 bg-white p-5 space-y-3 max-w-xl">
          <h2 className="font-serif text-2xl">Cancelar pedido</h2>
          <p className="text-sm text-ot-muted">
            Esta acción cancela el pedido en la tienda. No revierte el pago en
            Wompi automáticamente.
          </p>
          <textarea
            className="w-full border border-black/15 px-4 py-3 text-sm outline-none focus:border-ot-green"
            rows={3}
            placeholder="Motivo de la cancelación"
            value={draft.reason}
            onChange={(e) => setDraft({ ...draft, reason: e.target.value })}
          />
          <textarea
            className="w-full border border-black/15 px-4 py-3 text-sm outline-none focus:border-ot-green"
            rows={2}
            placeholder="Nota interna de reembolso (opcional)"
            value={draft.refund_note}
            onChange={(e) =>
              setDraft({ ...draft, refund_note: e.target.value })
            }
          />
          <div className="flex flex-wrap gap-2">
            <button
              type="button"
              className="ot-btn"
              disabled={busyId === draft.id}
              onClick={() => void confirmCancel()}
            >
              {busyId === draft.id ? "Cancelando…" : "Confirmar cancelación"}
            </button>
            <button
              type="button"
              className="ot-btn ot-btn-ghost"
              onClick={() => setDraft(null)}
            >
              Volver
            </button>
          </div>
        </div>
      ) : null}

      {loading ? (
        <p className="text-ot-muted text-sm">Cargando…</p>
      ) : !orders.length ? (
        <p className="text-ot-muted text-sm">No hay pedidos en esta vista.</p>
      ) : (
        <div className="space-y-4">
          {orders.map((order) => {
            const addr = order.shipping_address;
            const name = [addr?.first_name, addr?.last_name]
              .filter(Boolean)
              .join(" ");
            const canCancel =
              order.status === "por_alistar" || order.status === "alistado";
            const needsRefund = order.refund_status === "pending_manual";
            return (
              <article
                key={order.id}
                className="border border-black/10 bg-white p-5"
              >
                <div className="flex flex-wrap justify-between gap-3">
                  <div>
                    <p className="font-serif text-2xl">
                      Pedido #{order.display_id || order.id.slice(-6)}
                    </p>
                    <p className="text-sm text-ot-muted mt-1">
                      {name || "Cliente"} · {order.email}
                    </p>
                    <p className="text-sm mt-1">
                      {formatCop(order.total || 0)}
                      {order.wompi_reference ? (
                        <span className="text-ot-muted">
                          {" "}
                          · Ref Wompi: {order.wompi_reference}
                        </span>
                      ) : null}
                    </p>
                  </div>
                  <div className="text-right text-xs tracking-[0.12em] uppercase space-y-1">
                    <p>
                      {order.status === "cancelado"
                        ? "Cancelado"
                        : order.status}
                    </p>
                    <p className="text-ot-gold normal-case tracking-normal">
                      {REFUND_LABEL[order.refund_status || "none"] ||
                        order.refund_status}
                    </p>
                  </div>
                </div>

                <ul className="mt-4 text-sm space-y-1">
                  {(order.items || []).map((item) => (
                    <li key={item.id}>
                      {item.quantity}× {item.title}
                      {item.variant_title ? ` · ${item.variant_title}` : ""}
                    </li>
                  ))}
                </ul>

                {order.cancel_reason ? (
                  <p className="mt-3 text-sm text-ot-muted">
                    Motivo: {order.cancel_reason}
                  </p>
                ) : null}
                {order.refund_note ? (
                  <p className="mt-1 text-sm text-ot-muted">
                    Nota reembolso: {order.refund_note}
                  </p>
                ) : null}

                <div className="mt-4 flex flex-wrap gap-2">
                  {canCancel ? (
                    <button
                      type="button"
                      className="ot-btn !text-[11px] !py-2"
                      disabled={busyId === order.id}
                      onClick={() => openCancel(order)}
                    >
                      Cancelar pedido
                    </button>
                  ) : null}
                  {order.status === "cancelado" && needsRefund ? (
                    <button
                      type="button"
                      className="ot-btn ot-btn-ghost !text-[11px] !py-2"
                      disabled={busyId === order.id}
                      onClick={() => void markRefunded(order.id)}
                    >
                      Marcar reembolso hecho
                    </button>
                  ) : null}
                  {order.wompi_transaction_id ? (
                    <a
                      href="https://comercios.wompi.co/"
                      target="_blank"
                      rel="noreferrer"
                      className="ot-btn ot-btn-ghost !text-[11px] !py-2 inline-flex"
                    >
                      Abrir Wompi
                    </a>
                  ) : null}
                </div>
              </article>
            );
          })}
        </div>
      )}
    </div>
  );
}
