import { Component, effect, inject, input, OnInit } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { ThemeType } from '@app/domain/settings/setting.model';
import { SettingsFacade } from '@app/adapters/settings/settings.facade';
import { ProfileViewModel } from '@app/adapters/profiles/profile.presenter.model';
import { ProfileFacade } from '@app/adapters/profiles/profile.facade';
import { ActionType } from '@app/domain/action-type.util';
import { SettingsProfileDto } from '@app/domain/profiles/dto/settings-profile.dto';

@Component({
  selector: 'app-settings',
  standalone: true,
  imports: [ReactiveFormsModule],
  templateUrl: './settings.component.html',
  styleUrl: './settings.component.scss',
})
export class SettingsComponent implements OnInit {
  protected readonly ThemeType = ThemeType;
  private readonly settingsFacade = inject(SettingsFacade);
  private readonly fb: FormBuilder = inject(FormBuilder);
  private readonly profileFacade = inject(ProfileFacade);
  private readonly loading = this.profileFacade.loading;
  private readonly error = this.profileFacade.error;
  profile = input.required<ProfileViewModel>();

  settings = this.settingsFacade.settings;

  privacyForm = this.fb.group({
    isProfilePublic: [false, [Validators.required]],
    showEmail: [false, [Validators.required]],
    showPhone: [false, [Validators.required]],
    allowGeolocation: [false, [Validators.required]],
  });

  settingsForm = this.fb.group({
    theme: [ThemeType.SYSTEM, [Validators.required]],
    privacy: this.privacyForm,
  });

  constructor() {
    effect(() => {
      const userSettings = this.profile()!.settings!
        ? this.profile()!.settings!
        : this.settings().privacy;
      if (userSettings) {
        this.updateForm(userSettings);
      }

      if (!this.loading().isLoading) {
        switch (this.loading().action) {
          case ActionType.UPDATE:
            if (!this.error().hasError && this.loading().isDone) {
              this.updateForm(userSettings);
            }
            break;
        }
      }
    });
  }

  ngOnInit(): void {
    this.settingsFacade.loadSettings();
  }

  onSubmit() {
    if (this.settingsForm.invalid) return;

    const settingsFormValue = this.settingsForm.getRawValue();
    const privacyFormValue = {
      isProfilePublic: !!settingsFormValue.privacy.isProfilePublic,
      showEmail: !!settingsFormValue.privacy.showEmail,
      showPhone: !!settingsFormValue.privacy.showPhone,
      allowGeolocation: !!settingsFormValue.privacy.allowGeolocation,
    };

    this.profileFacade.updateSettings(this.profile()!.id, privacyFormValue);

    this.settingsFacade.updateSettings({
      ...this.settings()!,
      theme: settingsFormValue.theme!,
      privacy: privacyFormValue,
    });
  }

  onCancel() {
    const current = this.settings();
    if (current) {
      this.settingsForm.reset({
        theme: current.theme,
        privacy: current.privacy,
      });
    }
  }

  onThemeChange(themeMode: ThemeType) {
    this.settingsForm.patchValue({ theme: themeMode });
    this.settingsFacade.applyThemeSettings({ ...this.settings(), theme: themeMode });
  }

  private updateForm(userSettings: SettingsProfileDto) {
    this.settingsForm.patchValue(
      {
        theme: this.settings().theme,
        privacy: {
          isProfilePublic: userSettings.isProfilePublic ?? false,
          showEmail: userSettings.showEmail,
          showPhone: userSettings.showPhone,
          allowGeolocation: userSettings.allowGeolocation,
        },
      },
      { emitEvent: false }
    );
  }
}
