import { Component, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { PrescriptionService, Prescription, PrescriptionRequest } from '../../../../services/prescription.service';
import { ModalService } from '../../../../services/modal.service';
import { LoggerService } from '../../../../services/logger.service';

@Component({
  selector: 'app-prescriptions',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './prescriptions.component.html',
  styleUrl: './prescriptions.component.scss'
})
export class PrescriptionsComponent implements OnInit, OnChanges {
  @Input() doctorId: string | null = null;
  @Input() selectedPatientId: string | null = null;
  @Input() prescriptions: Prescription[] = [];
  @Input() patients: any[] = [];
  @Output() prescriptionChanged = new EventEmitter<void>();
  @Output() patientSelected = new EventEmitter<string>();
  @Output() safetyCheckRequested = new EventEmitter<void>();

  // Prescription Management State
  allPrescriptions: Prescription[] = [];
  filteredPrescriptions: Prescription[] = [];
  showAllRecords = false;
  selectedPrescription: Prescription | null = null;
  showUpdatePrescription = false;
  showCreatePrescription = false;
  showPrescriptionAnalytics = false;
  showPrescriptionDebug = false;
  
  // Filters and Controls
  prescriptionSearchTerm: string = '';
  prescriptionStatusFilter: string = 'all';
  prescriptionDateFilter: string = 'all';
  prescriptionDateFrom: string = '';
  prescriptionDateTo: string = '';
  prescriptionSortBy: string = 'createdAt';
  prescriptionSortOrder: 'asc' | 'desc' = 'desc';
  prescriptionViewMode: 'card' | 'table' = 'card';
  selectedPrescriptions: string[] = [];
  
  // Form Data
  newPrescription: PrescriptionRequest = {
    patientId: '',
    doctorId: '',
    medicationName: '',
    dosage: '',
    frequency: '',
    quantity: 30,
    refills: 0,
    startDate: new Date().toISOString().split('T')[0]
  };
  
  error: string | null = null;
  loading = false;

  constructor(
    private prescriptionService: PrescriptionService,
    private modalService: ModalService,
    private logger: LoggerService
  ) {}

  ngOnInit() {
    if (this.doctorId) {
      this.newPrescription.doctorId = this.doctorId;
      this.loadAllPrescriptions();
    }
    if (this.selectedPatientId) {
      this.loadPatientPrescriptions();
    }
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['doctorId'] && this.doctorId) {
      this.newPrescription.doctorId = this.doctorId;
      if (!this.allPrescriptions.length) {
        this.loadAllPrescriptions();
      }
    }
    if (changes['selectedPatientId']) {
      if (this.selectedPatientId) {
        this.loadPatientPrescriptions();
      } else {
        this.showAllRecords = true;
        this.applyPrescriptionFilters();
      }
    }
    if (changes['prescriptions']) {
      this.applyPrescriptionFilters();
    }
  }

  async loadAllPrescriptions() {
    if (!this.doctorId) return;
    try {
      this.loading = true;
      this.allPrescriptions = await this.prescriptionService.getPrescriptionsByDoctorId(this.doctorId);
      this.applyPrescriptionFilters();
    } catch (e: any) {
      this.logger.error('Error loading all prescriptions:', e);
      this.error = e?.response?.data?.error || 'Failed to load prescriptions';
      this.allPrescriptions = [];
    } finally {
      this.loading = false;
    }
  }

  async loadPatientPrescriptions() {
    if (!this.selectedPatientId) return;
    try {
      this.loading = true;
      this.prescriptions = await this.prescriptionService.getPrescriptionsByPatientId(this.selectedPatientId);
      this.applyPrescriptionFilters();
    } catch (e: any) {
      this.logger.error('Error loading patient prescriptions:', e);
      this.error = e?.response?.data?.error || 'Failed to load prescriptions';
      this.prescriptions = [];
    } finally {
      this.loading = false;
    }
  }

  async refreshPrescriptions() {
    if (this.showAllRecords) {
      await this.loadAllPrescriptions();
    } else if (this.selectedPatientId) {
      await this.loadPatientPrescriptions();
    }
    this.prescriptionChanged.emit();
  }

  async openCreatePrescription() {
    this.showCreatePrescription = !this.showCreatePrescription;
    if (this.showCreatePrescription) {
      this.newPrescription = {
        patientId: this.selectedPatientId || '',
        doctorId: this.doctorId || '',
        medicationName: '',
        dosage: '',
        frequency: '',
        quantity: 30,
        refills: 0,
        startDate: new Date().toISOString().split('T')[0]
      };
    }
  }

  async createPrescription() {
    // Validation
    const missing: string[] = [];
    if (!this.newPrescription.patientId) missing.push('patient');
    if (!this.newPrescription.doctorId) missing.push('doctor');
    if (!this.newPrescription.medicationName) missing.push('medication');
    if (!this.newPrescription.dosage) missing.push('dosage');
    if (!this.newPrescription.frequency) missing.push('frequency');
    if ((this.newPrescription.quantity as any) == null || (this.newPrescription.quantity as any) <= 0) missing.push('quantity');
    if (!(this.newPrescription.startDate as any)) missing.push('start date');

    if (missing.length > 0) {
      this.error = `Please fill in all required fields (${missing.join(', ')})`;
      // Auto-hide error after 5 seconds
      setTimeout(() => {
        if (this.error?.includes('required fields')) {
          this.error = null;
        }
      }, 5000);
      return;
    }

    try {
      this.loading = true;
      this.error = null;
      await this.prescriptionService.createPrescription(this.newPrescription);
      this.showCreatePrescription = false;
      this.newPrescription = {
        patientId: '',
        doctorId: this.doctorId || '',
        medicationName: '',
        dosage: '',
        frequency: '',
        quantity: 30,
        refills: 0,
        startDate: new Date().toISOString().split('T')[0]
      };
      await this.refreshPrescriptions();
      
      // Request parent component to refresh safety alerts
      this.safetyCheckRequested.emit();
      
      // Show success feedback
      await this.modalService.alert(
        'Prescription created successfully! Safety checks are being performed...',
        'success',
        'Success'
      );
    } catch (e: any) {
      this.logger.error('Error creating prescription:', e);
      const errorMessage = e?.response?.data?.message || 
                          e?.response?.data?.error || 
                          e?.message || 
                          'Failed to create prescription';
      this.error = errorMessage;
      // Auto-hide error after 5 seconds
      setTimeout(() => {
        this.error = null;
      }, 5000);
    } finally {
      this.loading = false;
    }
  }

  editPrescription(prescription: Prescription) {
    this.selectedPrescription = prescription;
    this.newPrescription = {
      patientId: prescription.patientId,
      doctorId: prescription.doctorId,
      medicationName: prescription.medicationName,
      dosage: prescription.dosage,
      frequency: prescription.frequency,
      quantity: prescription.quantity,
      refills: prescription.refills || 0,
      instructions: prescription.instructions,
      startDate: prescription.startDate,
      endDate: prescription.endDate,
      pharmacyName: prescription.pharmacyName,
      pharmacyAddress: prescription.pharmacyAddress,
      pharmacyPhone: prescription.pharmacyPhone
    };
    this.showUpdatePrescription = true;
    (this.newPrescription as any).prescriptionId = prescription.id;
  }

  async updatePrescription() {
    const prescriptionId = (this.newPrescription as any).prescriptionId;
    if (!prescriptionId) {
      this.error = 'Prescription ID is missing. Please try again.';
      return;
    }

    // Validation
    const missing: string[] = [];
    if (!this.newPrescription.patientId) missing.push('patient');
    if (!this.newPrescription.doctorId) missing.push('doctor');
    if (!this.newPrescription.medicationName?.trim()) missing.push('medication name');
    if (!this.newPrescription.dosage?.trim()) missing.push('dosage');
    if (!this.newPrescription.frequency?.trim()) missing.push('frequency');
    if (this.newPrescription.quantity == null || this.newPrescription.quantity <= 0) missing.push('quantity');
    if (!this.newPrescription.startDate) missing.push('start date');

    if (missing.length > 0) {
      this.error = `Please fill in all required fields (${missing.join(', ')})`;
      // Auto-hide error after 5 seconds
      setTimeout(() => {
        if (this.error?.includes('required fields')) {
          this.error = null;
        }
      }, 5000);
      return;
    }

    try {
      this.loading = true;
      this.error = null;
      
      // Create a clean request object without the prescriptionId property
      const updateRequest: PrescriptionRequest = {
        patientId: this.newPrescription.patientId,
        doctorId: this.newPrescription.doctorId,
        medicationName: this.newPrescription.medicationName.trim(),
        dosage: this.newPrescription.dosage.trim(),
        frequency: this.newPrescription.frequency.trim(),
        quantity: this.newPrescription.quantity,
        refills: this.newPrescription.refills || 0,
        instructions: this.newPrescription.instructions?.trim() || undefined,
        startDate: this.newPrescription.startDate,
        endDate: this.newPrescription.endDate || undefined,
        pharmacyName: this.newPrescription.pharmacyName?.trim() || undefined,
        pharmacyAddress: this.newPrescription.pharmacyAddress?.trim() || undefined,
        pharmacyPhone: this.newPrescription.pharmacyPhone?.trim() || undefined,
        appointmentId: this.newPrescription.appointmentId
      };
      
      await this.prescriptionService.updatePrescription(prescriptionId, updateRequest);
      this.showUpdatePrescription = false;
      this.selectedPrescription = null;
      delete (this.newPrescription as any).prescriptionId;
      await this.refreshPrescriptions();
      
      // Request parent component to refresh safety alerts
      this.safetyCheckRequested.emit();
      
      // Show success feedback
      await this.modalService.alert(
        'Prescription updated successfully! Safety checks are being performed...',
        'success',
        'Success'
      );
    } catch (e: any) {
      this.logger.error('Error updating prescription:', e);
      const errorMessage = e?.response?.data?.message || 
                          e?.response?.data?.error || 
                          e?.message || 
                          'Failed to update prescription. Please check your input and try again.';
      this.error = errorMessage;
      // Auto-hide error after 5 seconds
      setTimeout(() => {
        this.error = null;
      }, 5000);
    } finally {
      this.loading = false;
    }
  }

  async deletePrescription(prescriptionId: string) {
    const confirmed = await this.modalService.confirm(
      'Are you sure you want to delete this prescription? This action cannot be undone.',
      'Delete Prescription',
      'Delete',
      'Cancel'
    );
    if (!confirmed) {
      return;
    }
    try {
      this.loading = true;
      this.error = null;
      await this.prescriptionService.deletePrescription(prescriptionId);
      this.selectedPrescriptions = this.selectedPrescriptions.filter(id => id !== prescriptionId);
      await this.refreshPrescriptions();
      // Show success feedback
    } catch (e: any) {
      this.error = e?.response?.data?.error || 'Failed to delete prescription';
      // Auto-hide error after 5 seconds
      setTimeout(() => {
        this.error = null;
      }, 5000);
    } finally {
      this.loading = false;
    }
  }

  async updatePrescriptionStatus(prescriptionId: string, status: 'ACTIVE' | 'COMPLETED' | 'CANCELLED' | 'DISCONTINUED') {
    if (!prescriptionId) {
      this.error = 'Prescription ID is missing. Please try again.';
      return;
    }

    try {
      this.loading = true;
      this.error = null;
      await this.prescriptionService.updatePrescriptionStatus(prescriptionId, status);
      await this.refreshPrescriptions();
    } catch (e: any) {
      this.logger.error('Error updating prescription status:', e);
      const errorMessage = e?.response?.data?.message || 
                          e?.response?.data?.error || 
                          e?.message || 
                          `Failed to update prescription status to ${status}. Please try again.`;
      this.error = errorMessage;
      // Auto-hide error after 5 seconds
      setTimeout(() => {
        this.error = null;
      }, 5000);
    } finally {
      this.loading = false;
    }
  }

  async markEPrescriptionSent(prescriptionId: string) {
    try {
      this.loading = true;
      await this.prescriptionService.markEPrescriptionSent(prescriptionId);
      await this.refreshPrescriptions();
    } catch (e: any) {
      this.error = e?.response?.data?.error || 'Failed to mark e-prescription as sent';
    } finally {
      this.loading = false;
    }
  }

  async bulkUpdatePrescriptionStatus(status: 'ACTIVE' | 'COMPLETED' | 'CANCELLED' | 'DISCONTINUED') {
    if (this.selectedPrescriptions.length === 0) {
      this.error = 'Please select at least one prescription';
      // Auto-hide error after 5 seconds
      setTimeout(() => {
        if (this.error?.includes('Please select')) {
          this.error = null;
        }
      }, 5000);
      return;
    }
    
    const confirmed = await this.modalService.confirm(
      `Are you sure you want to update ${this.selectedPrescriptions.length} prescription(s) to ${status}?`,
      'Update Prescription Status',
      'Update',
      'Cancel'
    );
    if (!confirmed) {
      return;
    }
    
    try {
      this.loading = true;
      this.error = null;
      
      // Update prescriptions one by one to handle partial failures
      const results = await Promise.allSettled(
        this.selectedPrescriptions.map(id => {
          if (!id || id.trim() === '') {
            throw new Error('Invalid prescription ID');
          }
          return this.prescriptionService.updatePrescriptionStatus(id, status);
        })
      );
      
      // Check for failures
      const failures = results.filter(result => result.status === 'rejected');
      const successes = results.filter(result => result.status === 'fulfilled');
      
      if (failures.length > 0) {
        // Log failures for debugging
        failures.forEach((failure, index) => {
          if (failure.status === 'rejected') {
            this.logger.error(`Failed to update prescription ${this.selectedPrescriptions[index]}:`, failure.reason);
          }
        });
        
        const failureReasons = failures.map((failure, index) => {
          if (failure.status === 'rejected') {
            const error = failure.reason;
            const errorMsg = error?.response?.data?.message || 
                            error?.response?.data?.error || 
                            error?.message || 
                            'Unknown error';
            return errorMsg;
          }
          return 'Unknown error';
        }).join('; ');
        
        const totalFailures = failures.length;
        const totalSuccess = successes.length;
        
        if (totalSuccess > 0) {
          this.error = `Updated ${totalSuccess} prescription(s) successfully. Failed to update ${totalFailures} prescription(s). ${failureReasons}`;
        } else {
          this.error = `Failed to update all ${totalFailures} prescription(s). ${failureReasons}`;
        }
      } else {
        // All succeeded
        this.selectedPrescriptions = [];
        // Don't show error message if all succeeded
        this.error = null;
      }
      
      // Refresh to show updated statuses
      await this.refreshPrescriptions();
      
      // Auto-hide error after 8 seconds (longer since it contains more info)
      if (failures.length > 0) {
        setTimeout(() => {
          this.error = null;
        }, 8000);
      }
    } catch (e: any) {
      this.logger.error('Error bulk updating prescriptions:', e);
      const errorMessage = e?.response?.data?.message || 
                          e?.response?.data?.error || 
                          e?.message || 
                          'Failed to update prescriptions. Please try again.';
      this.error = errorMessage;
      // Auto-hide error after 5 seconds
      setTimeout(() => {
        this.error = null;
      }, 5000);
    } finally {
      this.loading = false;
    }
  }

  applyPrescriptionFilters() {
    const prescriptionsToFilter = this.showAllRecords ? this.allPrescriptions : this.prescriptions;
    let filtered = prescriptionsToFilter && prescriptionsToFilter.length > 0 ? [...prescriptionsToFilter] : [];
    
    // Search filter
    if (this.prescriptionSearchTerm) {
      const searchLower = this.prescriptionSearchTerm.toLowerCase();
      filtered = filtered.filter(p => 
        p.medicationName?.toLowerCase().includes(searchLower) ||
        p.prescriptionNumber?.toLowerCase().includes(searchLower) ||
        p.patientName?.toLowerCase().includes(searchLower) ||
        p.doctorName?.toLowerCase().includes(searchLower) ||
        p.pharmacyName?.toLowerCase().includes(searchLower)
      );
    }
    
    // Status filter
    if (this.prescriptionStatusFilter !== 'all') {
      filtered = filtered.filter(p => p.status === this.prescriptionStatusFilter);
    }
    
    // Date filter
    if (this.prescriptionDateFilter !== 'all') {
      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      
      filtered = filtered.filter(p => {
        const startDate = new Date(p.startDate);
        
        switch (this.prescriptionDateFilter) {
          case 'today':
            return startDate >= today;
          case 'week':
            const weekAgo = new Date(today);
            weekAgo.setDate(weekAgo.getDate() - 7);
            return startDate >= weekAgo;
          case 'month':
            const monthAgo = new Date(today);
            monthAgo.setMonth(monthAgo.getMonth() - 1);
            return startDate >= monthAgo;
          case 'year':
            const yearAgo = new Date(today);
            yearAgo.setFullYear(yearAgo.getFullYear() - 1);
            return startDate >= yearAgo;
          case 'custom':
            if (this.prescriptionDateFrom && this.prescriptionDateTo) {
              const fromDate = new Date(this.prescriptionDateFrom);
              const toDate = new Date(this.prescriptionDateTo);
              toDate.setHours(23, 59, 59, 999);
              return startDate >= fromDate && startDate <= toDate;
            }
            return true;
          default:
            return true;
        }
      });
    }
    
    // Sorting
    filtered.sort((a, b) => {
      let aValue: any, bValue: any;
      
      switch (this.prescriptionSortBy) {
        case 'medicationName':
          aValue = a.medicationName || '';
          bValue = b.medicationName || '';
          break;
        case 'patientName':
          aValue = a.patientName || a.patientId || '';
          bValue = b.patientName || b.patientId || '';
          break;
        case 'status':
          aValue = a.status || '';
          bValue = b.status || '';
          break;
        case 'startDate':
          aValue = new Date(a.startDate).getTime();
          bValue = new Date(b.startDate).getTime();
          break;
        case 'prescriptionNumber':
          aValue = a.prescriptionNumber || '';
          bValue = b.prescriptionNumber || '';
          break;
        case 'createdAt':
        default:
          aValue = new Date(a.createdAt).getTime();
          bValue = new Date(b.createdAt).getTime();
          break;
      }
      
      if (aValue < bValue) return this.prescriptionSortOrder === 'asc' ? -1 : 1;
      if (aValue > bValue) return this.prescriptionSortOrder === 'asc' ? 1 : -1;
      return 0;
    });
    
    this.filteredPrescriptions = filtered;
  }

  onPrescriptionFilterChange() {
    this.applyPrescriptionFilters();
  }

  togglePrescriptionSort(column: string) {
    if (this.prescriptionSortBy === column) {
      this.prescriptionSortOrder = this.prescriptionSortOrder === 'asc' ? 'desc' : 'asc';
    } else {
      this.prescriptionSortBy = column;
      this.prescriptionSortOrder = 'desc';
    }
    this.applyPrescriptionFilters();
  }

  togglePrescriptionSelection(prescriptionId: string) {
    const index = this.selectedPrescriptions.indexOf(prescriptionId);
    if (index > -1) {
      this.selectedPrescriptions.splice(index, 1);
    } else {
      this.selectedPrescriptions.push(prescriptionId);
    }
  }

  toggleSelectAllPrescriptions() {
    const prescriptionsToSelect = this.filteredPrescriptions.length > 0 
      ? this.filteredPrescriptions 
      : (this.showAllRecords ? this.allPrescriptions : this.prescriptions);
    
    if (this.selectedPrescriptions.length === prescriptionsToSelect.length) {
      this.selectedPrescriptions = [];
    } else {
      this.selectedPrescriptions = prescriptionsToSelect.map(p => p.id);
    }
  }

  async toggleRecordsView() {
    this.showAllRecords = !this.showAllRecords;
    this.selectedPrescriptions = [];
    if (this.showAllRecords) {
      await this.loadAllPrescriptions();
    } else {
      if (this.selectedPatientId) {
        await this.loadPatientPrescriptions();
      } else {
        this.applyPrescriptionFilters();
      }
    }
  }

  selectPatient(patientId: string) {
    this.patientSelected.emit(patientId);
  }

  onPatientSelectionChange(patientId: string) {
    this.newPrescription.patientId = patientId;
  }

  getPrescriptionStatistics() {
    const prescriptions = this.showAllRecords ? this.allPrescriptions : this.prescriptions;
    const sourcePrescriptions = prescriptions && prescriptions.length > 0 ? prescriptions : this.filteredPrescriptions;
    const total = sourcePrescriptions.length;
    const active = sourcePrescriptions.filter(p => p.status === 'ACTIVE').length;
    const completed = sourcePrescriptions.filter(p => p.status === 'COMPLETED').length;
    const ePrescriptionsSent = sourcePrescriptions.filter(p => p.ePrescriptionSent).length;
    
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    const recent = sourcePrescriptions.filter(p => {
      const createdDate = new Date(p.createdAt);
      return createdDate >= thirtyDaysAgo;
    }).length;
    
    return {
      total,
      active,
      completed,
      ePrescriptionsSent,
      recent,
      completionRate: total > 0 ? ((completed / total) * 100).toFixed(1) : '0'
    };
  }

  exportPrescriptions() {
    const prescriptions = this.filteredPrescriptions.length > 0 ? this.filteredPrescriptions : 
                         (this.showAllRecords ? this.allPrescriptions : this.prescriptions);
    
    const headers = ['Prescription #', 'Medication', 'Patient', 'Dosage', 'Frequency', 'Quantity', 'Refills', 'Status', 'Start Date', 'End Date', 'E-Prescription Sent'];
    const rows = prescriptions.map(p => [
      p.prescriptionNumber || '',
      p.medicationName || '',
      p.patientName || p.patientId || '',
      p.dosage || '',
      p.frequency || '',
      p.quantity?.toString() || '',
      p.refills?.toString() || '',
      p.status || '',
      p.startDate || '',
      p.endDate || '',
      p.ePrescriptionSent ? 'Yes' : 'No'
    ]);
    
    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.map(cell => `"${cell}"`).join(','))
    ].join('\n');
    
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `prescriptions_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
    window.URL.revokeObjectURL(url);
  }

  printPrescription(prescription: Prescription) {
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    
    printWindow.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>Prescription - ${prescription.prescriptionNumber}</title>
          <style>
            body { font-family: Arial, sans-serif; padding: 20px; max-width: 800px; margin: 0 auto; }
            .header { border-bottom: 2px solid #333; padding-bottom: 20px; margin-bottom: 20px; }
            .prescription-info { margin: 20px 0; }
            .section { margin: 15px 0; }
            .label { font-weight: bold; margin-right: 10px; }
            table { width: 100%; border-collapse: collapse; margin: 20px 0; }
            th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; }
            .footer { margin-top: 40px; padding-top: 20px; border-top: 2px solid #333; }
          </style>
        </head>
        <body>
          <div class="header">
            <h1>Prescription</h1>
            <p><strong>Prescription #:</strong> ${prescription.prescriptionNumber}</p>
            <p><strong>Date:</strong> ${this.formatDate(prescription.createdAt)}</p>
          </div>
          <div class="prescription-info">
            <div class="section">
              <p><span class="label">Patient:</span> ${prescription.patientName || prescription.patientId}</p>
              <p><span class="label">Doctor:</span> ${prescription.doctorName || prescription.doctorId}</p>
            </div>
            <div class="section">
              <h2>Medication Information</h2>
              <table>
                <tr><th>Medication</th><td>${prescription.medicationName}</td></tr>
                <tr><th>Dosage</th><td>${prescription.dosage}</td></tr>
                <tr><th>Frequency</th><td>${prescription.frequency}</td></tr>
                <tr><th>Quantity</th><td>${prescription.quantity}</td></tr>
                <tr><th>Refills</th><td>${prescription.refills || 0}</td></tr>
                <tr><th>Start Date</th><td>${this.formatDate(prescription.startDate)}</td></tr>
                ${prescription.endDate ? `<tr><th>End Date</th><td>${this.formatDate(prescription.endDate)}</td></tr>` : ''}
              </table>
            </div>
            ${prescription.instructions ? `<div class="section"><p><span class="label">Instructions:</span> ${prescription.instructions}</p></div>` : ''}
            ${prescription.pharmacyName ? `
              <div class="section">
                <h2>Pharmacy Information</h2>
                <p><span class="label">Pharmacy:</span> ${prescription.pharmacyName}</p>
                ${prescription.pharmacyAddress ? `<p><span class="label">Address:</span> ${prescription.pharmacyAddress}</p>` : ''}
                ${prescription.pharmacyPhone ? `<p><span class="label">Phone:</span> ${prescription.pharmacyPhone}</p>` : ''}
              </div>
            ` : ''}
            <div class="footer">
              <p><strong>Status:</strong> ${prescription.status}</p>
              ${prescription.ePrescriptionSent ? `<p><strong>E-Prescription Sent:</strong> Yes (${prescription.ePrescriptionSentAt ? this.formatDate(prescription.ePrescriptionSentAt) : 'N/A'})</p>` : ''}
            </div>
          </div>
        </body>
      </html>
    `);
    
    printWindow.document.close();
    printWindow.print();
  }

  formatDate(dateString: string): string {
    if (!dateString) return 'N/A';
    const date = new Date(dateString);
    return date.toLocaleDateString();
  }

  get prescriptionDebug() {
    return {
      doctorId: this.doctorId,
      selectedPatientId: this.selectedPatientId,
      showAllRecords: this.showAllRecords,
      prescriptions: this.prescriptions?.length || 0,
      allPrescriptions: this.allPrescriptions?.length || 0,
      filteredPrescriptions: this.filteredPrescriptions?.length || 0,
      newPrescription: this.newPrescription,
    };
  }
}
