import { Component, inject, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { ToastModule } from 'primeng/toast';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { FileUploadModule } from 'primeng/fileupload';
import { TagModule } from 'primeng/tag';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent, DataTableComponent, TableColumn } from '../../shared';
import { AttachmentService, Attachment } from '../../core/services/attachment.service';

@Component({
  selector: 'app-attachments',
  standalone: true,
  imports: [
    CommonModule, TranslateModule,
    TableModule, ButtonModule, ToastModule, ConfirmDialogModule,
    FileUploadModule, TagModule,
    PageHeaderComponent, DataTableComponent,
  ],
  providers: [MessageService, ConfirmationService],
  template: `
    <p-toast />
    <p-confirmDialog />

    <div class="page-container">
      <app-page-header title="ATTACHMENTS.TITLE" subtitle="ATTACHMENTS.SUBTITLE" (refresh)="retry()">
        <p-fileUpload
          mode="basic"
          [auto]="true"
          [chooseLabel]="'ATTACHMENTS.UPLOAD' | translate"
          chooseIcon="pi pi-upload"
          (onSelect)="onUpload($event)"
          [maxFileSize]="10485760"
        />
      </app-page-header>

      <ng-template #bodyTpl let-att>
          <tr>
            <td>
              <i [class]="getFileIcon(att.mime_type)" class="me-2"></i>
              {{ att.file_name }}
            </td>
            <td><p-tag [value]="att.mime_type" severity="info" [rounded]="true" /></td>
            <td>{{ formatSize(att.size || att.file_size) }}</td>
            <td>{{ att.created_at | date:'short' }}</td>
            <td>
              <div class="action-buttons">
                <p-button icon="pi pi-download" [rounded]="true" [text]="true" severity="info" (onClick)="download(att)" />
                <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" (onClick)="confirmDelete(att)" />
              </div>
            </td>
          </tr>
        </ng-template>
      <app-data-table [data]="attachments()" [loading]="tableLoading()" [lazy]="true" [totalRecords]="totalRecords()" [first]="first" (onLazyLoad)="onPageChange($event)" (retry)="retry()" [columns]="columns" [bodyTpl]="bodyTpl">
      </app-data-table>
    </div>
  `,
  styles: [`
    .page-container { max-width: 1200px; margin: 0 auto; }
    .action-buttons { display: flex; gap: 0.25rem; }
  `],
})
export class AttachmentsComponent implements OnInit {
  readonly columns: TableColumn[] = [
    { field: 'file_name', header: 'ATTACHMENTS.FILE_NAME' },
    { field: 'mime_type', header: 'ATTACHMENTS.MIME_TYPE' },
    { field: 'size', header: 'ATTACHMENTS.SIZE' },
    { field: 'uploaded_at', header: 'ATTACHMENTS.UPLOADED_AT' },
    { field: 'actions', header: 'COMMON.ACTIONS' },
  ];

  private attachmentService = inject(AttachmentService);
  private messageService = inject(MessageService);
  private confirmationService = inject(ConfirmationService);
  private translate = inject(TranslateService);

  attachments = signal<Attachment[]>([]);
  totalRecords = signal(0);
  tableLoading = signal(false);
  first = 0;
  rows = 25;
  loading = signal(false);

  ngOnInit(): void {
    this.loadPage();
  }

  loadPage(page = 1, perPage = this.rows): void {
    this.tableLoading.set(true);
    this.loading.set(true);
    this.attachmentService.list(page, perPage).subscribe({
      next: (res) => {
        this.loading.set(false);
        this.tableLoading.set(false);
        this.attachments.set(res.data || []);
        this.totalRecords.set(res.meta?.total || 0);
      },
      error: () => {
        this.loading.set(false);
        this.tableLoading.set(false);
        this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: 'Failed to load attachments' });
      },
    });
  }

  onPageChange(event: any): void {
    this.first = event.first;
    this.rows = event.rows;
    const page = Math.floor(event.first / event.rows) + 1;
    this.loadPage(page, event.rows);
  }

  private loadData(): void {
    this.loadPage(Math.floor(this.first / this.rows) + 1, this.rows);
  }

  retry(): void { this.loadPage(Math.floor(this.first / this.rows) + 1, this.rows); }

  onUpload(event: any): void {
    const file = event.files?.[0] || event.currentFiles?.[0];
    if (!file) return;
    this.attachmentService.upload(file).subscribe({
      next: () => {
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('ATTACHMENTS.UPLOAD_SUCCESS'),
        });
        this.loadData();
      },
      error: (err) => {
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Upload failed',
        });
      },
    });
  }

  download(att: Attachment): void {
    this.attachmentService.download(att.id).subscribe({
      next: (blob) => {
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = att.file_name;
        a.click();
        URL.revokeObjectURL(url);
      },
      error: () => {
        this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: 'Download failed' });
      },
    });
  }

  confirmDelete(att: Attachment): void {
    this.confirmationService.confirm({
      message: this.translate.instant('ATTACHMENTS.CONFIRM_DELETE', { name: att.file_name }),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.attachmentService.delete(att.id).subscribe({
          next: () => {
            this.messageService.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('ATTACHMENTS.DELETE_SUCCESS'),
            });
            this.loadData();
          },
          error: () => {
            this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: 'Delete failed' });
          },
        });
      },
    });
  }

  getFileIcon(mimeType: string): string {
    if (!mimeType) return 'pi pi-file';
    if (mimeType.startsWith('image/')) return 'pi pi-image';
    if (mimeType.includes('pdf')) return 'pi pi-file-pdf';
    if (mimeType.includes('word') || mimeType.includes('document')) return 'pi pi-file-word';
    if (mimeType.includes('excel') || mimeType.includes('spreadsheet')) return 'pi pi-file-excel';
    return 'pi pi-file';
  }

  formatSize(bytes: number): string {
    if (!bytes) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
  }
}
