import { Component, signal, inject } from '@angular/core';
import { Router, 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';

@Component({
  selector: 'app-reset-password',
  standalone: true,
  imports: [ReactiveFormsModule, RouterLink, MatIconModule, MatButtonModule],
  template: `
    <div class="auth-container">
      <div class="auth-card">
        <div class="auth-header">
          <div class="logo">
            <mat-icon>lock_reset</mat-icon>
          </div>
          <h1>Recuperar Contrasena</h1>
          <p>Usa tu codigo de recuperacion</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="Tu nombre de usuario" [class.error]="showError('username')" />
            @if (showError('username')) {
              <span class="error-message">El usuario es requerido</span>
            }
          </div>

          <div class="form-group">
            <label for="recoveryCode">Codigo de Recuperacion</label>
            <input id="recoveryCode" type="text" class="input" formControlName="recoveryCode"
              placeholder="XXXX-XXXX-XXXX" [class.error]="showError('recoveryCode')" />
            @if (showError('recoveryCode')) {
              <span class="error-message">El codigo es requerido</span>
            }
          </div>

          <div class="form-group">
            <label for="newPassword">Nueva Contrasena</label>
            <input id="newPassword" type="password" class="input" formControlName="newPassword"
              placeholder="Minimo 6 caracteres" [class.error]="showError('newPassword')" />
            @if (showError('newPassword')) {
              <span class="error-message">Minimo 6 caracteres</span>
            }
          </div>

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

          @if (success()) {
            <div class="success-message">
              <mat-icon>check_circle</mat-icon>
              Contrasena actualizada correctamente
            </div>
          }

          <button type="submit" class="btn btn-primary btn-full"
            [disabled]="form.invalid || loading() || success()">
            @if (loading()) {
              <span class="btn-loading"></span>
              Actualizando...
            } @else {
              <mat-icon>lock_reset</mat-icon>
              Cambiar Contrasena
            }
          </button>
        </form>

        <div class="auth-footer">
          <p><a routerLink="/login">Volver a iniciar sesion</a></p>
        </div>
      </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, #f59e0b 0%, #d97706 100%);
      color: white; display: flex; align-items: center; justify-content: center;
      margin: 0 auto 1rem;
    }
    .logo mat-icon { font-size: 32px; width: 32px; height: 32px; }
    h1 { font-size: 1.5rem; font-weight: 600; margin: 0 0 0.5rem; color: #1a1a2e; }
    p { color: #6b7280; margin: 0; }
    .form-group { margin-bottom: 1.25rem; }
    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;
    }
    .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;
    }
    .success-message {
      display: flex; align-items: center; gap: 0.5rem; padding: 0.875rem 1rem;
      background: rgba(34, 197, 94, 0.1); border: 1px solid rgba(34, 197, 94, 0.2);
      border-radius: 0.5rem; color: #22c55e; 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); } }
    .auth-footer { text-align: center; margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid #e5e7eb; }
    .auth-footer a { color: #007AFF; text-decoration: none; font-weight: 500; }
  `],
})
export class ResetPasswordComponent {
  private fb = inject(FormBuilder);
  private authService = inject(AuthService);
  private notification = inject(NotificationService);
  private router = inject(Router);

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

  loading = signal(false);
  serverError = signal<string | null>(null);
  success = signal(false);

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

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

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

    const { username, recoveryCode, newPassword } = this.form.value;

    this.authService.resetPassword(username!, recoveryCode!, newPassword!).subscribe({
      next: (response) => {
        this.loading.set(false);
        if (response.success) {
          this.success.set(true);
          this.notification.success('Contrasena actualizada!');
          setTimeout(() => this.router.navigate(['/login']), 2000);
        } else {
          this.serverError.set(response.error ?? 'Error al resetear contrasena');
        }
      },
      error: () => {
        this.loading.set(false);
        this.serverError.set('Error de conexion con el servidor');
      },
    });
  }
}
