"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { createRefundAction } from "@/features/refund/actions";

const REASON_OPTIONS = [
  { value: "USER_CANCELLATION", label: "Peserta cancel sendiri" },
  { value: "ORGANIZER_CANCELLED", label: "Organizer batalkan trip" },
  { value: "TRIP_ISSUE", label: "Masalah saat/setelah trip" },
  { value: "ADMIN_ADJUSTMENT", label: "Penyesuaian admin" },
  { value: "DISPUTE_RESOLVED", label: "Hasil dispute / chargeback" },
  { value: "OTHER", label: "Lain-lain" },
];

const REPORTER_OPTIONS = [
  { value: "PARTICIPANT", label: "Peserta" },
  { value: "ORGANIZER", label: "Organizer" },
];

export function CreateRefundForm() {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError("");
    setLoading(true);
    const fd = new FormData(e.currentTarget);
    const result = await createRefundAction(fd);
    setLoading(false);
    if (result.error) {
      setError(result.error);
      return;
    }
    (e.target as HTMLFormElement).reset();
    setOpen(false);
    router.refresh();
  }

  if (!open) {
    return (
      <div className="mb-6 flex justify-end">
        <button
          type="button"
          onClick={() => setOpen(true)}
          className="rounded-xl bg-primary-600 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-700"
        >
          + Catat Laporan Refund
        </button>
      </div>
    );
  }

  return (
    <form
      onSubmit={onSubmit}
      className="mb-6 space-y-4 rounded-2xl border border-neutral-200 bg-white p-5 shadow-sm sm:p-6"
    >
      <header className="flex items-start justify-between gap-3 border-b border-neutral-100 pb-3">
        <div>
          <h2 className="text-base font-bold text-neutral-900">
            Catat Laporan Refund Manual
          </h2>
          <p className="mt-0.5 text-xs text-neutral-500">
            Masukkan laporan yang diterima dari peserta atau organizer (via
            WhatsApp/email). Refund akan masuk antrian PENDING untuk di-review.
          </p>
        </div>
        <button
          type="button"
          onClick={() => {
            setOpen(false);
            setError("");
          }}
          className="rounded-lg px-2 py-1 text-xs font-medium text-neutral-500 hover:bg-neutral-100"
        >
          Tutup
        </button>
      </header>

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

      <div className="grid gap-4 sm:grid-cols-2">
        <Field label="Booking ID" required>
          <input
            name="bookingId"
            required
            placeholder="cuid booking yang dilaporkan"
            className="w-full rounded-xl border border-neutral-200 bg-neutral-50 px-3 py-2 text-sm font-mono focus:bg-white"
          />
        </Field>

        <Field label="Pelapor" required>
          <select
            name="reportedBy"
            required
            defaultValue=""
            className="w-full rounded-xl border border-neutral-200 bg-neutral-50 px-3 py-2 text-sm focus:bg-white"
          >
            <option value="" disabled>
              Pilih pelapor
            </option>
            {REPORTER_OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
        </Field>

        <Field label="Alasan" required>
          <select
            name="reason"
            required
            defaultValue=""
            className="w-full rounded-xl border border-neutral-200 bg-neutral-50 px-3 py-2 text-sm focus:bg-white"
          >
            <option value="" disabled>
              Pilih alasan
            </option>
            {REASON_OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
        </Field>

        <Field
          label="Nominal (IDR)"
          hint="Kosongkan untuk full remaining"
        >
          <input
            name="amount"
            inputMode="numeric"
            pattern="[0-9]*"
            placeholder="mis. 500000"
            className="w-full rounded-xl border border-neutral-200 bg-neutral-50 px-3 py-2 text-sm focus:bg-white"
          />
        </Field>
      </div>

      <Field label="Isi laporan" required>
        <textarea
          name="reportNote"
          required
          rows={3}
          placeholder="Salin/ringkas laporan dari peserta/organizer"
          className="w-full rounded-xl border border-neutral-200 bg-neutral-50 px-3 py-2 text-sm focus:bg-white"
        />
      </Field>

      <div className="flex justify-end gap-2 border-t border-neutral-100 pt-3">
        <button
          type="button"
          onClick={() => {
            setOpen(false);
            setError("");
          }}
          className="rounded-xl border border-neutral-200 px-4 py-2 text-sm font-medium text-neutral-600 hover:bg-neutral-50"
        >
          Batal
        </button>
        <button
          type="submit"
          disabled={loading}
          className="rounded-xl bg-primary-600 px-4 py-2 text-sm font-bold text-white hover:bg-primary-700 disabled:opacity-50"
        >
          {loading ? "Menyimpan…" : "Simpan Laporan"}
        </button>
      </div>
    </form>
  );
}

function Field({
  label,
  hint,
  required,
  children,
}: {
  label: string;
  hint?: string;
  required?: boolean;
  children: React.ReactNode;
}) {
  return (
    <label className="block">
      <div className="mb-1 flex items-baseline justify-between gap-2">
        <span className="text-xs font-semibold uppercase tracking-wide text-neutral-600">
          {label}
          {required && <span className="text-red-500"> *</span>}
        </span>
        {hint && <span className="text-xs text-neutral-400">{hint}</span>}
      </div>
      {children}
    </label>
  );
}
