import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { GdprService, ConsentType } from '../../services/gdpr.service';
import { AuthService } from '../../services/auth.service';
import { LoggerService } from '../../services/logger.service';

@Component({
  selector: 'app-gdpr-consent-banner',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './gdpr-consent-banner.component.html',
  styleUrl: './gdpr-consent-banner.component.scss'
})
export class GdprConsentBannerComponent implements OnInit, OnDestroy {
  showBanner = false;
  isLoading = false;
  showDetails = false;
  
  consents = {
    privacyPolicy: true, // Required
    cookies: false,
    dataProcessing: true, // Required
    analytics: false,
    marketing: false
  };

  constructor(
    private gdprService: GdprService,
    private authService: AuthService,
    private logger: LoggerService
  ) {}

  ngOnInit() {
    this.checkConsentStatus();
  }

  ngOnDestroy() {
    // Cleanup if needed
  }

  async checkConsentStatus() {
    const isAuthenticated = this.authService.isAuthenticated();
    if (!isAuthenticated) {
      // For unauthenticated users, check if banner was shown
      this.showBanner = this.gdprService.shouldShowConsentBanner();
      return;
    }

    try {
      const hasRequiredConsents = await this.gdprService.hasRequiredConsents();
      if (!hasRequiredConsents) {
        this.showBanner = true;
      }
    } catch (error) {
      this.logger.error('Error checking consent status:', error);
      // Show banner if there's an error
      this.showBanner = true;
    }
  }

  async acceptAll() {
    this.isLoading = true;
    try {
      const isAuthenticated = this.authService.isAuthenticated();
      
      if (isAuthenticated) {
        // Grant all consents
        await Promise.all([
          this.gdprService.grantConsent(ConsentType.PRIVACY_POLICY, '1.0'),
          this.gdprService.grantConsent(ConsentType.COOKIES, '1.0'),
          this.gdprService.grantConsent(ConsentType.DATA_PROCESSING, '1.0'),
          this.gdprService.grantConsent(ConsentType.ANALYTICS, '1.0'),
          this.gdprService.grantConsent(ConsentType.MARKETING, '1.0')
        ]);
      }
      
      // Mark banner as shown
      this.gdprService.markConsentBannerShown();
      this.showBanner = false;
    } catch (error) {
      this.logger.error('Error accepting consents:', error);
      alert('Error accepting consents. Please try again.');
    } finally {
      this.isLoading = false;
    }
  }

  async acceptSelected() {
    this.isLoading = true;
    try {
      const isAuthenticated = this.authService.isAuthenticated();
      
      if (isAuthenticated) {
        const promises: Promise<any>[] = [];
        
        if (this.consents.privacyPolicy) {
          promises.push(this.gdprService.grantConsent(ConsentType.PRIVACY_POLICY, '1.0'));
        }
        if (this.consents.cookies) {
          promises.push(this.gdprService.grantConsent(ConsentType.COOKIES, '1.0'));
        }
        if (this.consents.dataProcessing) {
          promises.push(this.gdprService.grantConsent(ConsentType.DATA_PROCESSING, '1.0'));
        }
        if (this.consents.analytics) {
          promises.push(this.gdprService.grantConsent(ConsentType.ANALYTICS, '1.0'));
        }
        if (this.consents.marketing) {
          promises.push(this.gdprService.grantConsent(ConsentType.MARKETING, '1.0'));
        }
        
        await Promise.all(promises);
      }
      
      // Mark banner as shown
      this.gdprService.markConsentBannerShown();
      this.showBanner = false;
    } catch (error) {
      this.logger.error('Error accepting selected consents:', error);
      alert('Error accepting consents. Please try again.');
    } finally {
      this.isLoading = false;
    }
  }

  rejectAll() {
    // Mark banner as shown even if rejecting
    this.gdprService.markConsentBannerShown();
    this.showBanner = false;
  }

  toggleDetails() {
    this.showDetails = !this.showDetails;
    // Optionally navigate to privacy policy page
    // window.location.href = '/privacy-policy';
  }
}

