'use client';

import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { useToast } from '@/components/ui/ToastContext';

interface UseRoleProtectionOptions {
  requiredRole?: 'CLIENT' | 'FREELANCER' | 'ADMIN';
  redirectTo?: string;
  showErrorMessage?: boolean;
}

interface UseRoleProtectionReturn {
  isLoading: boolean;
  isAuthorized: boolean;
  user: any;
  userRole: string | null;
}

export function useRoleProtection(
  locale: string,
  options: UseRoleProtectionOptions = {}
): UseRoleProtectionReturn {
  const { data: session, status } = useSession();
  const router = useRouter();
  const { showError } = useToast();
  const [isLoading, setIsLoading] = useState(true);
  const [isAuthorized, setIsAuthorized] = useState(false);

  const {
    requiredRole,
    redirectTo,
    showErrorMessage = true
  } = options;

  useEffect(() => {
    if (status === 'loading') return;

    // Check authentication
    if (!session?.user) {
      if (showErrorMessage) {
        showError('Please login to access this page', 'Access Denied');
      }
      router.push(`/${locale}/login`);
      return;
    }
    debugger
console.log("session.user ==", session.user)
    const userRole = (session.user as any).role;

    // Check role authorization if required
    if (requiredRole && userRole !== requiredRole) {
      if (showErrorMessage) {
        const roleName = requiredRole.toLowerCase();
        showError(`This page is only accessible to ${roleName}s`, 'Access Denied');
      }

      // Determine redirect URL
      let redirectUrl = redirectTo;
      if (!redirectUrl) {
        switch (userRole) {
          case 'CLIENT':
            redirectUrl = `/${locale}/client/my-projects`;
            break;
          case 'FREELANCER':
            redirectUrl = `/${locale}/freelancer/my-projects`;
            break;
          case 'ADMIN':
            redirectUrl = `/${locale}/admin/dashboard`;
            break;
          default:
            redirectUrl = `/${locale}`;
            break;
        }
      }

      router.push(redirectUrl);
      return;
    }

    setIsAuthorized(true);
    setIsLoading(false);
  }, [session, status, router, locale, requiredRole, redirectTo, showError, showErrorMessage]);

  return {
    isLoading: status === 'loading' || isLoading,
    isAuthorized,
    user: session?.user || null,
    userRole: session?.user ? (session.user as any).role : null,
  };
}

// Convenience hooks for specific roles
export function useClientProtection(locale: string) {
  return useRoleProtection(locale, { requiredRole: 'CLIENT' });
}

export function useFreelancerProtection(locale: string) {
  return useRoleProtection(locale, { requiredRole: 'FREELANCER' });
}

export function useAdminProtection(locale: string) {
  return useRoleProtection(locale, { requiredRole: 'ADMIN' });
}

// Hook for checking if user has any of multiple roles
export function useMultiRoleProtection(
  locale: string, 
  allowedRoles: Array<'CLIENT' | 'FREELANCER' | 'ADMIN'>
) {
  const { data: session, status } = useSession();
  const router = useRouter();
  const { showError } = useToast();
  const [isLoading, setIsLoading] = useState(true);
  const [isAuthorized, setIsAuthorized] = useState(false);

  useEffect(() => {
    if (status === 'loading') return;

    if (!session?.user) {
      showError('Please login to access this page', 'Access Denied');
      router.push(`/${locale}/login`);
      return;
    }

    const userRole = (session.user as any).role;

    if (!allowedRoles.includes(userRole)) {
      showError('You do not have permission to access this page', 'Access Denied');
      
      // Redirect to appropriate dashboard
      switch (userRole) {
        case 'CLIENT':
          router.push(`/${locale}/client/my-projects`);
          break;
        case 'FREELANCER':
          router.push(`/${locale}/freelancer/my-projects`);
          break;
        case 'ADMIN':
          router.push(`/${locale}/admin/dashboard`);
          break;
        default:
          router.push(`/${locale}`);
          break;
      }
      return;
    }

    setIsAuthorized(true);
    setIsLoading(false);
  }, [session, status, router, locale, allowedRoles, showError]);

  return {
    isLoading: status === 'loading' || isLoading,
    isAuthorized,
    user: session?.user || null,
    userRole: session?.user ? (session.user as any).role : null,
  };
}