"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "@/components/ui/toast";

export function CoachReviewActions({
  coachId,
  currentStatus,
  initialNotes,
}: {
  coachId: string;
  currentStatus: string;
  initialNotes: string;
}) {
  const router = useRouter();
  const [notes, setNotes] = useState(initialNotes);
  const [busyDecision, setBusyDecision] = useState("");
  const [message, setMessage] = useState("");
  const [isError, setIsError] = useState(false);

  const review = async (decision: "approved" | "rejected") => {
    if (decision === "rejected" && notes.trim().length < 5) {
      setIsError(true);
      const err = "Add a short reason before rejecting the application.";
      setMessage(err);
      toast.error("Reason required", { description: err });
      return;
    }

    setBusyDecision(decision);
    setMessage("");
    setIsError(false);
    try {
      const response = await fetch(`/api/admin/coaches/${coachId}/review`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ decision, reviewerNotes: notes }),
      });
      const payload = (await response.json()) as { error?: string };
      if (!response.ok) throw new Error(payload.error || "Unable to save review.");
      const successText = decision === "approved" ? "Application approved." : "Application rejected.";
      setMessage(successText);
      toast.success(successText, {
        description: "Coach status updated and audit log recorded.",
      });
      router.refresh();
    } catch (error) {
      const errorText = error instanceof Error ? error.message : "Unable to save review.";
      setIsError(true);
      setMessage(errorText);
      toast.error("Review action failed", { description: errorText });
    } finally {
      setBusyDecision("");
    }
  };

  return (
    <section className="rounded-2xl border border-slate-200/80 bg-white p-6 shadow-xs">
      <p className="text-[10px] font-extrabold uppercase tracking-[0.16em] text-[#F97316]">
        Admin decision
      </p>
      <h2 className="mt-1 text-lg font-bold tracking-tight text-[#0D1B2A]">Approve team access or request changes</h2>
      <p className="mt-1.5 text-xs leading-relaxed text-slate-500">
        Approval unlocks coach tools but keeps the applicant&apos;s family account and parent controls unchanged.
      </p>
      <label className="mt-5 block text-xs font-semibold text-slate-700">
        Review notes
        <textarea
          rows={4}
          value={notes}
          onChange={(event) => setNotes(event.target.value)}
          placeholder="Record checks completed, or explain what must be corrected."
          className="mt-1.5 w-full resize-none rounded-xl border border-slate-200/80 bg-white px-4 py-2.5 text-sm font-medium outline-none transition focus:border-[#1D4ED8] focus:ring-2 focus:ring-[#1D4ED8]/20"
        />
      </label>
      <div className="mt-5 flex flex-wrap gap-2.5">
        <button
          type="button"
          disabled={Boolean(busyDecision)}
          onClick={() => review("approved")}
          className="rounded-xl bg-emerald-600 px-4 py-2.5 text-xs font-semibold text-white shadow-xs transition hover:bg-emerald-700 disabled:opacity-50"
        >
          {busyDecision === "approved" ? "Approving..." : "Approve application"}
        </button>
        <button
          type="button"
          disabled={Boolean(busyDecision)}
          onClick={() => review("rejected")}
          className="rounded-xl border border-rose-200 bg-rose-50 px-4 py-2.5 text-xs font-semibold text-rose-700 transition hover:bg-rose-100 disabled:opacity-50"
        >
          {busyDecision === "rejected" ? "Rejecting..." : "Reject with reason"}
        </button>
      </div>
      {message && (
        <p className={`mt-3 text-xs font-semibold ${isError ? "text-rose-600" : "text-emerald-700"}`}>
          {message}
        </p>
      )}
      {currentStatus !== "pending" && (
        <p className="mt-4 text-xs text-slate-400">
          Current decision: <strong className="capitalize text-[#0D1B2A]">{currentStatus}</strong>. Saving another decision will replace it and remain in the audit log.
        </p>
      )}
    </section>
  );
}
