"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import {
  confirmParticipantAction,
  rejectParticipantAction,
} from "@/features/trip/actions";

export interface PendingJoinRequest {
  id: string;
  user: { name: string; image: string | null };
  /** Peserta sudah menekan &quot;Saya sudah bayar&quot; */
  markedPaidAt?: string | Date | null;
}

interface OrganizerJoinRequestsProps {
  tripId: string;
  pending: PendingJoinRequest[];
}

export function OrganizerJoinRequests({
  tripId,
  pending,
}: OrganizerJoinRequestsProps) {
  const router = useRouter();
  const [loadingId, setLoadingId] = useState<string | null>(null);
  const [error, setError] = useState("");

  async function run(
    participantId: string,
    action: "confirm" | "reject"
  ) {
    setLoadingId(participantId);
    setError("");
    const result =
      action === "confirm"
        ? await confirmParticipantAction(tripId, participantId)
        : await rejectParticipantAction(tripId, participantId);
    setLoadingId(null);
    if (result.error) {
      setError(result.error);
      return;
    }
    router.refresh();
  }

  return (
    <div className="rounded-xl border border-amber-200 bg-amber-50/70 p-4 sm:p-5">
      <h2 className="text-sm font-bold text-amber-950 sm:text-base">
        Permintaan join ({pending.length})
      </h2>
      <p className="mt-1 text-xs text-amber-900/80 sm:text-sm">
        Setujui atau tolak siapa yang boleh ikut trip ini.
      </p>
      {error && (
        <p className="mt-3 rounded-lg bg-red-50 px-3 py-2 text-xs font-medium text-red-700 sm:text-sm">
          {error}
        </p>
      )}
      <ul className="mt-4 space-y-3">
        {pending.map((p) => (
          <li
            key={p.id}
            className="flex flex-col gap-3 rounded-xl border border-amber-100 bg-white/90 p-3 sm:flex-row sm:items-center sm:justify-between"
          >
            <div className="flex min-w-0 items-center gap-3">
              {p.user.image ? (
                <Image
                  src={p.user.image}
                  alt=""
                  width={40}
                  height={40}
                  className="h-10 w-10 shrink-0 rounded-full object-cover"
                />
              ) : (
                <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-primary-600 text-sm font-bold text-white">
                  {p.user.name.charAt(0).toUpperCase()}
                </div>
              )}
              <div className="min-w-0">
                <p className="truncate text-sm font-semibold text-neutral-800">
                  {p.user.name}
                </p>
                <div className="flex flex-wrap items-center gap-1.5">
                  <p className="text-xs text-amber-800/80">Menunggu persetujuan</p>
                  {p.markedPaidAt ? (
                    <span className="rounded-full bg-primary-100 px-2 py-0.5 text-[10px] font-bold text-primary-800">
                      Sudah tandai bayar
                    </span>
                  ) : null}
                </div>
              </div>
            </div>
            <div className="flex shrink-0 gap-2">
              <button
                type="button"
                disabled={loadingId !== null}
                onClick={() => run(p.id, "reject")}
                className="rounded-lg border border-neutral-200 bg-white px-3 py-2 text-xs font-semibold text-neutral-600 hover:bg-neutral-50 disabled:opacity-50 sm:text-sm"
              >
                {loadingId === p.id ? "…" : "Tolak"}
              </button>
              <button
                type="button"
                disabled={loadingId !== null}
                onClick={() => run(p.id, "confirm")}
                className="rounded-lg bg-primary-600 px-3 py-2 text-xs font-semibold text-white shadow-sm hover:bg-primary-700 disabled:opacity-50 sm:text-sm"
              >
                {loadingId === p.id ? "Memproses…" : "Setujui"}
              </button>
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
}
