import { supabase } from './supabase';
import type { TerritoryManager, TerritoryManagerProfile } from './territory-manager-types';

export class TerritoryManagerAuth {
  
  // Check if current user is a territory manager
  static async isTerritoryManager(): Promise<boolean> {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return false;

      const { data: territoryManager } = await supabase
        .from('territory_managers')
        .select('id')
        .eq('user_id', user.id)
        .single();

      return !!territoryManager;
    } catch (error) {

      return false;
    }
  }

  // Get current territory manager data
  static async getCurrentTerritoryManager(): Promise<TerritoryManager | null> {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return null;

      const { data: territoryManager } = await supabase
        .from('territory_managers')
        .select('*')
        .eq('user_id', user.id)
        .single();

      return territoryManager;
    } catch (error) {

      return null;
    }
  }

  // Sign in territory manager
  static async signIn(email: string, password: string) {
    try {
      const { data, error } = await supabase.auth.signInWithPassword({
        email,
        password
      });

      if (error) throw error;

      // Check if user is a territory manager
      const isTM = await this.isTerritoryManager();
      if (!isTM) {
        await supabase.auth.signOut();
        throw new Error('Access denied: Not a territory manager');
      }

      return data;
    } catch (error) {

      throw error;
    }
  }

  // Sign out
  static async signOut() {
    try {
      const { error } = await supabase.auth.signOut();
      if (error) throw error;
    } catch (error) {

      throw error;
    }
  }

  // Request password reset
  static async requestPasswordReset(email: string) {
    try {
      const { error } = await supabase.auth.resetPasswordForEmail(email, {
        redirectTo: `${window.location.origin}/territory-manager/reset-password`
      });
      
      if (error) throw error;
    } catch (error) {

      throw error;
    }
  }

  // Update password
  static async updatePassword(password: string) {
    try {
      const { error } = await supabase.auth.updateUser({
        password
      });
      
      if (error) throw error;
    } catch (error) {

      throw error;
    }
  }

  // Update profile
  static async updateProfile(profile: Partial<TerritoryManagerProfile>) {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) throw new Error('User not authenticated');

      // Update user metadata
      const { error: authError } = await supabase.auth.updateUser({
        data: {
          full_name: profile.full_name
        }
      });

      if (authError) throw authError;

      // Update territory manager profile
      const { error: profileError } = await supabase
        .from('territory_managers')
        .update({ profile })
        .eq('user_id', user.id);

      if (profileError) throw profileError;
    } catch (error) {

      throw error;
    }
  }

  // Create invitation for new territory manager
  static async createInvitation(email: string, territoryId?: string) {
    try {
      // Generate temporary password
      const tempPassword = Math.random().toString(36).slice(-8) + Math.random().toString(36).slice(-8);
      
      // Create Supabase Auth user
      const { data: authUser, error: authError } = await supabase.auth.admin.createUser({
        email,
        password: tempPassword,
        email_confirm: true,
        user_metadata: {
          role: 'territory_manager',
          must_change_password: true
        }
      });

      if (authError) throw authError;

      // Create territory manager record
      const { error: tmError } = await supabase
        .from('territory_managers')
        .insert({
          user_id: authUser.user.id,
          territory_id: territoryId,
          status: 'pending',
          profile: {
            full_name: email.split('@')[0] // Default name from email
          }
        });

      if (tmError) throw tmError;

      // Send invitation email with temporary password
      await this.sendInvitationEmail(email, tempPassword);

      return { success: true, userId: authUser.user.id };
    } catch (error) {

      throw error;
    }
  }

  // Send invitation email
  private static async sendInvitationEmail(email: string, tempPassword: string) {
    // TODO: Implement email sending logic

    // Email would include:
    // - Welcome message
    // - Temporary password
    // - Link to change password
    // - Instructions for getting started
  }

  // Check if user needs to change password
  static async mustChangePassword(): Promise<boolean> {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return false;

      return user.user_metadata?.must_change_password === true;
    } catch (error) {

      return false;
    }
  }

  // Mark password as changed
  static async markPasswordChanged() {
    try {
      const { error } = await supabase.auth.updateUser({
        data: {
          must_change_password: false
        }
      });
      
      if (error) throw error;
    } catch (error) {

      throw error;
    }
  }

  // Get territory manager permissions
  static async getPermissions(): Promise<string[]> {
    try {
      const territoryManager = await this.getCurrentTerritoryManager();
      if (!territoryManager) return [];

      const basePermissions = [
        'territory_manager.view_dashboard',
        'territory_manager.manage_leads',
        'territory_manager.view_commissions',
        'territory_manager.submit_expenses',
        'territory_manager.generate_referrals'
      ];

      // Add additional permissions based on status
      if (territoryManager.status === 'active') {
        basePermissions.push(
          'territory_manager.access_training',
          'territory_manager.view_marketing_materials'
        );
      }

      return basePermissions;
    } catch (error) {

      return [];
    }
  }

  // Check specific permission
  static async hasPermission(permission: string): Promise<boolean> {
    try {
      const permissions = await this.getPermissions();
      return permissions.includes(permission);
    } catch (error) {

      return false;
    }
  }

  // Listen for auth state changes
  static onAuthStateChange(callback: (event: string, session: any) => void) {
    return supabase.auth.onAuthStateChange(async (event, session) => {
      if (event === 'SIGNED_IN' && session) {
        // Check if user is a territory manager
        const isTM = await this.isTerritoryManager();
        if (!isTM) {
          await supabase.auth.signOut();
          return callback('SIGNED_OUT', null);
        }
      }
      callback(event, session);
    });
  }
}

// Export convenience functions
export const {
  isTerritoryManager,
  getCurrentTerritoryManager,
  signIn,
  signOut,
  requestPasswordReset,
  updatePassword,
  updateProfile,
  mustChangePassword,
  markPasswordChanged,
  getPermissions,
  hasPermission,
  onAuthStateChange
} = TerritoryManagerAuth;