"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Check } from "lucide-react";
import { adminReconcileMidtransAction } from "@/features/booking/actions";

interface AdminReconcileButtonProps {
  orderId: string;
  disabled?: boolean;
}

export function AdminReconcileButton({
  orderId,
  disabled,
}: AdminReconcileButtonProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState<string | null>(null);
  const [error, setError] = useState("");

  async function handleClick() {
    setLoading(true);
    setError("");
    setStatus(null);
    const res = await adminReconcileMidtransAction(orderId);
    setLoading(false);
    if ("error" in res && res.error) {
      setError(res.error);
      return;
    }
    if ("status" in res && res.status) {
      setStatus(res.status);
    }
    router.refresh();
  }

  return (
    <div className="inline-flex flex-col items-end gap-1">
      <button
        type="button"
        onClick={handleClick}
        disabled={loading || disabled}
        className="rounded-lg bg-secondary-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-secondary-700 disabled:cursor-not-allowed disabled:opacity-50"
      >
        {loading ? "Reconciling..." : "Reconcile Midtrans"}
      </button>
      {status && (
        <span className="inline-flex items-center gap-1 text-[11px] font-medium text-emerald-700">
          <Check size={12} strokeWidth={2.5} aria-hidden />
          {reconcileOutcomeLabel(status)}
        </span>
      )}
      {error && (
        <span className="text-[11px] font-medium text-red-600">{error}</span>
      )}
    </div>
  );
}

function reconcileOutcomeLabel(status: string): string {
  switch (status) {
    case "updated":
      return "Status di-update";
    case "skipped":
      return "Sudah final (tidak ada perubahan)";
    case "ignored":
      return "Tidak dikenali (mungkin sudah dihapus)";
    case "booking_conflict":
      return "Gateway PAID tapi booking di state konflik — perlu review manual";
    case "not_found":
      return "Order tidak ditemukan di Midtrans";
    default:
      return status;
  }
}
