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-department-login',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
  ],
  templateUrl: './department-login.component.html',
  styles: [
    `
      // =============================================================================
      // DEPARTMENT LOGIN - DBIM Compliant
      // =============================================================================

      :host {
        display: block;
        animation: fadeIn 0.3s ease-out;
      }

      @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
      }

      .back-link {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        color: var(--dbim-grey-2, #8E8E8E);
        text-decoration: none;
        font-size: 13px;
        font-weight: 500;
        margin-bottom: 24px;
        padding: 8px 12px;
        border-radius: 8px;
        transition: all 0.2s ease;

        &:hover {
          color: var(--dbim-blue-dark, #1D0A69);
          background: var(--dbim-linen, #EBEAEA);
        }

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

      .login-header {
        text-align: center;
        margin-bottom: 32px;
      }

      .header-icon {
        width: 64px;
        height: 64px;
        border-radius: 16px;
        background: linear-gradient(135deg, var(--dbim-blue-dark, #1D0A69) 0%, #6366F1 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 16px;
        box-shadow: 0 8px 24px rgba(99, 102, 241, 0.3);

        mat-icon {
          font-size: 32px;
          width: 32px;
          height: 32px;
          color: white;
        }
      }

      h2 {
        margin: 0 0 8px;
        font-size: 24px;
        font-weight: 700;
        color: var(--dbim-brown, #150202);
      }

      .login-subtitle {
        font-size: 14px;
        color: var(--dbim-grey-2, #8E8E8E);
        margin: 0;
      }

      .login-form {
        display: flex;
        flex-direction: column;
        gap: 20px;
      }

      .form-field-wrapper {
        position: relative;
      }

      .field-icon {
        position: absolute;
        left: 16px;
        top: 50%;
        transform: translateY(-50%);
        color: var(--dbim-grey-2, #8E8E8E);
        z-index: 1;
        pointer-events: none;

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

      mat-form-field {
        width: 100%;

        ::ng-deep {
          .mat-mdc-text-field-wrapper {
            background: var(--dbim-linen, #EBEAEA);
            border-radius: 12px;
          }

          .mdc-notched-outline__leading,
          .mdc-notched-outline__notch,
          .mdc-notched-outline__trailing {
            border-color: transparent !important;
          }

          .mat-mdc-form-field-focus-overlay {
            background-color: transparent;
          }

          &.mat-focused {
            .mat-mdc-text-field-wrapper {
              background: white;
              box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
            }
          }

          .mat-mdc-form-field-error-wrapper {
            padding: 4px 0 0;
          }
        }
      }

      .submit-button {
        height: 52px;
        border-radius: 12px;
        font-size: 15px;
        font-weight: 600;
        letter-spacing: 0.02em;
        background: linear-gradient(135deg, var(--dbim-blue-dark, #1D0A69) 0%, #6366F1 100%);
        box-shadow: 0 4px 16px rgba(99, 102, 241, 0.3);
        transition: all 0.2s ease;

        &:hover:not(:disabled) {
          transform: translateY(-2px);
          box-shadow: 0 6px 20px rgba(99, 102, 241, 0.4);
        }

        &:disabled {
          opacity: 0.7;
        }

        mat-spinner {
          margin: 0 auto;
        }
      }

      .password-toggle {
        cursor: pointer;
        color: var(--dbim-grey-2, #8E8E8E);
        transition: color 0.2s ease;

        &:hover {
          color: var(--dbim-blue-dark, #1D0A69);
        }
      }

      .demo-credentials {
        margin-top: 24px;
        padding: 16px;
        background: rgba(13, 110, 253, 0.05);
        border-radius: 12px;
        border: 1px solid rgba(13, 110, 253, 0.1);
      }

      .demo-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 13px;
        font-weight: 600;
        color: var(--dbim-info, #0D6EFD);
        margin-bottom: 12px;

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

      .demo-list {
        list-style: none;
        padding: 0;
        margin: 0;
        display: flex;
        flex-direction: column;
        gap: 8px;
      }

      .demo-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        padding: 8px 12px;
        background: white;
        border-radius: 8px;

        .dept-name {
          font-weight: 500;
          color: var(--dbim-brown, #150202);
        }

        .dept-code {
          font-family: 'Roboto Mono', monospace;
          color: var(--dbim-grey-3, #606060);
        }
      }
    `,
  ],
})
export class DepartmentLoginComponent {
  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 hidePassword = signal(true);

  readonly form = this.fb.nonNullable.group({
    departmentCode: ['', [
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(30),
      SecurityValidators.departmentCode(),
      SecurityValidators.noXss(),
    ]],
    apiKey: ['', [
      Validators.required,
      Validators.minLength(16),
      Validators.maxLength(256),
      SecurityValidators.apiKey(),
      SecurityValidators.noXss(),
    ]],
  });

  togglePasswordVisibility(): void {
    this.hidePassword.update((v) => !v);
  }

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

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

    // Sanitize inputs before sending
    const departmentCode = InputSanitizer.sanitizeAlphanumeric(rawValues.departmentCode, '_');
    const apiKey = rawValues.apiKey.trim(); // Only trim API key, don't modify

    // Additional security check
    if (InputSanitizer.isMalicious(departmentCode) || InputSanitizer.isMalicious(apiKey)) {
      this.notification.error('Invalid input detected');
      this.loading.set(false);
      return;
    }

    this.authService.departmentLogin({ departmentCode, apiKey }).subscribe({
      next: () => {
        this.notification.success('Login successful!');
        this.router.navigate(['/dashboard']);
      },
      error: (err) => {
        this.loading.set(false);
      },
      complete: () => {
        this.loading.set(false);
      },
    });
  }
}
