import { Component, signal, inject, OnInit } from '@angular/core';
import { Router, ActivatedRoute, RouterLink } from '@angular/router';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { AuthService } from '@core/services/auth.service';
import { NotificationService } from '@core/services';

type ActivationStep = 'validating' | 'form' | 'recovery' | 'error';

@Component({
  selector: 'app-activate',
  standalone: true,
  imports: [ReactiveFormsModule, RouterLink, MatIconModule, MatButtonModule],
  template: `
    <div class="auth-container">
      <div class="auth-card">
        @switch (step()) {
          @case ('validating') {
            <div class="validating-section">
              <div class="loading-spinner"></div>
              <h1>Validando codigo...</h1>
              <p>Por favor espera mientras verificamos tu codigo de activacion</p>
            </div>
          }
          @case ('error') {
            <div class="error-section">
              <mat-icon class="error-icon">error</mat-icon>
              <h1>Codigo Invalido</h1>
              <p>{{ validationError() }}</p>
              <div class="error-actions">
                <a routerLink="/login" class="btn btn-outline">
                  <mat-icon>arrow_back</mat-icon>
                  Ir a Login
                </a>
              </div>
            </div>
          }
          @case ('recovery') {
            <div class="recovery-code-section">
              <div class="recovery-header">
                <mat-icon class="success-icon">check_circle</mat-icon>
                <h1>Cuenta Activada!</h1>
                <p>Guarda tu codigo de recuperacion</p>
              </div>

              <div class="recovery-warning">
                <mat-icon>warning</mat-icon>
                <span>Este codigo se muestra solo UNA vez. Guardalo en un lugar seguro.</span>
              </div>

              <div class="recovery-code-display">
                <span class="code">{{ recoveryCode() }}</span>
              </div>

              <p class="recovery-info">
                Usa este codigo para recuperar tu contrasena si la olvidas.
              </p>

              <button type="button" class="btn btn-primary btn-full" (click)="continueToLogin()">
                <mat-icon>login</mat-icon>
                Continuar al Login
              </button>
            </div>
          }
          @case ('form') {
            <div class="auth-header">
              <div class="logo">S</div>
              <h1>Activar Cuenta</h1>
              <p>Bienvenido, {{ studentName() }}</p>
            </div>

            <form [formGroup]="form" (ngSubmit)="onSubmit()">
              <div class="form-group">
                <label for="username">Usuario</label>
                <input
                  id="username"
                  type="text"
                  class="input"
                  formControlName="username"
                  placeholder="Elige un nombre de usuario"
                  [class.error]="showError('username')"
                />
                @if (showError('username')) {
                  <span class="error-message">
                    @if (form.get('username')?.errors?.['required']) {
                      El usuario es requerido
                    } @else if (form.get('username')?.errors?.['minlength']) {
                      Minimo 3 caracteres
                    }
                  </span>
                }
              </div>

              <div class="form-group">
                <label for="password">Contrasena</label>
                <input
                  id="password"
                  type="password"
                  class="input"
                  formControlName="password"
                  placeholder="Minimo 6 caracteres"
                  [class.error]="showError('password')"
                />
                @if (showError('password')) {
                  <span class="error-message">
                    @if (form.get('password')?.errors?.['required']) {
                      La contrasena es requerida
                    } @else if (form.get('password')?.errors?.['minlength']) {
                      Minimo 6 caracteres
                    }
                  </span>
                }
              </div>

              <div class="form-group">
                <label for="confirmPassword">Confirmar Contrasena</label>
                <input
                  id="confirmPassword"
                  type="password"
                  class="input"
                  formControlName="confirmPassword"
                  placeholder="Repite la contrasena"
                  [class.error]="showError('confirmPassword') || passwordMismatch()"
                />
                @if (showError('confirmPassword')) {
                  <span class="error-message">La confirmacion es requerida</span>
                }
                @if (passwordMismatch()) {
                  <span class="error-message">Las contrasenas no coinciden</span>
                }
              </div>

              @if (serverError()) {
                <div class="server-error">
                  <mat-icon>error</mat-icon>
                  {{ serverError() }}
                </div>
              }

              <button
                type="submit"
                class="btn btn-primary btn-full"
                [disabled]="form.invalid || loading() || passwordMismatch()"
              >
                @if (loading()) {
                  <span class="btn-loading"></span>
                  Activando...
                } @else {
                  <mat-icon>how_to_reg</mat-icon>
                  Activar Cuenta
                }
              </button>
            </form>
          }
        }
      </div>
    </div>
  `,
  styles: [`
    .auth-container {
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      padding: 1rem;
    }
    .auth-card {
      background: white;
      border-radius: 1rem;
      padding: 2.5rem;
      width: 100%;
      max-width: 400px;
      box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
    }
    .auth-header { text-align: center; margin-bottom: 2rem; }
    .logo {
      width: 64px; height: 64px; border-radius: 16px;
      background: linear-gradient(135deg, #007AFF 0%, #5856D6 100%);
      color: white; font-size: 2rem; font-weight: 700;
      display: flex; align-items: center; justify-content: center;
      margin: 0 auto 1rem;
    }
    h1 { font-size: 1.5rem; font-weight: 600; margin: 0 0 0.5rem; color: #1a1a2e; }
    p { color: #6b7280; margin: 0; }
    .form-group { margin-bottom: 1rem; }
    label { display: block; font-weight: 500; margin-bottom: 0.5rem; color: #374151; }
    .input {
      width: 100%; padding: 0.75rem 1rem; border: 1px solid #e5e7eb;
      border-radius: 0.5rem; font-size: 1rem;
      transition: border-color 0.2s, box-shadow 0.2s;
    }
    .input:focus {
      outline: none; border-color: #007AFF;
      box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
    }
    .input.error { border-color: #ef4444; }
    .error-message { color: #ef4444; font-size: 0.875rem; margin-top: 0.25rem; display: block; }
    .server-error {
      display: flex; align-items: center; gap: 0.5rem; padding: 0.875rem 1rem;
      background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.2);
      border-radius: 0.5rem; color: #ef4444; font-size: 0.875rem; margin-bottom: 1rem;
    }
    .btn-full { width: 100%; justify-content: center; }
    .btn-loading {
      width: 16px; height: 16px; border: 2px solid rgba(255, 255, 255, 0.3);
      border-top-color: white; border-radius: 50%; animation: spin 0.8s linear infinite;
    }
    @keyframes spin { to { transform: rotate(360deg); } }

    .validating-section, .error-section { text-align: center; padding: 2rem 0; }
    .loading-spinner {
      width: 48px; height: 48px; border: 3px solid #e5e7eb;
      border-top-color: #007AFF; border-radius: 50%;
      animation: spin 1s linear infinite; margin: 0 auto 1.5rem;
    }
    .error-icon { font-size: 48px; width: 48px; height: 48px; color: #ef4444; }
    .error-actions { margin-top: 1.5rem; }
    .btn-outline {
      display: inline-flex; align-items: center; gap: 0.5rem;
      padding: 0.75rem 1.5rem; border: 1px solid #e5e7eb;
      border-radius: 0.5rem; background: white; color: #374151;
      text-decoration: none; font-weight: 500;
    }
    .btn-outline:hover { background: #f9fafb; }

    .recovery-code-section { text-align: center; }
    .recovery-header { margin-bottom: 1.5rem; }
    .recovery-header h1 { margin: 0.5rem 0; color: #1a1a2e; }
    .recovery-header p { color: #6b7280; margin: 0; }
    .success-icon { font-size: 48px; width: 48px; height: 48px; color: #22c55e; }
    .recovery-warning {
      display: flex; align-items: center; gap: 0.5rem; padding: 0.875rem;
      background: rgba(245, 158, 11, 0.1); border: 1px solid rgba(245, 158, 11, 0.2);
      border-radius: 0.5rem; color: #d97706; font-size: 0.875rem;
      margin-bottom: 1rem; text-align: left;
    }
    .recovery-code-display {
      background: #1a1a2e; padding: 1.5rem; border-radius: 0.75rem; margin-bottom: 1rem;
    }
    .recovery-code-display .code {
      font-family: monospace; font-size: 1.5rem; font-weight: 700;
      color: #22c55e; letter-spacing: 0.1em;
    }
    .recovery-info { font-size: 0.875rem; color: #6b7280; margin-bottom: 1.5rem; }
  `],
})
export class ActivateComponent implements OnInit {
  private fb = inject(FormBuilder);
  private authService = inject(AuthService);
  private notification = inject(NotificationService);
  private router = inject(Router);
  private route = inject(ActivatedRoute);

  step = signal<ActivationStep>('validating');
  studentName = signal<string>('');
  activationCode = signal<string>('');
  validationError = signal<string>('');
  serverError = signal<string | null>(null);
  recoveryCode = signal<string | null>(null);
  loading = signal(false);

  form = this.fb.group({
    username: ['', [Validators.required, Validators.minLength(3)]],
    password: ['', [Validators.required, Validators.minLength(6)]],
    confirmPassword: ['', [Validators.required]],
  });

  ngOnInit(): void {
    const code = this.route.snapshot.queryParamMap.get('code');
    if (!code) {
      this.step.set('error');
      this.validationError.set('No se proporciono codigo de activacion');
      return;
    }

    this.activationCode.set(code);
    this.validateCode(code);
  }

  private validateCode(code: string): void {
    this.authService.validateActivationCode(code).subscribe({
      next: (result) => {
        if (result.isValid && result.studentName) {
          this.studentName.set(result.studentName);
          this.step.set('form');
        } else {
          this.step.set('error');
          this.validationError.set(result.error ?? 'Codigo de activacion invalido');
        }
      },
      error: () => {
        this.step.set('error');
        this.validationError.set('Error al validar el codigo');
      },
    });
  }

  showError(field: string): boolean {
    const control = this.form.get(field);
    return !!(control?.invalid && control?.touched);
  }

  passwordMismatch(): boolean {
    const password = this.form.get('password')?.value;
    const confirm = this.form.get('confirmPassword')?.value;
    return !!(confirm && password !== confirm);
  }

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

    this.loading.set(true);
    this.serverError.set(null);

    const { username, password } = this.form.value;

    this.authService.activateAccount(this.activationCode(), username!, password!).subscribe({
      next: (response) => {
        this.loading.set(false);
        if (response.success) {
          if (response.recoveryCode) {
            this.recoveryCode.set(response.recoveryCode);
            this.step.set('recovery');
          } else {
            this.notification.success('Cuenta activada exitosamente!');
            this.router.navigate(['/login']);
          }
        } else {
          this.serverError.set(response.error ?? 'Error al activar la cuenta');
        }
      },
      error: () => {
        this.loading.set(false);
        this.serverError.set('Error de conexion con el servidor');
      },
    });
  }

  continueToLogin(): void {
    this.notification.success('Cuenta activada! Ahora puedes iniciar sesion');
    this.router.navigate(['/login']);
  }
}
