"use client";

import * as React from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { signOut } from "next-auth/react";
import { clearCachedSession } from "@/api/session-cache";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ShieldOff } from "lucide-react";

function SessionRevokedContent() {
  const searchParams = useSearchParams();
  const reason = searchParams.get("reason") ?? "revoked";

  React.useEffect(() => {
    clearCachedSession();
    void signOut({ redirect: false });
  }, []);

  const copy = (() => {
    if (reason === "expired") {
      return {
        title: "Session expired",
        description:
          "Your sign-in session has ended. Sign in again to continue using the app.",
      };
    }
    if (reason === "invalid") {
      return {
        title: "Session no longer valid",
        description:
          "This session cannot be used anymore. Sign in again to continue.",
      };
    }
    return {
      title: "Session revoked",
      description:
        "Your session was ended by an administrator or another device signed in with your account. Sign in again when you are ready.",
    };
  })();

  return (
    <Card className="w-full max-w-[420px] bg-white/95 backdrop-blur-md border border-white/60 shadow-lg rounded-2xl">
      <CardHeader className="space-y-3 pt-8 text-center">
        <div className="flex justify-center">
          <div className="size-14 rounded-2xl bg-amber-50 flex items-center justify-center border border-amber-100">
            <ShieldOff className="size-7 text-amber-700" />
          </div>
        </div>
        <CardTitle className="text-2xl font-bold font-['Lexend'] text-[#101828]">
          {copy.title}
        </CardTitle>
        <CardDescription className="text-[15px] text-muted-foreground leading-relaxed">
          {copy.description}
        </CardDescription>
      </CardHeader>
      <CardContent className="pb-8 flex flex-col gap-3">
        <Button asChild size="block">
          <Link href="/login">Back to sign in</Link>
        </Button>
      </CardContent>
    </Card>
  );
}

export default function SessionRevokedPage() {
  return (
    <React.Suspense
      fallback={
        <Card className="w-full max-w-[420px] bg-white/95 border border-white/60 rounded-2xl shadow-lg animate-pulse p-8 min-h-[280px]" />
      }
    >
      <SessionRevokedContent />
    </React.Suspense>
  );
}
