"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;
  isFull: boolean;
  tripStatus: string;
}

export function JoinTripButton({
  tripId,
  isLoggedIn,
  isOrganizer,
  isJoined,
  isFull,
  tripStatus,
}: 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 (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();
    }
  }

  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 ? (
        <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>
  );
}
