import { Component, inject, OnInit, OnDestroy, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Store } from '@ngrx/store';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { Subscription } from 'rxjs';
import { take } from 'rxjs/operators';
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { DialogModule } from 'primeng/dialog';
import { InputTextModule } from 'primeng/inputtext';
import { SelectModule } from 'primeng/select';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { DatePickerModule } from 'primeng/datepicker';
import { TooltipModule } from 'primeng/tooltip';
import { ProgressSpinnerModule } from 'primeng/progressspinner';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent, DataTableComponent, FormDialogComponent, TableColumn } from '../../shared';
import {
  FiscalYearsActions,
  selectAllFiscalYears,
  selectFiscalYearsLoading,
  selectFiscalYearsSaving,
  selectFiscalYearsError,
} from '../../core/store';
import { FiscalYear, FiscalPeriod } from '../../core/models/fiscal-year.model';
import { FiscalPeriodService } from '../../core/services/fiscal-period.service';
import { FiscalYearService } from '../../core/services/fiscal-year.service';

@Component({
  selector: 'app-fiscal-years',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    TranslateModule,
    TableModule,
    ButtonModule,
    DialogModule,
    InputTextModule,
    SelectModule,
    TagModule,
    ToastModule,
    ConfirmDialogModule,
    DatePickerModule, TooltipModule, ProgressSpinnerModule,
    PageHeaderComponent, DataTableComponent, FormDialogComponent,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './fiscal-years.component.html',
  styleUrl: './fiscal-years.component.scss',
})
export class FiscalYearsComponent implements OnInit, OnDestroy {
  private fb = inject(FormBuilder);
  private store = inject(Store);
  private messageService = inject(MessageService);
  private confirmationService = inject(ConfirmationService);
  private translate = inject(TranslateService);
  private fiscalPeriodService = inject(FiscalPeriodService);
  private fiscalYearService = inject(FiscalYearService);
  private langSub!: Subscription;

  readonly columns: TableColumn[] = [
    { field: 'name_ar', header: 'FISCAL_YEARS.NAME', sortable: true },
    { field: 'start_date', header: 'FISCAL_YEARS.START_DATE' },
    { field: 'end_date', header: 'FISCAL_YEARS.END_DATE' },
    { field: 'periods', header: 'FISCAL_YEARS.PERIODS' },
    { field: 'status', header: 'COMMON.STATUS' },
    { field: 'actions', header: 'COMMON.ACTIONS' },
  ];

  fiscalYears$ = this.store.select(selectAllFiscalYears);
  loading$ = this.store.select(selectFiscalYearsLoading);
  saving$ = this.store.select(selectFiscalYearsSaving);
  error$ = this.store.select(selectFiscalYearsError);

  dialogVisible = signal(false);
  periodsDialogVisible = signal(false);
  editingFiscalYear = signal<FiscalYear | null>(null);
  viewingPeriods = signal<FiscalYear | null>(null);
  fiscalYearForm!: FormGroup;

  statusOptions: any[] = [];

  ngOnInit(): void {
    this.initForm();
    this.buildOptions();
    this.langSub = this.translate.onLangChange.subscribe(() => this.buildOptions());
    this.store.dispatch(FiscalYearsActions.loadFiscalYears({}));
  }

  ngOnDestroy(): void {
    this.langSub?.unsubscribe();
  }

  private buildOptions(): void {
    this.statusOptions = [
      { label: this.translate.instant('FISCAL_YEARS.STATUS_OPEN'), value: 'open' },
      { label: this.translate.instant('FISCAL_YEARS.STATUS_CLOSED'), value: 'closed' },
    ];
  }

  private initForm(): void {
    this.fiscalYearForm = this.fb.group({
      name_ar: ['', Validators.required],
      start_date: [null, Validators.required],
      end_date: [null, Validators.required],
      status: ['open'],
    });
  }

  openNew(): void {
    this.editingFiscalYear.set(null);
    this.fiscalYearForm.reset({ status: 'open' });
    this.dialogVisible.set(true);
  }

  editFiscalYear(fy: FiscalYear): void {
    this.editingFiscalYear.set(fy);
    this.fiscalYearForm.patchValue({
      name_ar: fy.name_ar,
      start_date: new Date(fy.start_date),
      end_date: new Date(fy.end_date),
      status: fy.status || 'open',
    });
    this.dialogVisible.set(true);
  }

  loadingPeriods = signal(false);

  viewPeriods(fy: FiscalYear): void {
    this.viewingPeriods.set(fy);
    this.periodsDialogVisible.set(true);
    this.loadingPeriods.set(true);
    this.fiscalYearService.getById(fy.id).subscribe({
      next: (res) => {
        this.viewingPeriods.set(res.data);
        this.loadingPeriods.set(false);
      },
      error: () => {
        this.loadingPeriods.set(false);
        this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: 'Failed to load periods' });
      },
    });
  }

  deleteFiscalYear(fy: FiscalYear): void {
    this.confirmationService.confirm({
      message: this.translate.instant('FISCAL_YEARS.CONFIRM_DELETE'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.store.dispatch(FiscalYearsActions.deleteFiscalYear({ id: fy.id }));
        const sub = this.store.select(selectFiscalYearsSaving).subscribe((saving) => {
          if (!saving) {
            sub.unsubscribe();
            this.store.select(selectFiscalYearsError).pipe(take(1)).subscribe((error) => {
              if (error) {
                this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: error });
              } else {
                this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'), detail: this.translate.instant('FISCAL_YEARS.DELETE_SUCCESS') });
              }
            });
          }
        });
      },
    });
  }

  onSave(): void {
    if (this.fiscalYearForm.valid) {
      const formValue = this.fiscalYearForm.value;
      const startDate = formValue.start_date instanceof Date
        ? formValue.start_date.toISOString().split('T')[0]
        : formValue.start_date;
      const endDate = formValue.end_date instanceof Date
        ? formValue.end_date.toISOString().split('T')[0]
        : formValue.end_date;

      const data = {
        name: formValue.name_ar,
        name_ar: formValue.name_ar,
        start_date: startDate,
        end_date: endDate,
        status: formValue.status,
      };

      if (this.editingFiscalYear()) {
        this.store.dispatch(FiscalYearsActions.updateFiscalYear({ id: this.editingFiscalYear()!.id, fiscalYear: data }));
      } else {
        this.store.dispatch(FiscalYearsActions.createFiscalYear({ fiscalYear: data }));
      }

      const sub = this.store.select(selectFiscalYearsSaving).subscribe((saving) => {
        if (!saving) {
          sub.unsubscribe();
          this.store.select(selectFiscalYearsError).pipe(take(1)).subscribe((error) => {
            if (error) {
              this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: error });
            } else {
              this.dialogVisible.set(false);
              this.messageService.add({
                severity: 'success',
                summary: this.translate.instant('COMMON.SUCCESS'),
                detail: this.editingFiscalYear()
                  ? this.translate.instant('FISCAL_YEARS.UPDATE_SUCCESS')
                  : this.translate.instant('FISCAL_YEARS.CREATE_SUCCESS'),
              });
              // Reload to get periods
              this.store.dispatch(FiscalYearsActions.loadFiscalYears({ forceReload: true }));
            }
          });
        }
      });
    } else {
      this.fiscalYearForm.markAllAsTouched();
    }
  }

  closePeriod(period: FiscalPeriod): void {
    this.confirmationService.confirm({
      message: this.translate.instant('FISCAL_YEARS.CONFIRM_CLOSE_PERIOD'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.fiscalPeriodService.close(period.id).subscribe({
          next: () => {
            this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'), detail: this.translate.instant('FISCAL_YEARS.CLOSE_PERIOD_SUCCESS') });
            this.store.dispatch(FiscalYearsActions.loadFiscalYears({ forceReload: true }));
            // Refresh the viewing periods
            const fy = this.viewingPeriods();
            if (fy) {
              const updatedPeriods = fy.periods?.map(p => p.id === period.id ? { ...p, status: 'closed' } : p);
              this.viewingPeriods.set({ ...fy, periods: updatedPeriods });
            }
          },
          error: (err) => this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: err.error?.message || 'Failed to close period' }),
        });
      },
    });
  }

  retry(): void {
    this.store.dispatch(FiscalYearsActions.loadFiscalYears({ forceReload: true }));
  }
}
