import { Component, inject, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '@core/services/auth.service';
import { AppLogo } from '@app/components/app-logo';
import { PasswordStrengthBar } from '@app/components/password-strength-bar';
import { appName, credits, currentYear } from '@/app/constants';

@Component({
  selector: 'app-sign-in',
  standalone: true,
  imports: [FormsModule, CommonModule, AppLogo, PasswordStrengthBar],
  template: `
    <div class="auth-box overflow-hidden align-items-center d-flex">
      <div class="container">
        <div class="row justify-content-center">
          <div class="col-xxl-4 col-md-6 col-sm-8">
            <div class="card">
              <div class="card-body">
                <div class="auth-brand mb-4">
                  <app-app-logo />
                  <p class="text-muted w-lg-75 mt-3">
                    Let's get you signed in. Enter your username and password to continue.
                  </p>
                </div>

                <form #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm)" novalidate>
                  <div class="mb-3">
                    <label for="username" class="form-label">
                      Username <span class="text-danger">*</span>
                    </label>
                    <input
                      type="text"
                      id="username"
                      name="username"
                      class="form-control"
                      placeholder="Enter username"
                      required
                      [(ngModel)]="username"
                      #usernameCtrl="ngModel"
                      [class.is-invalid]="usernameCtrl.invalid && usernameCtrl.touched"
                    />
                    <div class="invalid-feedback">
                      Username is required
                    </div>
                  </div>

                  <div class="mb-3">
                    <label for="password" class="form-label">
                      Password <span class="text-danger">*</span>
                    </label>
                    <input
                      type="password"
                      id="password"
                      name="password"
                      class="form-control"
                      placeholder="••••••••"
                      required
                      [(ngModel)]="password"
                      #passwordCtrl="ngModel"
                      [class.is-invalid]="passwordCtrl.invalid && passwordCtrl.touched"
                    />
                    <div class="invalid-feedback">
                      Password is required
                    </div>

                    <!-- Password strength bar -->
                    <app-password-strength-bar [password]="password || ''"></app-password-strength-bar>
                  </div>
                  
                  <!-- Server-side error message -->
                  <div *ngIf="errorMessage" 
                       id="error-message"
                       class="alert alert-danger mt-3" 
                       role="alert"
                       tabindex="-1">
                    <i class="ri-error-warning-line me-2"></i>
                    {{ errorMessage }}
                  </div>

                  <div class="d-flex justify-content-between align-items-center mb-3">
                    <div class="form-check">
                      <input
                        type="checkbox"
                        id="rememberMe"
                        class="form-check-input"
                        [(ngModel)]="rememberMe"
                        name="rememberMe"
                      />
                      <label class="form-check-label" for="rememberMe">
                        Keep me signed in
                      </label>
                    </div>
                    <a
                      routerLink="/auth/reset-password"
                      class="text-decoration-underline link-offset-3 text-muted"
                    >
                      Forgot Password?
                    </a>
                  </div>

                  <div class="d-grid">
                    <button
                      type="submit"
                      class="btn btn-primary fw-semibold py-2"
                      [disabled]="loginForm.invalid || loading"
                    >
                      {{ loading ? 'Signing In...' : 'Sign In' }}
                    </button>
                  </div>

                </form>

              </div>
            </div>

            <p class="text-center text-muted mt-4 mb-0">
              © {{ currentYear }} {{ appName }}. Tous droits réservés. — Développé par
              <span class="fw-semibold">{{ credits.name }}</span>
            </p>
          </div>
        </div>
      </div>
    </div>
  `,
})
export class SignIn {
  protected readonly appName = appName;
  protected readonly currentYear = currentYear;
  protected readonly credits = credits;

  private authService = inject(AuthService);
  private router = inject(Router);
  private cdRef = inject(ChangeDetectorRef);

  username: string = '';
  password: string = '';
  rememberMe: boolean = false;
  loading: boolean = false;
  errorMessage: string | null = null;

  onSubmit(form: NgForm) {
    if (form.invalid) {
      form.control.markAllAsTouched();
      return;
    }

    this.loading = true;
    this.errorMessage = null;

    this.authService.login(this.username, this.password).subscribe({
      next: (res) => {
        this.router.navigate(['/dcb-dashboard']);
        this.loading = false;
      },
      error: (err) => {
        this.errorMessage = err.error?.message || 'Login failed';
        this.loading = false;
        
        // Forcer la mise à jour de la vue
        this.cdRef.detectChanges();
        
        // Scroll et focus sur l'erreur
        this.scrollToError();
      },
    });
  }

  private scrollToError() {
    setTimeout(() => {
      const errorElement = document.getElementById('error-message');
      if (errorElement) {
        errorElement.scrollIntoView({ 
          behavior: 'smooth', 
          block: 'center' 
        });
        errorElement.focus();
      }
    }, 100);
  }
}