import { useContext, useEffect, useMemo, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import { acceptInviteLink, getInviteLinkSummary } from "../api/households";
import { AuthContext } from "../context/AuthContext";
import { HouseholdContext } from "../context/HouseholdContext";
import useActionToast from "../hooks/useActionToast";
import getApiErrorMessage from "../lib/getApiErrorMessage";
import "../styles/pages/InviteLink.css";

function humanizeStatus(code) {
  switch (code) {
    case "ALREADY_MEMBER":
      return "You are already a member of this group.";
    case "PENDING":
      return "Your join request is already pending approval.";
    case "REVOKED":
      return "This invite link has been revoked.";
    case "EXPIRED":
      return "This invite link has expired.";
    case "USED":
      return "This invite link has already been used.";
    case "NOT_ACCEPTING":
      return "This group is not accepting new members right now.";
    default:
      return "";
  }
}

export default function InviteLink() {
  const { token } = useParams();
  const navigate = useNavigate();
  const { token: authToken } = useContext(AuthContext);
  const { refreshHouseholds } = useContext(HouseholdContext);
  const toast = useActionToast();
  const [loading, setLoading] = useState(true);
  const [joining, setJoining] = useState(false);
  const [link, setLink] = useState(null);
  const [error, setError] = useState("");
  const [message, setMessage] = useState("");

  useEffect(() => {
    const loadSummary = async () => {
      if (!token) return;
      setLoading(true);
      setError("");
      setMessage("");

      try {
        const response = await getInviteLinkSummary(token);
        setLink(response.data.link);
      } catch (err) {
        setError(err.response?.data?.error?.message || "Invite link not found");
      } finally {
        setLoading(false);
      }
    };

    loadSummary();
  }, [token]);

  const blockedCode = useMemo(() => {
    if (!link) return null;
    if (link.viewerStatus === "ALREADY_MEMBER") return "ALREADY_MEMBER";
    if (link.viewerStatus === "PENDING") return "PENDING";
    if (link.status === "REVOKED") return "REVOKED";
    if (link.status === "EXPIRED") return "EXPIRED";
    if (link.status === "USED") return "USED";
    if (link.active_policy === "NOT_ACCEPTING") return "NOT_ACCEPTING";
    return null;
  }, [link]);

  const handleJoin = async () => {
    if (!token) return;
    setJoining(true);
    setError("");
    setMessage("");

    try {
      const response = await acceptInviteLink(token);
      const result = response.data.result;
      if (result.status === "JOINED") {
        setMessage(`Joined ${result.group.name}. Redirecting...`);
        toast.success("Joined group", `Joined group ${result.group.name}`);
      } else if (result.status === "PENDING") {
        setMessage(`Request sent to join ${result.group.name}. Redirecting...`);
        toast.info("Join request sent", `Request sent for ${result.group.name}`);
      } else {
        setMessage(`You are already a member of ${result.group.name}. Redirecting...`);
        toast.info("Already a member", `Already a member of ${result.group.name}`);
      }

      await refreshHouseholds();
      window.setTimeout(() => navigate("/"), 1200);
    } catch (err) {
      const message = getApiErrorMessage(err, "Failed to process invite");
      setError(message);
      toast.error("Join invite failed", `Join invite failed: ${message}`);
    } finally {
      setJoining(false);
    }
  };

  if (loading) {
    return (
      <div className="invite-link-page">
        <div className="invite-card">
          <h1>Invite Link</h1>
          <p>Loading invite details...</p>
        </div>
      </div>
    );
  }

  if (error || !link) {
    return (
      <div className="invite-link-page">
        <div className="invite-card">
          <h1>Invite Link</h1>
          <p className="invite-error">{error || "Invite link not found"}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="invite-link-page">
      <div className="invite-card">
        <h1>Join {link.group_name}</h1>
        <p className="invite-meta">Invite status: {link.status}</p>

        {message && <p className="invite-success">{message}</p>}
        {!message && blockedCode && <p className="invite-error">{humanizeStatus(blockedCode)}</p>}
        {!message && !blockedCode && !authToken && (
          <p className="invite-meta">Sign in or register to join this group.</p>
        )}

        {!message && !authToken && (
          <div className="invite-actions">
            <Link className="invite-btn" to={`/login?next=/invite/${link.token}`}>
              Sign In
            </Link>
            <Link className="invite-btn invite-btn-secondary" to={`/register?next=/invite/${link.token}`}>
              Register
            </Link>
          </div>
        )}

        {!message && authToken && !blockedCode && (
          <div className="invite-actions">
            <button className="invite-btn" onClick={handleJoin} disabled={joining}>
              {joining ? "Joining..." : "Join Group"}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
