import { Component, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, RouterModule } from '@angular/router';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { AuthService } from '../../../core/services/auth.service';
import { NotificationService } from '../../../core/services/notification.service';
import { SecurityValidators } from '../../../core/utils/security-validators';
import { InputSanitizer } from '../../../core/utils/input-sanitizer';

@Component({
  selector: 'app-digilocker-login',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
  ],
  templateUrl: './digilocker-login.component.html',
  styles: [
    `
      .login-form {
        display: flex;
        flex-direction: column;
        gap: 16px;
      }

      .back-link {
        display: flex;
        align-items: center;
        gap: 4px;
        color: rgba(0, 0, 0, 0.54);
        text-decoration: none;
        font-size: 0.875rem;
        margin-bottom: 8px;

        &:hover {
          color: #1976d2;
        }

        mat-icon {
          font-size: 18px;
          width: 18px;
          height: 18px;
        }
      }

      h2 {
        margin: 0 0 8px;
        font-size: 1.25rem;
        font-weight: 500;
        text-align: center;
      }

      .subtitle {
        margin: 0 0 24px;
        color: rgba(0, 0, 0, 0.54);
        font-size: 0.875rem;
        text-align: center;
      }

      .submit-button {
        margin-top: 8px;
        height: 48px;
      }
    `,
  ],
})
export class DigiLockerLoginComponent {
  private readonly fb = inject(FormBuilder);
  private readonly authService = inject(AuthService);
  private readonly router = inject(Router);
  private readonly notification = inject(NotificationService);

  readonly loading = signal(false);

  readonly form = this.fb.nonNullable.group({
    digilockerId: ['', [
      Validators.required,
      Validators.minLength(8),
      Validators.maxLength(30),
      SecurityValidators.digilockerId(),
      SecurityValidators.noXss(),
    ]],
    name: ['', [
      Validators.maxLength(100),
      SecurityValidators.safeText(100),
      SecurityValidators.noXss(),
    ]],
    email: ['', [
      Validators.email,
      Validators.maxLength(254),
      SecurityValidators.secureEmail(),
    ]],
    phone: ['', [
      Validators.maxLength(15),
      SecurityValidators.securePhone(),
    ]],
  });

  onSubmit(): void {
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }

    this.loading.set(true);
    const values = this.form.getRawValue();

    // Sanitize all inputs before sending
    const sanitizedDigilockerId = InputSanitizer.sanitizeAlphanumeric(values.digilockerId, '-');
    const sanitizedName = values.name ? InputSanitizer.sanitizeName(values.name) : undefined;
    const sanitizedEmail = values.email ? InputSanitizer.sanitizeEmail(values.email) : undefined;
    const sanitizedPhone = values.phone ? InputSanitizer.sanitizePhone(values.phone) : undefined;

    // Security check
    if (InputSanitizer.isMalicious(values.digilockerId) ||
        InputSanitizer.isMalicious(values.name || '') ||
        InputSanitizer.isMalicious(values.email || '')) {
      this.notification.error('Invalid input detected');
      this.loading.set(false);
      return;
    }

    this.authService
      .digiLockerLogin({
        digilockerId: sanitizedDigilockerId,
        name: sanitizedName,
        email: sanitizedEmail,
        phone: sanitizedPhone,
      })
      .subscribe({
        next: () => {
          this.notification.success('Login successful!');
          this.router.navigate(['/dashboard']);
        },
        error: (err) => {
          this.loading.set(false);
          this.notification.error('Login failed. Please try again.');
          console.error('Login error:', err);
        },
        complete: () => {
          this.loading.set(false);
        },
      });
  }
}
