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-login',
  standalone: true,
  imports: [ReactiveFormsModule, RouterLink, MatIconModule, MatButtonModule],
  template: `
    <div class="auth-container">
      <div class="auth-card">
        <div class="auth-header">
          <div class="logo">S</div>
          <h1>Iniciar Sesion</h1>
          <p>Sistema de Gestion de Estudiantes</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="password">Contrasena</label>
            <input
              id="password"
              type="password"
              class="input"
              formControlName="password"
              placeholder="Tu contrasena"
              [class.error]="showError('password')"
            />
            @if (showError('password')) {
              <span class="error-message">La contrasena es requerida</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()"
          >
            @if (loading()) {
              <span class="btn-loading"></span>
              Iniciando...
            } @else {
              <mat-icon>login</mat-icon>
              Iniciar Sesion
            }
          </button>
        </form>

        <div class="auth-footer">
          <p>No tienes cuenta? <a routerLink="/register">Registrate</a></p>
          <p class="forgot-link"><a routerLink="/reset-password">Olvidaste tu contrasena?</a></p>
        </div>

        <div class="demo-hint" (click)="fillDemoCredentials()">
          <span class="demo-label">Demo</span>
          <span class="demo-credentials">admin · admin123</span>
        </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, #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: 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;
      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); }
    }

    .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;
    }

    .auth-footer a:hover {
      text-decoration: underline;
    }
    .forgot-link {
      margin-top: 0.5rem;
      font-size: 0.875rem;
    }

    .demo-hint {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 0.5rem;
      margin-top: 1.5rem;
      padding: 0.625rem 1rem;
      background: rgba(0, 0, 0, 0.02);
      border-radius: 0.5rem;
      cursor: pointer;
      transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
      animation: fadeIn 0.6s ease-out 0.3s both;
    }

    .demo-hint:hover {
      background: rgba(0, 0, 0, 0.04);
    }

    .demo-hint:active {
      transform: scale(0.98);
    }

    .demo-label {
      font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif;
      font-size: 0.6875rem;
      font-weight: 500;
      letter-spacing: 0.02em;
      text-transform: uppercase;
      color: #86868b;
      background: rgba(0, 0, 0, 0.05);
      padding: 0.125rem 0.375rem;
      border-radius: 0.25rem;
    }

    .demo-credentials {
      font-family: 'SF Mono', SFMono-Regular, ui-monospace, monospace;
      font-size: 0.75rem;
      font-weight: 400;
      letter-spacing: -0.01em;
      color: #86868b;
    }

    @keyframes fadeIn {
      from {
        opacity: 0;
        transform: translateY(4px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
  `],
})
export class LoginComponent {
  private fb = inject(FormBuilder);
  private authService = inject(AuthService);
  private notification = inject(NotificationService);
  private router = inject(Router);

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

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

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

  fillDemoCredentials(): void {
    this.form.patchValue({ username: 'admin', password: 'admin123' });
  }

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

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

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

    this.authService.login(username!, password!).subscribe({
      next: (response) => {
        this.loading.set(false);
        if (response.success) {
          this.notification.success('Bienvenido!');
          const redirectPath = response.user?.role === 'Admin' ? '/admin' : '/dashboard';
          this.router.navigate([redirectPath]);
        } else {
          this.serverError.set(response.error ?? 'Error al iniciar sesion');
        }
      },
      error: () => {
        this.loading.set(false);
        this.serverError.set('Error de conexion con el servidor');
      },
    });
  }
}
