import { Component, inject, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AuthService } from '../../auth/auth.service';
import { AdminQuery } from '../state/admin.query';
import { AdminStateService } from '../state/admin-state.service';
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 { Subject, takeUntil } from 'rxjs';
import { environment } from '../../../environments/environment';
import { IContactModel } from './contact.model';

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

  contact$ = this.adminQuery.contact$;
  loading$ = this.adminQuery.contactLoading$;
  imagesOrigin = environment.apiUrl + '/images/';

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

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

  openEdit(): void {
    const current = this.adminQuery.getContact();

    this.popupConfig = {
      title: 'Edit Contact',
      submitLabel: 'Save',
      api: {
        save: '/api/v1/admin/UpsertContact',
        method: 'POST'
      },
      fields: [
        { name: 'title', label: 'Title', type: 'text', required: true },
        { name: 'firstName', label: 'First Name', type: 'text', required: true },
        { name: 'lastName', label: 'Last Name', type: 'text', required: true },
        { name: 'email', label: 'Email', type: 'text', required: true },
        { name: 'phone', label: 'Phone', type: 'text', required: true },
        { name: 'dob', label: 'Date of Birth', type: 'date' },
        { name: 'address', label: 'Address', type: 'textarea' },
        { name: 'linkedin', label: 'LinkedIn URL', type: 'text' },
        { name: 'gitHub', label: 'GitHub URL', type: 'text' },
        { name: 'blogUrl', label: 'Blog URL', type: 'text' }
      ]
    };

    this.popupData = {
      title: current?.title,
      firstName: current?.candidate?.firstName,
      lastName: current?.candidate?.lastName,
      email: current?.candidate?.email,
      phone: current?.candidate?.phone,
      dob: current?.candidate?.dob,
      address: current?.candidate?.address,
      linkedin: current?.socialLinks?.linkedin,
      gitHub: current?.socialLinks?.gitHub,
      blogUrl: current?.socialLinks?.blogUrl
    };

    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: IContactModel) => {
        if (res) {
          const updated = {
            ...current!,
            title: res.title ?? '',
            candidate: {
              ...current!.candidate!,
              firstName: res.candidate?.firstName ?? '',
              lastName: res.candidate?.lastName ?? '',
              displayName: `${res.candidate?.firstName ?? ''} ${res.candidate?.lastName ?? ''}`,
              email: res.candidate?.email ?? '',
              phone: res.candidate?.phone ?? '',
              dob: res.candidate?.dob ?? '',
              address: res.candidate?.address ?? ''
            },
            socialLinks: {
              ...current!.socialLinks!,
              linkedin: res.socialLinks?.linkedin ?? '',
              gitHub: res.socialLinks?.gitHub ?? '',
              blogUrl: res.socialLinks?.blogUrl ?? ''
            }
          };
          this.adminState.updateContact(updated);
        }
      });
  }

  logout() {
    this.authSvc.logout();
  }

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