from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.db import IntegrityError
from django.http import HttpResponseServerError
from openpyxl import load_workbook

from apps.carers.lib.emails import send_staff_welcome_email
from apps.carers.models import Profile
from apps.orgs.models import Administrator


def check_row_valid(row):
    for item in row:
        if item == '':
            return False
    try:
        validate_email(row[-1])
    except ValidationError as e:
        return False

    return True


def process_excel_file(file, organisation, admins, send_emails=False):
    """
    Process the uploaded Excel file using openpyxl and add users to admins or staff.
    """
    wb = load_workbook(filename=file)
    sheet = wb.active  # Load the first sheet by default

    # Read the header
    headers = [cell.value for cell in sheet[1]]  # Assuming headers are in the first row
    total_rows = 0
    number_added = 0
    # Process rows
    for row in sheet.iter_rows(min_row=2, values_only=True):  # Skip the header
        total_rows += 1
        row_is_valid = check_row_valid(row)
        if row_is_valid:
            row_data = dict(zip(headers, row))
            # Create user
            password = User.objects.make_random_password()
            try:
                user = User.objects.create_user(username=row_data['Email address'], email=row_data['Email address'],
                                            first_name=row_data['First Name'], last_name=row_data['Last Name'],
                                            password=password, is_active=False)

            except IntegrityError as e:
                continue
            if admins:
                # Process as admin, add admin object and add to org as admin
                admin = Administrator.objects.create(user=user)
                organisation.admins.add(admin)
                # Add your logic to associate email with admins here
                number_added += 1
            else:
                # Process as staff, create profile and add to org as staff
                if hasattr(user, 'profile'):
                    profile = user.profile
                    organisation.staff.add(profile)
                    number_added += 1
                    if send_emails:
                        send_staff_welcome_email(user, organisation)
                        profile.sent_welcome_email = True
                        profile.save()
                else:
                    return HttpResponseServerError(f"Something went wrong.")



    return number_added, total_rows
