'use client';

import { useEffect, useState, createContext, useContext, ReactNode } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/store/useAuthStore';
import { api } from '@/lib/api';

interface AdminContextType {
  isAdmin: boolean;
  isLoading: boolean;
}

const AdminContext = createContext<AdminContextType>({
  isAdmin: false,
  isLoading: true,
});

export function useAdmin() {
  return useContext(AdminContext);
}

interface AdminGuardProps {
  children: ReactNode;
}

export function AdminGuard({ children }: AdminGuardProps) {
  const router = useRouter();
  const { isAuthenticated, token } = useAuthStore();
  const [isAdmin, setIsAdmin] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const checkAdmin = async () => {
      if (!isAuthenticated || !token) {
        router.push('/login');
        return;
      }

      try {
        // Get user profile to check if admin
        const user = await api.get<{
          id: string;
          email: string;
          username: string;
          role?: string;
          createdAt: string;
          lastLoginAt: string;
        }>('/api/auth/me');

        // Check if user is admin by role or by email
        const adminEmailsStr = (process.env as Record<string, string | undefined>)['NEXT_PUBLIC_ADMIN_EMAILS'] ?? '';        const adminEmails = adminEmailsStr ? adminEmailsStr.split(',').map(e => e.trim()) : [];
        const isAdminByEmail = adminEmails.includes(user.email);
        const isAdminByRole = user.role === 'ADMIN';

        if (!isAdminByEmail && !isAdminByRole) {
          router.push('/dashboard');
          return;
        }

        setIsAdmin(true);
      } catch (error) {
        router.push('/dashboard');
      } finally {
        setIsLoading(false);
      }
    };

    void checkAdmin();
  }, [isAuthenticated, token, router]);

  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
          <p className="text-sm text-muted-foreground">Verificando permisos...</p>
        </div>
      </div>
    );
  }

  if (!isAdmin) {
    return null;
  }

  return (
    <AdminContext.Provider value={{ isAdmin, isLoading }}>
      {children}
    </AdminContext.Provider>
  );
}