"use client";

import { useState, useEffect, use } from "react";
import { useRouter } from "next/navigation";

export default function InvitePage({ params }: { params: Promise<{ token: string }> }) {
  const { token } = use(params);
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [invite, setInvite] = useState<any>(null);

  useEffect(() => {
    async function checkInvite() {
      try {
        // Get current user (would use NextAuth in production)
        const userId = "current-user-id"; // TODO: Get from session

        const res = await fetch("/api/invites/accept", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ token, userId }),
        });

        const data = await res.json();

        if (data.success) {
          router.push("/home");
        } else {
          setError(data.error || "Invalid invite");
        }
      } catch (err) {
        setError("Failed to accept invite");
      } finally {
        setLoading(false);
      }
    }

    checkInvite();
  }, [token, router]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="text-4xl mb-4">⏳</div>
          <p>Accepting invite...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center p-8">
          <div className="text-4xl mb-4">❌</div>
          <p className="text-red-500">{error}</p>
          <button onClick={() => router.push("/home")} className="mt-4 px-4 py-2 bg-rose-400 text-white rounded-lg">
            Go Home
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center">
      <div className="text-center">
        <div className="text-4xl mb-4">✅</div>
        <p>Invite accepted!</p>
      </div>
    </div>
  );
}