"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { adminCancelTripAction } from "@/features/trip/actions";

interface AdminCancelTripButtonProps {
  tripId: string;
}

export function AdminCancelTripButton({ tripId }: AdminCancelTripButtonProps) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [reason, setReason] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [result, setResult] = useState<{
    refundCount: number;
    cancelledCount: number;
    skippedCount: number;
  } | null>(null);

  async function handleConfirm() {
    setLoading(true);
    setError("");
    const res = await adminCancelTripAction(tripId, reason);
    setLoading(false);
    if ("error" in res && res.error) {
      setError(res.error);
      return;
    }
    if ("success" in res && res.success) {
      setResult({
        refundCount: res.refundCount,
        cancelledCount: res.cancelledCount,
        skippedCount: res.skippedCount,
      });
      router.refresh();
    }
  }

  if (result) {
    return (
      <div className="rounded-xl border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-900">
        <p className="font-bold">✅ Trip berhasil dibatalkan.</p>
        <ul className="mt-2 space-y-0.5 text-xs">
          <li>• {result.refundCount} booking PAID → refund auto-dibuat</li>
          <li>
            • {result.cancelledCount} booking PENDING/AWAITING_PAY → CANCELLED
          </li>
          {result.skippedCount > 0 && (
            <li>
              • {result.skippedCount} booking di-skip (sudah ada refund aktif —
              cek manual)
            </li>
          )}
        </ul>
      </div>
    );
  }

  if (!open) {
    return (
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="rounded-xl bg-red-600 px-4 py-2 text-sm font-bold text-white shadow-sm hover:bg-red-700"
      >
        Cancel Trip (Admin)
      </button>
    );
  }

  return (
    <div className="space-y-3">
      <div>
        <label
          htmlFor="cancel-reason"
          className="mb-1 block text-xs font-semibold text-red-900"
        >
          Alasan cancel (wajib, min 10 karakter — untuk audit)
        </label>
        <textarea
          id="cancel-reason"
          rows={3}
          value={reason}
          onChange={(e) => setReason(e.target.value)}
          maxLength={500}
          placeholder="contoh: Organizer tidak responsif sejak H-7, peserta lapor via WA. Safety issue tidak terjawab."
          className="w-full rounded-xl border border-red-200 bg-white px-3 py-2 text-sm text-neutral-800 placeholder:text-neutral-400 focus:border-red-400"
        />
        <p className="mt-1 text-[11px] text-red-900/70">
          {reason.trim().length}/500 karakter
        </p>
      </div>

      {error && (
        <div className="rounded-lg bg-red-100 px-3 py-2 text-xs font-medium text-red-700">
          {error}
        </div>
      )}

      <div className="flex gap-2">
        <button
          type="button"
          onClick={handleConfirm}
          disabled={loading || reason.trim().length < 10}
          className="rounded-xl bg-red-600 px-4 py-2 text-sm font-bold text-white shadow-sm hover:bg-red-700 disabled:cursor-not-allowed disabled:opacity-50"
        >
          {loading ? "Membatalkan..." : "Konfirmasi Cancel"}
        </button>
        <button
          type="button"
          onClick={() => {
            setOpen(false);
            setReason("");
            setError("");
          }}
          disabled={loading}
          className="rounded-xl border border-neutral-200 bg-white px-4 py-2 text-sm font-semibold text-neutral-700 hover:bg-neutral-50 disabled:opacity-50"
        >
          Batal
        </button>
      </div>
    </div>
  );
}
