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 { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { InputTextModule } from 'primeng/inputtext';
import { InputNumberModule } from 'primeng/inputnumber';
import { SelectModule } from 'primeng/select';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { TooltipModule } from 'primeng/tooltip';
import { ToggleSwitchModule } from 'primeng/toggleswitch';
import { DatePickerModule } from 'primeng/datepicker';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent, DataTableComponent, FormDialogComponent, TableColumn } from '../../shared';
import { RecurringEntryService } from '../../core/services/recurring-entry.service';
import { EntryTemplateService } from '../../core/services/entry-template.service';
import { RecurringEntry } from '../../core/models/recurring-entry.model';
import { EntryTemplate } from '../../core/models/entry-template.model';

@Component({
  selector: 'app-recurring-entries',
  standalone: true,
  imports: [
    CommonModule, ReactiveFormsModule, TranslateModule,
    TableModule, ButtonModule, InputTextModule, InputNumberModule,
    SelectModule, TagModule, ToastModule, ConfirmDialogModule, TooltipModule,
    ToggleSwitchModule, DatePickerModule,
    PageHeaderComponent, DataTableComponent, FormDialogComponent,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './recurring-entries.component.html',
  styleUrl: './recurring-entries.component.scss',
})
export class RecurringEntriesComponent implements OnInit, OnDestroy {
  readonly columns: TableColumn[] = [
    { field: 'name', header: 'RECURRING_ENTRIES.NAME' },
    { field: 'template', header: 'RECURRING_ENTRIES.TEMPLATE' },
    { field: 'frequency', header: 'RECURRING_ENTRIES.FREQUENCY' },
    { field: 'next_execution', header: 'RECURRING_ENTRIES.NEXT_EXECUTION' },
    { field: 'executions', header: 'RECURRING_ENTRIES.EXECUTIONS' },
    { field: 'status', header: 'COMMON.STATUS' },
    { field: 'actions', header: 'COMMON.ACTIONS' },
  ];

  private fb = inject(FormBuilder);
  private service = inject(RecurringEntryService);
  private templateService = inject(EntryTemplateService);
  private messageService = inject(MessageService);
  private confirmationService = inject(ConfirmationService);
  private translate = inject(TranslateService);
  private langSub!: Subscription;

  entries = signal<RecurringEntry[]>([]);
  totalRecords = signal(0);
  tableLoading = signal(false);
  first = 0;
  rows = 25;
  templates = signal<EntryTemplate[]>([]);
  loading = signal(true);
  dialogVisible = signal(false);
  editing = signal<RecurringEntry | null>(null);
  saving = signal(false);

  form!: FormGroup;
  frequencyOptions: any[] = [];

  ngOnInit(): void {
    this.initForm();
    this.buildOptions();
    this.langSub = this.translate.onLangChange.subscribe(() => this.buildOptions());
    this.loadPage();
    this.loadTemplates();
  }

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

  private buildOptions(): void {
    this.frequencyOptions = [
      { label: this.translate.instant('RECURRING_ENTRIES.FREQ_DAILY'), value: 'daily' },
      { label: this.translate.instant('RECURRING_ENTRIES.FREQ_WEEKLY'), value: 'weekly' },
      { label: this.translate.instant('RECURRING_ENTRIES.FREQ_MONTHLY'), value: 'monthly' },
      { label: this.translate.instant('RECURRING_ENTRIES.FREQ_QUARTERLY'), value: 'quarterly' },
      { label: this.translate.instant('RECURRING_ENTRIES.FREQ_YEARLY'), value: 'yearly' },
    ];
  }

  private initForm(): void {
    this.form = this.fb.group({
      name_ar: ['', Validators.required],
      name: [''],
      entry_template_id: [null, Validators.required],
      frequency: ['monthly', Validators.required],
      start_date: [null, Validators.required],
      end_date: [null],
      max_executions: [null],
      is_active: [true],
    });
  }

  loadPage(page = 1, perPage = this.rows): void {
    this.tableLoading.set(true);
    this.loading.set(true);
    this.service.list(page, perPage).subscribe({
      next: (res) => {
        this.entries.set(res.data || []);
        this.totalRecords.set(res.meta?.total || 0);
        this.tableLoading.set(false);
        this.loading.set(false);
      },
      error: () => { this.tableLoading.set(false); this.loading.set(false); },
    });
  }

  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);
  }

  private loadTemplates(): void {
    this.templateService.list(1, 100).subscribe({
      next: (res) => this.templates.set(res.data || []),
      error: () => {},
    });
  }

  openNew(): void {
    this.editing.set(null);
    this.form.reset({ frequency: 'monthly', is_active: true });
    this.dialogVisible.set(true);
  }

  edit(entry: RecurringEntry): void {
    this.editing.set(entry);
    this.form.patchValue({
      name_ar: entry.name_ar,
      name: entry.name,
      entry_template_id: entry.entry_template_id,
      frequency: entry.frequency,
      start_date: entry.start_date ? new Date(entry.start_date) : null,
      end_date: entry.end_date ? new Date(entry.end_date) : null,
      max_executions: entry.max_executions,
      is_active: entry.is_active,
    });
    this.dialogVisible.set(true);
  }

  delete(entry: RecurringEntry): void {
    this.confirmationService.confirm({
      message: this.translate.instant('RECURRING_ENTRIES.CONFIRM_DELETE'),
      header: this.translate.instant('COMMON.CONFIRM'),
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.service.delete(entry.id).subscribe({
          next: () => {
            this.loadData();
            this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'), detail: this.translate.instant('RECURRING_ENTRIES.DELETE_SUCCESS') });
          },
          error: (err) => this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: err.error?.message || 'Failed' }),
        });
      },
    });
  }

  execute(entry: RecurringEntry): void {
    this.confirmationService.confirm({
      message: this.translate.instant('RECURRING_ENTRIES.CONFIRM_EXECUTE'),
      header: this.translate.instant('COMMON.CONFIRM'),
      accept: () => {
        this.service.execute(entry.id).subscribe({
          next: () => {
            this.loadData();
            this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'), detail: this.translate.instant('RECURRING_ENTRIES.EXECUTE_SUCCESS') });
          },
          error: (err) => this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: err.error?.message || 'Failed' }),
        });
      },
    });
  }

  onSave(): void {
    if (!this.form.valid) { this.form.markAllAsTouched(); return; }
    this.saving.set(true);
    const val = { ...this.form.value };
    val.name = val.name || val.name_ar;
    if (val.start_date instanceof Date) val.start_date = val.start_date.toISOString().split('T')[0];
    if (val.end_date instanceof Date) val.end_date = val.end_date.toISOString().split('T')[0];

    const obs = this.editing()
      ? this.service.update(this.editing()!.id, val)
      : this.service.create(val);

    obs.subscribe({
      next: () => {
        this.saving.set(false);
        this.dialogVisible.set(false);
        this.loadData();
        this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant(this.editing() ? 'RECURRING_ENTRIES.UPDATE_SUCCESS' : 'RECURRING_ENTRIES.CREATE_SUCCESS') });
      },
      error: (err) => {
        this.saving.set(false);
        this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: err.error?.message || 'Failed' });
      },
    });
  }

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