from django.contrib import messages
from django.utils import timezone
from ..models import PlayerRegistration, UnregisteredTeam, UnregisteredPlayer, PlayerPaymentType
from ..services.payment_service import PaymentService
from ..services.email_service import TournamentEmailService, TeamEmailType

class TournamentUnregistrationService:
    def __init__(self, request, tournament):
        self.request = request
        self.tournament = tournament
        self.player_registration = None
        self.other_player = None
        self.team_registration = None

    def can_unregister(self):
        if not self.tournament.is_unregistration_possible():
            messages.error(self.request, "Le désistement n'est plus possible pour ce tournoi. Si vous souhaitez vous désinscrire, veuillez contacter le juge-arbitre.")
            return False

        # if not self.request.user.licence_id:
        #     messages.error(self.request,
        #         "Vous ne pouvez pas vous désinscrire car vous n'avez pas de numéro de licence associé.")
        #     return False

        return True

    def process_unregistration(self):
        if not self._find_player_registration():
            messages.error(self.request,
                "La désincription a échouée. Veuillez contacter le juge-arbitre.")
            return False

        # Check if refund is possible and needed
        if self.tournament.is_refund_possible() and self._team_has_paid():
            refund_processed, message, refund_details = self._process_refund()
            if refund_processed:
                # Refund successful, continue with unregistration process
                messages.success(self.request, message)
            else:
                # Refund failed, show error but continue with normal unregistration
                messages.error(self.request, message)

        # Proceed with unregistration
        self._unregister_team()
        self._delete_registered_team()
        self._cleanup_session()

        messages.success(self.request, "Votre désinscription a été effectuée.")

        return True

    def _team_has_paid(self):
        """Check if team has paid for registration"""
        if not self.team_registration:
            print("Team registration not found")
            return False

        # Check if any player registration has a payment ID
        player_registrations = PlayerRegistration.objects.filter(team_registration=self.team_registration)
        for player_reg in player_registrations:
            if player_reg.payment_id and player_reg.payment_type == PlayerPaymentType.CREDIT_CARD:
                print("Player has paid")
                return True

        print("No player has paid")
        return False

    def _process_refund(self):
        """Process refund for paid registration"""
        try:
            payment_service = PaymentService(self.request)
            return payment_service.process_refund(self.team_registration.id)
        except Exception as e:
            return False, f"Erreur lors du remboursement: {str(e)}", None

    def _unregister_team(self):
        # Create unregistered team record
        team_registration = self.player_registration.team_registration

        unregistered_team = UnregisteredTeam.objects.create(
            tournament=team_registration.tournament,
            user=team_registration.user,
            unregistration_date=timezone.now(),
        )

        for player in team_registration.players_sorted_by_rank:
            UnregisteredPlayer.objects.create(
                unregistered_team=unregistered_team,
                user=player.user,
                first_name=player.first_name,
                last_name=player.last_name,
                licence_id=player.licence_id,
                payment_type=player.payment_type,
                payment_id=player.payment_id,
                registered_online=player.registered_online
            )

        TournamentEmailService.notify_umpire(team_registration, team_registration.tournament, TeamEmailType.UNREGISTERED)

    def _find_player_registration(self):
        # First check if we can find the player registration directly by user
        if self.request.user.is_authenticated:
            self.player_registration = self.tournament.get_user_registered(self.request.user)

            if self.player_registration:
                self.team_registration = self.player_registration.team_registration
                self.other_player = self.team_registration.get_other_player(self.player_registration)
                return True
        return False

    def _delete_registered_team(self):
        team_registration = self.player_registration.team_registration
        team_registration.delete()

    def _cleanup_session(self):
        self.request.session['team_registration'] = []
        self.request.session.modified = True
