import { Component, OnInit, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, FormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { TabsModule } from 'primeng/tabs';
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { DialogModule } from 'primeng/dialog';
import { InputTextModule } from 'primeng/inputtext';
import { InputNumberModule } from 'primeng/inputnumber';
import { SelectModule } from 'primeng/select';
import { MultiSelectModule } from 'primeng/multiselect';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { TextareaModule } from 'primeng/textarea';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { HrKpiService } from '../../../core/services/hr-kpi.service';
import { HrReviewTemplateService } from '../../../core/services/hr-review-template.service';

@Component({
  selector: 'app-hr-kpis',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    TranslateModule,
    TabsModule,
    TableModule,
    ButtonModule,
    DialogModule,
    InputTextModule,
    InputNumberModule,
    SelectModule,
    MultiSelectModule,
    TagModule,
    ToastModule,
    ConfirmDialogModule,
    TextareaModule,
    PageHeaderComponent,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './hr-kpis.component.html',
  styleUrl: './hr-kpis.component.scss',
})
export class HrKpisComponent implements OnInit {
  private fb = inject(FormBuilder);
  private messageService = inject(MessageService);
  private confirmationService = inject(ConfirmationService);
  private translate = inject(TranslateService);
  private kpiService = inject(HrKpiService);
  private reviewTemplateService = inject(HrReviewTemplateService);

  // KPI tab state
  kpiDialogVisible = signal(false);
  editingKpi = signal<any>(null);
  kpiTableLoading = signal(false);
  kpiSaving = signal(false);
  kpiTableData = signal<any[]>([]);
  kpiTotalRecords = signal(0);
  kpiFirst = 0;
  kpiRows = 25;
  kpiForm!: FormGroup;

  // Review Template tab state
  templateDialogVisible = signal(false);
  editingTemplate = signal<any>(null);
  templateTableLoading = signal(false);
  templateSaving = signal(false);
  templateTableData = signal<any[]>([]);
  templateTotalRecords = signal(0);
  templateFirst = 0;
  templateRows = 25;
  templateForm!: FormGroup;

  // Shared data
  allKpis: any[] = [];

  statusOptions = [
    { label: 'Active', value: 'active' },
    { label: 'Inactive', value: 'inactive' },
  ];

  ngOnInit(): void {
    this.initKpiForm();
    this.initTemplateForm();
    this.loadKpiPage();
    this.loadTemplatePage();
    this.loadAllKpis();
  }

  // ==================== KPI Methods ====================

  private initKpiForm(): void {
    this.kpiForm = this.fb.group({
      name_ar: ['', Validators.required],
      name_en: [''],
      category: [''],
      weight: [null],
      target_value: [null],
      unit: [''],
      description: [''],
      status: ['active'],
    });
  }

  loadKpiPage(page = 1, perPage = this.kpiRows): void {
    this.kpiTableLoading.set(true);
    this.kpiService.list(page, perPage).subscribe({
      next: (res) => {
        this.kpiTableData.set(res.data);
        this.kpiTotalRecords.set(res.meta.total);
        this.kpiTableLoading.set(false);
      },
      error: () => this.kpiTableLoading.set(false),
    });
  }

  onKpiPageChange(event: any): void {
    this.kpiFirst = event.first;
    this.kpiRows = event.rows;
    const page = Math.floor(event.first / event.rows) + 1;
    this.loadKpiPage(page, event.rows);
  }

  openNewKpi(): void {
    this.editingKpi.set(null);
    this.kpiForm.reset({ status: 'active' });
    this.kpiDialogVisible.set(true);
  }

  editKpi(item: any): void {
    this.editingKpi.set(item);
    this.kpiForm.patchValue(item);
    this.kpiDialogVisible.set(true);
  }

  onSaveKpi(): void {
    if (!this.kpiForm.valid) {
      this.kpiForm.markAllAsTouched();
      return;
    }

    const data = { ...this.kpiForm.value };
    const isEdit = !!this.editingKpi();
    const obs = isEdit
      ? this.kpiService.update(this.editingKpi()!.id, data)
      : this.kpiService.create(data);

    this.kpiSaving.set(true);
    obs.subscribe({
      next: () => {
        this.kpiSaving.set(false);
        this.kpiDialogVisible.set(false);
        this.loadKpiPage();
        this.loadAllKpis();
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: isEdit
            ? this.translate.instant('COMMON.UPDATED')
            : this.translate.instant('COMMON.CREATED'),
        });
      },
      error: (err) => {
        this.kpiSaving.set(false);
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Operation failed',
        });
      },
    });
  }

  deleteKpi(item: any): void {
    this.confirmationService.confirm({
      message: this.translate.instant('HR.KPIS.DELETE_CONFIRM'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.kpiService.delete(item.id).subscribe({
          next: () => {
            this.loadKpiPage();
            this.loadAllKpis();
            this.messageService.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('COMMON.DELETED'),
            });
          },
          error: (err) => {
            this.messageService.add({
              severity: 'error',
              summary: this.translate.instant('COMMON.ERROR'),
              detail: err.error?.message || 'Delete failed',
            });
          },
        });
      },
    });
  }

  // ==================== Review Template Methods ====================

  private initTemplateForm(): void {
    this.templateForm = this.fb.group({
      name_ar: ['', Validators.required],
      name_en: [''],
      description: [''],
      kpi_ids: [[]],
      status: ['active'],
    });
  }

  private loadAllKpis(): void {
    this.kpiService.listAll().subscribe({
      next: (res) => (this.allKpis = res.data),
    });
  }

  loadTemplatePage(page = 1, perPage = this.templateRows): void {
    this.templateTableLoading.set(true);
    this.reviewTemplateService.list(page, perPage).subscribe({
      next: (res) => {
        this.templateTableData.set(res.data);
        this.templateTotalRecords.set(res.meta.total);
        this.templateTableLoading.set(false);
      },
      error: () => this.templateTableLoading.set(false),
    });
  }

  onTemplatePageChange(event: any): void {
    this.templateFirst = event.first;
    this.templateRows = event.rows;
    const page = Math.floor(event.first / event.rows) + 1;
    this.loadTemplatePage(page, event.rows);
  }

  openNewTemplate(): void {
    this.editingTemplate.set(null);
    this.templateForm.reset({ status: 'active', kpi_ids: [] });
    this.templateDialogVisible.set(true);
  }

  editTemplate(item: any): void {
    this.editingTemplate.set(item);
    this.templateForm.patchValue({
      ...item,
      kpi_ids: item.kpis?.map((k: any) => k.id) || item.kpi_ids || [],
    });
    this.templateDialogVisible.set(true);
  }

  onSaveTemplate(): void {
    if (!this.templateForm.valid) {
      this.templateForm.markAllAsTouched();
      return;
    }

    const data = { ...this.templateForm.value };
    const isEdit = !!this.editingTemplate();
    const obs = isEdit
      ? this.reviewTemplateService.update(this.editingTemplate()!.id, data)
      : this.reviewTemplateService.create(data);

    this.templateSaving.set(true);
    obs.subscribe({
      next: () => {
        this.templateSaving.set(false);
        this.templateDialogVisible.set(false);
        this.loadTemplatePage();
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: isEdit
            ? this.translate.instant('COMMON.UPDATED')
            : this.translate.instant('COMMON.CREATED'),
        });
      },
      error: (err) => {
        this.templateSaving.set(false);
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Operation failed',
        });
      },
    });
  }

  deleteTemplate(item: any): void {
    this.confirmationService.confirm({
      message: this.translate.instant('HR.REVIEW_TEMPLATES.DELETE_CONFIRM'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.reviewTemplateService.delete(item.id).subscribe({
          next: () => {
            this.loadTemplatePage();
            this.messageService.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('COMMON.DELETED'),
            });
          },
          error: (err) => {
            this.messageService.add({
              severity: 'error',
              summary: this.translate.instant('COMMON.ERROR'),
              detail: err.error?.message || 'Delete failed',
            });
          },
        });
      },
    });
  }

  // ==================== Shared ====================

  getStatusSeverity(status: string): 'success' | 'info' | 'warn' | 'secondary' | 'contrast' | 'danger' {
    return status === 'active' ? 'success' : 'danger';
  }
}
