"use client";

import { useEffect, useState, useRef } from "react";
import api from "@/lib/axiosClient";
import { getCookie, useAuth } from "@/contexts/auth-context";
import { ShieldAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
import { decrypt } from "@/lib/encryption";

const IP_RESTRICTED_USER_TYPES = [1]; 

export default function IpGuard({ children }: { children: React.ReactNode }) {
  const [isAllowed, setIsAllowed] = useState<boolean | null>(null);
  const ipCheck = useRef(false);
  const { user, isLoading } = useAuth();

  useEffect(() => {
    if (isLoading) return;
    
    // If not restricted user type or no user, allow
    if (!user || !user.type || !IP_RESTRICTED_USER_TYPES.includes(user.type.id)) {
      setIsAllowed(true);
      return;
    }

    if (ipCheck.current) return;
    ipCheck.current = true;

    const checkIp = async () => {
      try {
        const token = getCookie("__token__");
        if (!token) {
           setIsAllowed(true); 
           return;
        }

        const response = await api.post("/v1.0/setting/service/check-ip", {
          setting: 1
        }, {
          headers: {
            Authorization: `Bearer ${token}`,
            encrypt:'false'
          }
        });

        const allowed = response.data?.allowed !== false;
        setIsAllowed(allowed);
      } catch (error) {
        console.error("IP Check Failed", error);
        setIsAllowed(true); 
      }
    };

    checkIp();
  }, [user, isLoading]);

  if (isAllowed === null || isLoading) {
    return (
      <div className="flex h-screen w-full items-center justify-center bg-[#d1d7db] dark:bg-[#0b141a]">
         <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#00a884]"></div>
      </div>
    );
  }

  if (isAllowed === false) {
    return (
      <div className="flex h-screen w-full flex-col items-center justify-center bg-[#f0f2f5] dark:bg-[#0b141a] px-4 text-center">
        <div className="relative mb-6">
          <div className="absolute -inset-1 rounded-full bg-red-500/20 blur-xl"></div>
          <div className="relative flex h-24 w-24 items-center justify-center rounded-full bg-white dark:bg-[#111b21] shadow-xl">
            <ShieldAlert className="h-12 w-12 text-red-500" />
          </div>
        </div>
        
        <h1 className="mb-2 text-3xl font-bold tracking-tight text-gray-900 dark:text-gray-100 sm:text-4xl">
          Akses Ditolak
        </h1>
        
        <p className="mb-8 max-w-md text-lg text-gray-600 dark:text-gray-400">
          Maaf, alamat IP Anda tidak diizinkan untuk mengakses halaman ini. Silakan hubungi administrator Anda.
        </p>

        <div className="flex flex-col space-y-3 sm:flex-row sm:space-x-4 sm:space-y-0">
          <Button 
            variant="outline" 
            className="flex items-center gap-2 border-gray-300 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800"
            onClick={() => {
              window.location.href = process.env.NEXT_PUBLIC_LOGIN_URL || '';
            }}
          >
            Kembali Ke Dashboard
          </Button>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}
