import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { AdminService } from '../../services/admin.service';
import { AuthService } from '../../services/auth.service';
import { AppointmentService, Appointment } from '../../services/appointment.service';
import { UserService, UserInfo, UserUpdateRequest } from '../../services/user.service';
import { HipaaAuditService, HipaaAuditLog, PhiAccessLog, BreachNotification } from '../../services/hipaa-audit.service';
import { ModalService } from '../../services/modal.service';
import { LoggerService } from '../../services/logger.service';

@Component({
  selector: 'app-admin',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './admin.component.html',
  styleUrl: './admin.component.scss'
})
export class AdminComponent implements OnInit {
  stats: any = null;
  metrics: any = null;
  users: any[] = [];
  doctors: any[] = [];
  patients: any[] = [];
  appointments: Appointment[] = [];
  loading = false;
  error: string | null = null;
  activeTab: string = 'overview';
  currentUser: UserInfo | null = null;
  showEditProfile = false;
  editUserData: UserUpdateRequest = {
    firstName: '',
    lastName: '',
    phoneNumber: ''
  };

  // HIPAA Audit data
  selectedPatientIdForAudit: string | null = null;
  selectedUserIdForAudit: string | null = null;
  hipaaAuditLogs: HipaaAuditLog[] = [];
  phiAccessLogs: PhiAccessLog[] = [];
  breachNotifications: BreachNotification[] = [];
  showCreateBreachNotification = false;
  newBreachNotification = {
    breachType: 'UNAUTHORIZED_ACCESS' as 'UNAUTHORIZED_ACCESS' | 'DISCLOSURE' | 'LOSS' | 'THEFT',
    description: '',
    affectedPatientsCount: 0,
    mitigationSteps: '',
    incidentDate: new Date().toISOString().split('T')[0], // Today's date in YYYY-MM-DD format
    discoveryDate: new Date().toISOString().split('T')[0] // Today's date in YYYY-MM-DD format
  };

  constructor(
    private admin: AdminService, 
    private auth: AuthService, 
    private router: Router,
    private appointmentService: AppointmentService,
    private userService: UserService,
    private hipaaAuditService: HipaaAuditService,
    private modalService: ModalService,
    private logger: LoggerService
  ) {}

  ngOnInit() {
    this.refresh();
  }

  hasObjectKeys(obj: any): boolean {
    return obj && typeof obj === 'object' && Object.keys(obj).length > 0;
  }

  async refresh() {
    this.loading = true;
    this.error = null;
    try {
      this.currentUser = await this.userService.getCurrentUserProfile();
      const [stats, metrics, users, doctors, patients] = await Promise.all([
        this.admin.getStats(),
        this.admin.getMetrics(),
        this.admin.getUsers(),
        this.admin.getDoctors(),
        this.admin.getPatients()
      ]);
      
      this.stats = stats;
      this.metrics = metrics;
      this.users = users;
      this.doctors = doctors;
      this.patients = patients;
      if (this.activeTab === 'appointments') {
        await this.loadAppointments();
      }
      if (this.activeTab === 'hipaa-audit') {
        await this.loadBreachNotifications();
      }
    } catch (e: any) {
      if (e?.response?.status === 401) {
        await this.auth.logout();
        this.router.navigateByUrl('/login');
        return;
      }
      this.error = e?.response?.data?.message || 'Failed to load admin data';
    } finally {
      this.loading = false;
    }
  }

  async toggleUserStatus(user: any) {
    try {
      if (user.isActive) {
        await this.admin.deactivateUser(user.email);
      } else {
        await this.admin.activateUser(user.email);
      }
      await this.refresh();
    } catch (e: any) {
      this.error = e?.response?.data?.message || 'Failed to update user status';
    }
  }

  async deleteUser(user: any) {
    const confirmed = await this.modalService.confirm(
      `Are you sure you want to delete user ${user.email}? This action cannot be undone.`,
      'Delete User',
      'Delete',
      'Cancel'
    );
    if (!confirmed) {
      return;
    }
    
    try {
      await this.admin.deleteUser(user.email);
      await this.refresh();
    } catch (e: any) {
      this.error = e?.response?.data?.message || 'Failed to delete user';
    }
  }

  async verifyDoctor(doctor: any) {
    if (!doctor.medicalLicenseNumber) {
      this.error = 'Medical license number not available for this doctor';
      return;
    }

    const confirmed = await this.modalService.confirm(
      `Are you sure you want to verify Dr. ${doctor.firstName} ${doctor.lastName}?\n\nMedical License: ${doctor.medicalLicenseNumber}`,
      'Verify Doctor',
      'Verify',
      'Cancel'
    );
    if (!confirmed) return;

    try {
      await this.admin.verifyDoctor(doctor.medicalLicenseNumber);
      await this.refresh();
      this.error = null;
    } catch (e: any) {
      this.error = e?.response?.data?.message || 'Failed to verify doctor';
    }
  }

  async unverifyDoctor(doctor: any) {
    if (!doctor.medicalLicenseNumber) {
      this.error = 'Medical license number not available for this doctor';
      return;
    }

    const confirmed = await this.modalService.confirm(
      `Are you sure you want to unverify Dr. ${doctor.firstName} ${doctor.lastName}?\n\nMedical License: ${doctor.medicalLicenseNumber}\n\nThis will remove the verified status from this doctor.`,
      'Unverify Doctor',
      'Unverify',
      'Cancel'
    );
    if (!confirmed) return;

    try {
      await this.admin.unverifyDoctor(doctor.medicalLicenseNumber);
      await this.refresh();
      this.error = null;
    } catch (e: any) {
      this.error = e?.response?.data?.message || 'Failed to unverify doctor';
    }
  }

  async deleteAppointment(appointment: Appointment) {
    if (!appointment.id) {
      this.error = 'Appointment ID not available';
      return;
    }
    const confirmed = await this.modalService.confirm(
      'Are you sure you want to delete this appointment? This action cannot be undone.',
      'Delete Appointment',
      'Delete',
      'Cancel'
    );
    if (!confirmed) {
      return;
    }
    
    try {
      await this.admin.deleteAppointment(appointment.id);
      await this.loadAppointments();
    } catch (e: any) {
      this.error = e?.response?.data?.message || 'Failed to delete appointment';
    }
  }

  async loadAppointments() {
    try {
      this.appointments = await this.admin.getAllAppointments();
    } catch (e: any) {
      this.logger.error('Failed to load appointments:', e);
      this.appointments = [];
    }
  }

  setTab(tab: string) {
    this.activeTab = tab;
  }

  async logout() {
    await this.auth.logout();
    this.router.navigateByUrl('/login');
  }

  formatDate(dateString: string): string {
    if (!dateString) return 'N/A';
    const date = new Date(dateString);
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  }

  async updateUserProfile() {
    try {
      await this.userService.updateUserProfile(this.editUserData);
      await this.refresh();
      this.showEditProfile = false;
    } catch (e: any) {
      this.error = e?.response?.data?.message || 'Failed to update profile';
    }
  }

  editProfile() {
    // Ensure currentUser is loaded
    if (!this.currentUser) {
      this.logger.error('Current user not loaded');
      return;
    }
    this.editUserData = {
      firstName: this.currentUser.firstName || '',
      lastName: this.currentUser.lastName || '',
      phoneNumber: this.currentUser.phoneNumber || ''
    };
    this.showEditProfile = true;
  }

  // HIPAA Audit methods
  async loadHipaaAuditLogsByPatient(patientId: string) {
    try {
      this.hipaaAuditLogs = await this.hipaaAuditService.getHipaaAuditLogsByPatientId(patientId);
      this.selectedPatientIdForAudit = patientId;
    } catch (e: any) {
      this.logger.error('Error loading HIPAA audit logs:', e);
      this.hipaaAuditLogs = [];
    }
  }

  async loadHipaaAuditLogsByUser(userId: string) {
    try {
      this.hipaaAuditLogs = await this.hipaaAuditService.getHipaaAuditLogsByUserId(userId);
      this.selectedUserIdForAudit = userId;
    } catch (e: any) {
      this.logger.error('Error loading HIPAA audit logs:', e);
      this.hipaaAuditLogs = [];
    }
  }

  async loadPhiAccessLogsByPatient(patientId: string) {
    try {
      this.phiAccessLogs = await this.hipaaAuditService.getPhiAccessLogsByPatientId(patientId);
      this.selectedPatientIdForAudit = patientId;
    } catch (e: any) {
      this.logger.error('Error loading PHI access logs:', e);
      this.phiAccessLogs = [];
    }
  }

  async loadBreachNotifications() {
    try {
      this.breachNotifications = await this.hipaaAuditService.getBreachNotifications();
    } catch (e: any) {
      this.logger.error('Error loading breach notifications:', e);
      this.breachNotifications = [];
    }
  }

  async createBreachNotification() {
    // Ensure dates are set
    if (!this.newBreachNotification.incidentDate) {
      this.newBreachNotification.incidentDate = new Date().toISOString().split('T')[0];
    }
    if (!this.newBreachNotification.discoveryDate) {
      this.newBreachNotification.discoveryDate = new Date().toISOString().split('T')[0];
    }
    
    if (!this.newBreachNotification.description || !this.newBreachNotification.mitigationSteps || 
        !this.newBreachNotification.incidentDate || !this.newBreachNotification.discoveryDate) {
      this.error = 'Please fill in all required fields';
      return;
    }
    
    this.logger.debug('Creating breach notification with data:', this.newBreachNotification);
    
    try {
      await this.hipaaAuditService.createBreachNotification(this.newBreachNotification);
      this.showCreateBreachNotification = false;
      this.newBreachNotification = {
        breachType: 'UNAUTHORIZED_ACCESS',
        description: '',
        affectedPatientsCount: 0,
        mitigationSteps: '',
        incidentDate: new Date().toISOString().split('T')[0],
        discoveryDate: new Date().toISOString().split('T')[0]
      };
      await this.loadBreachNotifications();
    } catch (e: any) {
      this.logger.error('Error creating breach notification:', e);
      if (e?.response?.status === 401 || e?.message?.includes('Authentication required')) {
        // Check if token exists
        const token = localStorage.getItem('jwtToken');
        if (!token || token === 'null' || token === 'undefined') {
          this.error = 'You are not logged in. Please log in to continue.';
          setTimeout(() => {
            this.auth.logout();
            this.router.navigate(['/login']);
          }, 2000);
        } else {
          // Token exists but is invalid/expired - give user option to retry or login
          this.error = 'Your session may have expired. Please try refreshing the page or logging in again.';
          // Don't auto-logout - let user decide
        }
      } else {
        this.error = e?.response?.data?.error || e?.response?.data?.message || e?.message || 'Failed to create breach notification';
      }
    }
  }
}
