import { Component, inject, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DynamicPopupComponent } from '../../shared/dynamic-popup/dynamic-popup';
import { DynamicFormConfig } from '../../shared/dynamic-form/dynamic-form-config';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { AdminQuery } from '../state/admin.query';
import { AdminStateService } from '../state/admin-state.service';
import { Subject, takeUntil } from 'rxjs';
import { environment } from '../../../environments/environment';
import { IHobby } from '../models/hobby.model';

@Component({
  selector: 'app-about',
  imports: [CommonModule, MatDialogModule],
  templateUrl: './about.html',
  styleUrl: './about.scss'
})
export class About implements OnInit, OnDestroy {
  private dialog = inject(MatDialog);
  private adminQuery = inject(AdminQuery);
  private adminState = inject(AdminStateService);
  private destroy$ = new Subject<void>();

  about$ = this.adminQuery.about$;
  loading$ = this.adminQuery.aboutLoading$;
  imagesOrigin = environment.apiUrl + '/images/';

  popupConfig?: DynamicFormConfig;
  popupData: Record<string, unknown> = {};

  ngOnInit(): void {
    if (!this.adminQuery.getAbout()) {
      this.adminState.loadAbout()
        .pipe(takeUntil(this.destroy$))
        .subscribe();
    }
  }

  openEdit(): void {
    const currentAbout = this.adminQuery.getAbout();

    this.popupConfig = {
      title: 'Edit About',
      submitLabel: 'Save',
      api: {
        save: '/api/v1/admin/UpsertHobbies',
        method: 'POST'
      },
      fields: [
        { name: 'about', label: 'About', type: 'textarea', required: true },
        {
          name: 'hobbies',
          label: 'Hobbies',
          type: 'array',
          itemConfig: [
            { name: 'hobbyId', label: 'Hobby ID', type: 'hidden' },
            { name: 'name', label: 'Name', type: 'text', required: true },
            { name: 'description', label: 'Description', type: 'text', required: true },
            { name: 'icon', label: 'Icon (FA class)', type: 'text', placeholder: 'e.g. fa-code' }
          ]
        }
      ]
    };

    this.popupData = {
      about: currentAbout?.about,
      hobbies: currentAbout?.hobbies ?? []
    };

    const ref = this.dialog.open(DynamicPopupComponent, {
      data: { config: this.popupConfig, data: this.popupData },
      panelClass: 'dark-popup-panel'
    });

    ref.afterClosed()
      .pipe(takeUntil(this.destroy$))
      .subscribe((res: { about: string; hobbies: IHobby[] } | null) => {
        if (res) {
          const updated = { ...currentAbout!, about: res.about, hobbies: res.hobbies ?? currentAbout!.hobbies };
          this.adminState.updateAbout(updated);
        }
      });
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
