"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { XCircle, LogOut, Mail } from "lucide-react";
import { LogoIcon } from "@/components/ui/logo";
import { Button } from "@/components/ui/button";
import { useUserStore } from "@/store";
import { getAuthToken } from "@/lib/utils";

export default function DeniedPage() {
  const router = useRouter();
  const { email, displayName, clearUser } = useUserStore();
  const [authorized, setAuthorized] = useState(false);

  useEffect(() => {
    const token = getAuthToken();
    if (!token) { router.replace("/login"); return; }

    // Call /me once on every load/refresh to get latest approval_status
    const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "";
    fetch(`${BASE_URL}/me`, {
      headers: {
        "Content-Type": "application/json",
        "ngrok-skip-browser-warning": "true",
        Authorization: `Bearer ${token}`,
      },
    })
      .then((res) => res.json())
      .then((data) => {
        if (data.success && data.data) {
          const { name, role, approval_status } = data.data;
          const { email } = useUserStore.getState();
          useUserStore.getState().setMe({ email, name, role, approval_status });

          if (approval_status === "approved") { router.replace("/dashboard"); return; }
          if (approval_status === "pending")  { router.replace("/pending-approval"); return; }
        }
        setAuthorized(true);
      })
      .catch(() => setAuthorized(true)); // /me failed - show page anyway
  }, [router]);

  if (!authorized) return null;

  const handleSignOut = () => {
    clearUser();
    sessionStorage.removeItem("auth_token");
    sessionStorage.removeItem("auth_email");
    document.cookie = "auth_token=; path=/; max-age=0";
    router.push("/login");
  };

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-950 flex items-center justify-center p-4">
      <div className="w-full max-w-md">

        {/* Card */}
        <div className="bg-white dark:bg-gray-900 rounded-2xl border border-gray-200 dark:border-gray-800 shadow-sm p-8 text-center space-y-6">

          {/* Logo */}
          <div className="flex justify-center">
            <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-blue-600">
              <LogoIcon size={32} />
            </div>
          </div>

          {/* Icon */}
          <div className="flex justify-center">
            <div className="flex h-16 w-16 items-center justify-center rounded-full bg-red-50 dark:bg-red-950/40 border-2 border-red-200 dark:border-red-800">
              <XCircle className="h-7 w-7 text-red-500" />
            </div>
          </div>

          {/* Text */}
          <div className="space-y-2">
            <h1 className="text-xl font-bold text-gray-900 dark:text-gray-100">
              Access Denied
            </h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 leading-relaxed">
              Your request to access IIH Notetaker has been denied. If you believe this is a mistake, please contact your administrator.
            </p>
          </div>

          {/* User info */}
          {email && (
            <div className="flex items-center gap-2.5 rounded-xl border border-red-100 dark:border-red-900 bg-red-50 dark:bg-red-950/30 px-4 py-3">
              <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/50">
                <Mail className="h-4 w-4 text-red-600 dark:text-red-400" />
              </div>
              <div className="text-left min-w-0">
                <p className="text-xs font-medium text-gray-900 dark:text-gray-100 truncate">
                  {displayName || email}
                </p>
                <p className="text-xs text-gray-500 dark:text-gray-400 truncate">{email}</p>
              </div>
            </div>
          )}

          {/* Info box */}
          <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800 px-4 py-3 text-left">
            <p className="text-xs text-gray-600 dark:text-gray-400 leading-5">
              This decision was made by an administrator. To request a review, reach out to your organization&apos;s admin or contact support directly.
            </p>
          </div>

          {/* Sign out */}
          <Button
            variant="outline"
            className="w-full gap-2 border-red-200 dark:border-red-900 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/30"
            onClick={handleSignOut}
          >
            <LogOut className="h-4 w-4" />
            Sign out
          </Button>
        </div>

        <p className="text-center text-xs text-gray-400 dark:text-gray-600 mt-4">
          IIH Notetaker · Secure meeting transcription
        </p>
      </div>
    </div>
  );
}
