"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { joinTripAction, cancelJoinAction } from "@/features/trip/actions";

interface JoinTripButtonProps {
  tripId: string;
  isLoggedIn: boolean;
  isOrganizer: boolean;
  isJoined: boolean;
  /** Trip gratis (price <= 0) — sembunyikan flow pembayaran */
  isFree: boolean;
  /** Status partisipasi user saat isJoined (bukan organizer) */
  participationStatus?: "PENDING" | "CONFIRMED" | null;
  /** Status pembayaran manual (peserta). Hanya relevan untuk trip berbayar. */
  participantPayment?: {
    markedPaidAt: string | Date | null;
    paymentConfirmedAt: string | Date | null;
  } | null;
  isFull: boolean;
  tripStatus: string;
  /** Tanggal berangkat trip sudah lewat */
  isDeparturePast?: boolean;
  /** Sembunyikan tombol cancel — dipakai saat booking PAID dan parent
   *  menampilkan CancelBookingButton (refund flow) di tempat terpisah. */
  hideCancelButton?: boolean;
}

export function JoinTripButton({
  tripId,
  isLoggedIn,
  isOrganizer,
  isJoined,
  isFree,
  participationStatus,
  participantPayment,
  isFull,
  tripStatus,
  isDeparturePast,
  hideCancelButton,
}: JoinTripButtonProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  if (!isLoggedIn) {
    return (
      <Link
        href="/login"
        className="block w-full rounded-xl bg-primary-600 py-3 text-center text-sm font-bold text-white shadow-lg shadow-primary-600/20 hover:bg-primary-700"
      >
        Login untuk Join Trip
      </Link>
    );
  }

  if (isOrganizer) {
    return (
      <div className="rounded-xl bg-secondary-50 py-3 text-center text-sm font-medium text-secondary-700">
        Kamu adalah organizer trip ini
      </div>
    );
  }

  if (isJoined && isDeparturePast) {
    return (
      <div className="rounded-xl bg-neutral-100 px-3 py-3 text-center text-sm font-medium leading-relaxed text-neutral-600">
        Kamu terdaftar di trip ini. Setelah tanggal berangkat lewat,{" "}
        <span className="font-semibold text-neutral-700">pembatalan ditutup</span>
        . Jika trip sudah selesai, isi ulasan di bagian bawah halaman.
      </div>
    );
  }

  if (isDeparturePast && !isJoined) {
    return (
      <div className="rounded-xl bg-neutral-100 py-3 text-center text-sm font-medium text-neutral-500">
        Trip sudah lewat tanggal berangkat
      </div>
    );
  }

  if (tripStatus !== "OPEN" && !isJoined) {
    return (
      <div className="rounded-xl bg-neutral-100 py-3 text-center text-sm font-medium text-neutral-500">
        Trip tidak tersedia untuk pendaftaran
      </div>
    );
  }

  async function handleJoin() {
    setLoading(true);
    setError("");
    const result = await joinTripAction(tripId);
    setLoading(false);
    if (result.error) {
      setError(result.error);
    } else {
      router.refresh();
    }
  }

  async function handleCancel() {
    setLoading(true);
    setError("");
    const result = await cancelJoinAction(tripId);
    setLoading(false);
    if (result.error) {
      setError(result.error);
    } else {
      router.refresh();
    }
  }

  const pay = participantPayment;
  const showPaymentLink = !isFree && isJoined && !isDeparturePast;
  const waitingPaymentConfirm =
    !isFree && isJoined && pay && pay.markedPaidAt && !pay.paymentConfirmedAt;
  const paymentDone = !isFree && isJoined && pay && pay.paymentConfirmedAt;

  return (
    <div>
      {error && (
        <div className="mb-3 rounded-xl bg-red-50 px-4 py-3 text-sm font-medium text-red-600">
          {error}
        </div>
      )}
      {isJoined && participationStatus === "PENDING" && (
        <div className="mb-3 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-medium leading-relaxed text-amber-900">
          Permintaan ikut trip kamu{" "}
          <span className="font-semibold">menunggu persetujuan organizer</span>.
          Kamu bisa membatalkan kapan saja sebelum disetujui.
        </div>
      )}
      {isJoined && participationStatus === "CONFIRMED" && (
        <div className="mb-3 rounded-xl border border-secondary-200 bg-secondary-50 px-4 py-3 text-sm font-medium text-secondary-900">
          Kamu sudah{" "}
          <span className="font-semibold">terkonfirmasi</span> sebagai peserta
          trip ini
          {isFree && <span> — trip gratis, tidak ada pembayaran 🎉</span>}.
        </div>
      )}
      {waitingPaymentConfirm && (
        <div className="mb-3 rounded-xl border border-primary-200 bg-primary-50 px-4 py-3 text-sm font-medium leading-relaxed text-primary-950">
          Kamu sudah menandai <span className="font-semibold">sudah bayar</span>.
          Tunggu organizer mengonfirmasi pembayaran.
        </div>
      )}
      {paymentDone && (
        <div className="mb-3 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm font-medium text-emerald-900">
          Pembayaran kamu sudah{" "}
          <span className="font-semibold">dikonfirmasi organizer</span>.
        </div>
      )}
      {showPaymentLink && (
        <Link
          href={`/trips/${tripId}/payment`}
          className="mb-3 block w-full rounded-xl border-2 border-primary-500 bg-white py-3 text-center text-sm font-bold text-primary-700 transition-colors hover:bg-primary-50"
        >
          {paymentDone
            ? "Lihat detail pembayaran"
            : pay?.markedPaidAt
              ? "Lihat status pembayaran"
              : "Buka detail pembayaran"}
        </Link>
      )}
      {isJoined ? (
        hideCancelButton ? null : (
          <button
            onClick={handleCancel}
            disabled={loading}
            className="w-full rounded-xl border-2 border-red-200 py-3 text-sm font-bold text-red-600 transition-colors hover:bg-red-50 disabled:opacity-50"
          >
            {loading ? "Memproses..." : "Batal Ikut"}
          </button>
        )
      ) : (
        <button
          onClick={handleJoin}
          disabled={loading || isFull}
          className="w-full rounded-xl bg-primary-600 py-3 text-sm font-bold text-white shadow-lg shadow-primary-600/20 transition-colors hover:bg-primary-700 disabled:opacity-50"
        >
          {loading
            ? "Memproses..."
            : isFull
            ? "Trip Sudah Penuh"
            : "Join Trip Sekarang"}
        </button>
      )}
    </div>
  );
}
