"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";

const inputClass =
  "mt-2 h-11 w-full rounded-xl border border-slate-200/80 bg-white px-4 text-sm font-medium text-[#0D1B2A] outline-none transition focus:border-[#1D4ED8] focus:ring-2 focus:ring-[#1D4ED8]/20";

export function PaymentActions({
  paymentId,
  provider,
  status,
  refundableCents,
  refunds,
}: {
  paymentId: string;
  provider: string;
  status: string;
  refundableCents: number;
  refunds: Array<{ id: string; status: string }>;
}) {
  const router = useRouter();
  const [isUpdating, setIsUpdating] = useState(false);
  const [isRefunding, setIsRefunding] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [currentPassword, setCurrentPassword] = useState("");
  const [reconcilingRefundId, setReconcilingRefundId] = useState("");

  const updateStatus = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setIsUpdating(true);
    setMessage("");
    setError("");
    const form = new FormData(event.currentTarget);
    const response = await fetch(`/api/admin/payments/${paymentId}/reconcile`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(Object.fromEntries(form)),
    });
    const payload = (await response.json()) as { error?: string };
    if (!response.ok) setError(payload.error || "Unable to update payment status.");
    else {
      setMessage("Payment reconciliation updated.");
      router.refresh();
    }
    setIsUpdating(false);
  };

  const refund = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setIsRefunding(true);
    setMessage("");
    setError("");
    const form = new FormData(event.currentTarget);
    const response = await fetch(`/api/admin/payments/${paymentId}/refund`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(Object.fromEntries(form)),
    });
    const payload = (await response.json()) as { error?: string };
    if (!response.ok) setError(payload.error || "Unable to process this refund.");
    else {
      setMessage("Refund recorded successfully.");
      router.refresh();
    }
    setIsRefunding(false);
  };

  const reconcile = async (refundId: string) => {
    if (!currentPassword) {
      setError("Enter your current password before reconciling a Stripe refund.");
      return;
    }
    setReconcilingRefundId(refundId);
    setMessage("");
    setError("");
    try {
      const response = await fetch(`/api/admin/refunds/${refundId}/reconcile`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ currentPassword }),
      });
      const payload = (await response.json()) as { error?: string; status?: string };
      if (!response.ok) throw new Error(payload.error || "Unable to reconcile this refund.");
      setMessage(payload.status === "succeeded" ? "Refund confirmed by Stripe." : "Stripe refund checked. It is still pending or needs review.");
      router.refresh();
    } catch (requestError) {
      setError(requestError instanceof Error ? requestError.message : "Unable to reconcile this refund.");
    } finally {
      setReconcilingRefundId("");
    }
  };

  return (
    <aside className="space-y-5">
      {provider !== "stripe" && !["refunded"].includes(status) && (
        <form onSubmit={updateStatus} className="rounded-2xl border border-slate-200/80 bg-white p-6 shadow-xs sm:p-7">
          <p className="text-[10px] font-extrabold uppercase tracking-[0.16em] text-slate-400">Manual reconciliation</p>
          <label className="mt-4 block text-xs font-semibold text-slate-700">
            Payment status
            <select name="status" defaultValue={status} className={inputClass}>
              <option value="pending">Pending</option>
              <option value="paid">Paid</option>
              <option value="failed">Failed</option>
              <option value="cancelled">Cancelled</option>
            </select>
          </label>
          <label className="mt-4 block text-xs font-semibold text-slate-700">
            Internal reason
            <textarea required minLength={3} maxLength={1000} name="reason" rows={3} className={`${inputClass} h-auto py-2.5`} />
          </label>
          <button type="submit" disabled={isUpdating} className="mt-5 w-full rounded-xl bg-[#1D4ED8] px-5 py-2.5 text-xs font-semibold text-white shadow-xs transition hover:bg-[#1e40af] disabled:opacity-50">
            {isUpdating ? "Updating..." : "Update payment status"}
          </button>
        </form>
      )}

      {refundableCents > 0 && ["paid", "partially_refunded"].includes(status) && (
        <form onSubmit={refund} className="rounded-2xl border border-orange-200/80 bg-orange-50/40 p-6 shadow-xs sm:p-7">
          <p className="text-[10px] font-extrabold uppercase tracking-[0.16em] text-[#F97316]">Issue refund</p>
          <p className="mt-2 text-xs leading-relaxed text-slate-600">Choose the exact amount. This creates a separate refund record and never deletes the original payment.</p>
          <label className="mt-4 block text-xs font-semibold text-slate-700">
            Refund amount (AUD)
            <input required type="number" name="amount" min={0.01} max={(refundableCents / 100).toFixed(2)} step="0.01" defaultValue={(refundableCents / 100).toFixed(2)} className={inputClass} />
          </label>
          <label className="mt-4 block text-xs font-semibold text-slate-700">
            Reason
            <select name="reason" defaultValue="event_cancelled" className={inputClass}>
              <option value="event_cancelled">Event cancelled</option>
              <option value="customer_request">Customer request</option>
              <option value="duplicate">Duplicate payment</option>
              <option value="service_issue">Service issue</option>
              <option value="other">Other</option>
            </select>
          </label>
          <label className="mt-4 block text-xs font-semibold text-slate-700">
            Internal notes
            <textarea required minLength={3} maxLength={1000} name="notes" rows={3} className={`${inputClass} h-auto py-2.5`} />
          </label>
          <label className="mt-4 block text-xs font-semibold text-slate-700">
            Confirm with your current password
            <input required type="password" name="currentPassword" value={currentPassword} onChange={(event) => setCurrentPassword(event.target.value)} autoComplete="current-password" className={inputClass} />
          </label>
          <button type="submit" disabled={isRefunding} className="mt-5 w-full rounded-xl bg-[#F97316] px-5 py-2.5 text-xs font-semibold text-white shadow-xs transition hover:bg-[#ea580c] disabled:opacity-50">
            {isRefunding ? "Processing..." : provider === "stripe" ? "Refund through Stripe" : "Record refund"}
          </button>
        </form>
      )}
      {provider === "stripe" && refunds.some((refund) => ["pending", "failed"].includes(refund.status)) && (
        <section className="rounded-2xl border border-slate-200/80 bg-white p-6 shadow-xs sm:p-7">
          <p className="text-[10px] font-extrabold uppercase tracking-[0.16em] text-slate-400">Stripe reconciliation</p>
          <p className="mt-3 text-xs leading-5 text-slate-600">Retrying checks the same provider refund or safely reuses its idempotency key. It never creates a second refund.</p>
          <div className="mt-4 space-y-2">
            {refunds.filter((refund) => ["pending", "failed"].includes(refund.status)).map((refund) => (
              <button key={refund.id} type="button" disabled={Boolean(reconcilingRefundId)} onClick={() => reconcile(refund.id)} className="w-full rounded-xl border border-slate-200/80 bg-white px-4 py-2.5 text-xs font-semibold text-[#0D1B2A] shadow-xs transition hover:bg-slate-50 disabled:opacity-50">
                {reconcilingRefundId === refund.id ? "Checking Stripe..." : `Reconcile ${refund.status} refund`}
              </button>
            ))}
          </div>
        </section>
      )}
      {message && <p className="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-2.5 text-xs font-semibold text-emerald-700">{message}</p>}
      {error && <p className="rounded-xl border border-rose-200 bg-rose-50 px-4 py-2.5 text-xs font-semibold text-rose-700">{error}</p>}
    </aside>
  );
}
