"use client";

import { useState, useEffect, use } from "react";
import { useRouter } from "next/navigation";
import { useFamily } from "@/app/FamilyProvider";

type State = "loading" | "preview" | "joining" | "success" | "error";

export default function JoinCirclePage({ params }: { params: Promise<{ token: string }> }) {
  const { token }    = use(params);
  const router       = useRouter();
  const { familyId, loading: authLoading } = useFamily();

  const [state, setState]         = useState<State>("loading");
  const [circleName, setCircleName] = useState("");
  const [memberCount, setMemberCount] = useState(0);
  const [errorMsg, setErrorMsg]   = useState("");

  // Preview the circle info (no auth required)
  useEffect(() => {
    fetch(`/api/circle/join/${token}`)
      .then(r => r.json())
      .then(data => {
        if (data.error) { setErrorMsg(data.error); setState("error"); return; }
        setCircleName(data.circleName);
        setMemberCount(data.memberCount);
        setState("preview");
      })
      .catch(() => { setErrorMsg("Could not load this invite."); setState("error"); });
  }, [token]);

  const joinCircle = async () => {
    if (!familyId) {
      // Not logged in — redirect to login with return URL
      router.push(`/login?next=/circle/join/${token}`);
      return;
    }
    setState("joining");
    try {
      const res  = await fetch(`/api/circle/join/${token}`, { method: "POST" });
      const data = await res.json();
      if (data.success) {
        setState("success");
        setTimeout(() => router.push(`/circle/${data.circleId}`), 1500);
      } else {
        setErrorMsg(data.error ?? "Could not join circle.");
        setState("error");
      }
    } catch {
      setErrorMsg("Something went wrong. Please try again.");
      setState("error");
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-rose-50 to-amber-50 dark:from-gray-900 dark:to-gray-800 flex items-center justify-center p-6">
      <div className="w-full max-w-sm bg-white dark:bg-gray-800 rounded-3xl shadow-xl p-6 text-center">

        {(state === "loading" || authLoading) && (
          <>
            <div className="flex justify-center gap-2 text-3xl mb-4">
              {["👨‍👩‍👧", "❤️", "👶"].map((e, i) => (
                <span key={i} className="animate-bounce" style={{ animationDelay: `${i * 120}ms` }}>{e}</span>
              ))}
            </div>
            <p className="text-gray-500">Loading invite…</p>
          </>
        )}

        {state === "preview" && !authLoading && (
          <>
            <div className="w-16 h-16 bg-rose-100 dark:bg-rose-900/40 rounded-full flex items-center justify-center text-3xl mx-auto mb-4">
              👨‍👩‍👧‍👦
            </div>
            <h1 className="text-xl font-bold mb-1">You're invited!</h1>
            <p className="text-gray-500 text-sm mb-4">
              Join <strong className="text-gray-800 dark:text-white">{circleName}</strong>
              <br />
              <span className="text-xs">{memberCount} {memberCount === 1 ? "family" : "families"} already inside</span>
            </p>
            {!familyId && (
              <p className="text-xs text-amber-600 bg-amber-50 rounded-xl px-3 py-2 mb-4">
                You'll need to log in to Tia first.
              </p>
            )}
            <button
              onClick={joinCircle}
              className="w-full py-3 bg-rose-400 text-white rounded-xl font-semibold"
            >
              {familyId ? `Join ${circleName}` : "Log in to Join"}
            </button>
            <button onClick={() => router.push("/home")} className="mt-3 text-xs text-gray-400">
              Not now
            </button>
          </>
        )}

        {state === "joining" && (
          <>
            <div className="w-12 h-12 border-4 border-rose-400 border-t-transparent rounded-full animate-spin mx-auto mb-4" />
            <p className="text-gray-500">Joining circle…</p>
          </>
        )}

        {state === "success" && (
          <>
            <div className="text-5xl mb-4">🎉</div>
            <h1 className="text-xl font-bold mb-1">You're in!</h1>
            <p className="text-gray-500 text-sm">Welcome to <strong>{circleName}</strong>. Taking you there…</p>
          </>
        )}

        {state === "error" && (
          <>
            <div className="text-5xl mb-4">😕</div>
            <h1 className="text-lg font-bold mb-2 text-gray-800 dark:text-white">Invite issue</h1>
            <p className="text-gray-500 text-sm mb-5">{errorMsg}</p>
            <button onClick={() => router.push("/home")} className="w-full py-3 bg-gray-100 dark:bg-gray-700 rounded-xl text-sm">Go to Home</button>
          </>
        )}
      </div>
    </div>
  );
}
