"use client";

import {useRef, useState, useTransition} from "react";
import {registerPayment} from "@/features/invoices/server/actions";

type RegisterPaymentFormProps = {
  tenantId: string;
  tenantSlug: string;
  bookingId?: string;
  invoiceId?: string;
  currency: string;
  outstanding: number;
};

export function RegisterPaymentForm({
  tenantId,
  tenantSlug,
  bookingId,
  invoiceId,
  currency,
  outstanding
}: RegisterPaymentFormProps) {
  const [open, setOpen] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [isPending, startTransition] = useTransition();
  const formRef = useRef<HTMLFormElement>(null);

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    fd.set("tenantId", tenantId);
    fd.set("tenantSlug", tenantSlug);
    if (bookingId) fd.set("bookingId", bookingId);
    if (invoiceId) fd.set("invoiceId", invoiceId);
    fd.set("currency", currency);

    setError(null);
    startTransition(async () => {
      const result = await registerPayment(fd);
      if (result.success) {
        setSuccess(true);
        setOpen(false);
        formRef.current?.reset();
      } else {
        setError(result.error ?? "Error");
      }
    });
  }

  return (
    <div>
      {success && (
        <p className="mb-3 text-sm text-green-600 font-medium">Payment registered successfully.</p>
      )}
      {!open ? (
        <button
          onClick={() => setOpen(true)}
          className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 transition"
        >
          Register Payment
        </button>
      ) : (
        <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
          <h3 className="mb-4 font-semibold text-slate-900">Register Manual Payment</h3>
          <form ref={formRef} onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">
                Amount ({currency})
              </label>
              <input
                name="amount"
                type="number"
                step="0.01"
                min="0.01"
                max={outstanding}
                defaultValue={outstanding.toFixed(2)}
                required
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Payment Method</label>
              <select
                name="method"
                required
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
              >
                <option value="CASH">Cash</option>
                <option value="CARD">Card</option>
                <option value="BANK_TRANSFER">Bank Transfer</option>
                <option value="ONLINE_GATEWAY">Online Gateway</option>
                <option value="WALLET">Wallet</option>
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Reference (optional)</label>
              <input
                name="reference"
                type="text"
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
                placeholder="Transaction reference..."
              />
            </div>
            {error && <p className="text-sm text-red-600">{error}</p>}
            <div className="flex gap-3">
              <button
                type="submit"
                disabled={isPending}
                className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50 transition"
              >
                {isPending ? "Saving..." : "Save Payment"}
              </button>
              <button
                type="button"
                onClick={() => setOpen(false)}
                className="rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 hover:bg-slate-50 transition"
              >
                Cancel
              </button>
            </div>
          </form>
        </div>
      )}
    </div>
  );
}
