import { useState, useEffect, useMemo } from 'react';

/**
 * Roles that have full access to all work orders
 * Users with ONLY "Technician" role (and none of these) will have restricted view
 */
const FULL_ACCESS_ROLES = [
  'System Manager',
  'Administrator',
  'Contractor Supervisor', 
  'Contractor Manager',
  'Work Control',
  'End user'
];

interface TechnicianFilterResult {
  currentUser: string;
  isTechnicianOnly: boolean;
  technicianOrFilters: any[][] | undefined;
  loading: boolean;
  error: string | null;
}

/**
 * Hook to determine if current user is a Technician-only user
 * and build appropriate OR filters for work order visibility
 * 
 * Logic:
 * - If user has ONLY "Technician" role (no higher roles), they see only:
 *   - Work orders they own (owner = user)
 *   - Work orders assigned to them (assigned_technician = user)
 *   - Work orders where they're in additional technicians (custom_add_technicians contains user)
 * - If user has Technician + any higher role, they see all work orders
 * - If user has only higher roles (no Technician), they see all work orders
 */
export function useTechnicianFilter(): TechnicianFilterResult {
  const [currentUser, setCurrentUser] = useState<string>('');
  const [isTechnicianOnly, setIsTechnicianOnly] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const checkTechnicianRole = async () => {
      try {
        setLoading(true);
        
        // Fetch user info with roles from the API
        const response = await fetch('/api/method/asset_lite.api.user_roles.get_user_info_with_roles', {
          method: 'GET',
          headers: { 'Content-Type': 'application/json' }
        });
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        
        if (data.message) {
          const { user, roles } = data.message;
          setCurrentUser(user || '');
          
          if (!user || user === 'Guest') {
            setIsTechnicianOnly(false);
            return;
          }
          
          // Check if user has Technician role
          const hasTechnician = roles.includes('Technician');
          
          // Check if user has any full access role
          const hasFullAccess = roles.some((r: string) => FULL_ACCESS_ROLES.includes(r));
          
          // User is Technician-only if they have Technician but NO full access roles
          const technicianOnly = hasTechnician && !hasFullAccess;
          
          console.log('[useTechnicianFilter] User:', user);
          console.log('[useTechnicianFilter] Roles:', roles);
          console.log('[useTechnicianFilter] Has Technician:', hasTechnician);
          console.log('[useTechnicianFilter] Has Full Access:', hasFullAccess);
          console.log('[useTechnicianFilter] Is Technician Only:', technicianOnly);
          
          setIsTechnicianOnly(technicianOnly);
        }
        
        setError(null);
      } catch (err) {
        console.error('[useTechnicianFilter] Error checking technician role:', err);
        setError(err instanceof Error ? err.message : 'Failed to check user roles');
        // Default to showing nothing if we can't verify permissions
        setIsTechnicianOnly(false);
      } finally {
        setLoading(false);
      }
    };
    
    checkTechnicianRole();
  }, []);

  /**
   * Build OR filters for Technician-only users
   * These filters ensure technicians only see work orders they're associated with
   * 
   * Frappe or_filters format: [["field", "operator", "value"], ...]
   * Records matching ANY of these conditions will be included
   */
  const technicianOrFilters = useMemo(() => {
    // If not Technician-only or no user, don't apply OR filters
    if (!isTechnicianOnly || !currentUser) {
      return undefined;
    }
    
    console.log('[useTechnicianFilter] Building OR filters for user:', currentUser);
    
    // Return OR filters - user sees work orders where they are:
    // 1. The owner (creator) of the work order
    // 2. The assigned technician
    // 3. Listed in additional technicians field (using LIKE for comma-separated values)
    return [
      ['owner', '=', currentUser],
      ['assigned_technician', '=', currentUser],
      ['custom_add_technicians', 'like', `%${currentUser}%`]
    ];
  }, [isTechnicianOnly, currentUser]);

  return {
    currentUser,
    isTechnicianOnly,
    technicianOrFilters,
    loading,
    error
  };
}

export default useTechnicianFilter;