import { Component, ChangeDetectionStrategy, signal, inject, input, effect } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { StudentService, NotificationService, ErrorHandlerService } from '@core/services';
import { LoadingSpinnerComponent } from '@shared/index';
import { CreateStudentWithActivationPayload } from '@core/models';

@Component({
  selector: 'app-student-form',
  standalone: true,
  imports: [
    RouterLink, ReactiveFormsModule, MatIconModule, MatButtonModule,
    MatFormFieldModule, MatInputModule, LoadingSpinnerComponent
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="page">
      <a routerLink="/students" class="back-link">
        <mat-icon>arrow_back</mat-icon>
        Volver a estudiantes
      </a>

      <header class="page-header">
        <div>
          <h1>{{ isEditing() ? 'Editar Estudiante' : 'Nuevo Estudiante' }}</h1>
          <p class="page-subtitle">
            {{ isEditing() ? 'Modifica los datos del estudiante' : 'Registra un nuevo estudiante en el sistema' }}
          </p>
        </div>
      </header>

      @if (loadingStudent()) {
        <app-loading-spinner message="Cargando datos..." />
      } @else {
        <div class="card form-card">
          <form [formGroup]="form" (ngSubmit)="onSubmit()">
            <div class="form-group">
              <label for="name">Nombre completo</label>
              <input
                id="name"
                type="text"
                class="input"
                formControlName="name"
                placeholder="Ej: Juan Perez Garcia"
                [class.error]="showError('name')"
                data-testid="input-name"
              >
              @if (showError('name')) {
                <span class="error-message">
                  @if (form.get('name')?.errors?.['required']) {
                    El nombre es requerido
                  } @else if (form.get('name')?.errors?.['minlength']) {
                    El nombre debe tener al menos 3 caracteres
                  }
                </span>
              }
            </div>

            <div class="form-group">
              <label for="email">Correo electronico</label>
              <input
                id="email"
                type="email"
                class="input"
                formControlName="email"
                placeholder="Ej: juan.perez&#64;ejemplo.com"
                [class.error]="showError('email')"
                data-testid="input-email"
              >
              @if (showError('email')) {
                <span class="error-message">
                  @if (form.get('email')?.errors?.['required']) {
                    El email es requerido
                  } @else if (form.get('email')?.errors?.['email']) {
                    Ingresa un email valido
                  }
                </span>
              }
            </div>

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

            <div class="form-actions">
              <a routerLink="/students" class="btn btn-secondary">Cancelar</a>
              <button
                type="submit"
                class="btn btn-primary"
                [disabled]="form.invalid || saving()"
                data-testid="btn-submit"
              >
                @if (saving()) {
                  <span class="btn-loading"></span>
                  Guardando...
                } @else {
                  <mat-icon>save</mat-icon>
                  {{ isEditing() ? 'Guardar Cambios' : 'Crear Estudiante' }}
                }
              </button>
            </div>
          </form>
        </div>
      }
    </div>

    @if (showActivationModal()) {
      <div class="modal-overlay" (click)="closeModal()">
        <div class="modal-content" (click)="$event.stopPropagation()">
          <div class="modal-header">
            <mat-icon class="success-icon">check_circle</mat-icon>
            <h2>Estudiante Creado!</h2>
            <p>Comparte el codigo de activacion con el estudiante</p>
          </div>

          <div class="activation-info">
            <div class="info-row">
              <span class="label">Estudiante:</span>
              <span class="value">{{ activationData()?.student?.name }}</span>
            </div>
            <div class="info-row">
              <span class="label">Email:</span>
              <span class="value">{{ activationData()?.student?.email }}</span>
            </div>
          </div>

          <div class="activation-code-section">
            <label>Codigo de Activacion</label>
            <div class="code-display">
              <code>{{ activationData()?.activationCode }}</code>
              <button type="button" class="copy-btn" (click)="copyCode()">
                <mat-icon>content_copy</mat-icon>
              </button>
            </div>
          </div>

          <div class="activation-url-section">
            <label>URL de Activacion</label>
            <div class="url-display">
              <code>{{ activationData()?.activationUrl }}</code>
              <button type="button" class="copy-btn" (click)="copyUrl()">
                <mat-icon>content_copy</mat-icon>
              </button>
            </div>
          </div>

          <div class="expiration-warning">
            <mat-icon>schedule</mat-icon>
            <span>Este codigo expira el {{ formatExpiration(activationData()?.expiresAt) }}</span>
          </div>

          <div class="modal-actions">
            <button type="button" class="btn btn-primary" (click)="closeModal()">
              <mat-icon>done</mat-icon>
              Entendido
            </button>
          </div>
        </div>
      </div>
    }
  `,
  styles: [`
    .page {
      animation: fadeIn 0.3s ease;
      max-width: 560px;
    }

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

    .form-card {
      padding: 2rem;
    }

    .form-actions {
      display: flex;
      justify-content: flex-end;
      gap: 0.75rem;
      margin-top: 2rem;
      padding-top: 1.5rem;
      border-top: 1px solid var(--border-light);
    }

    .server-error {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.875rem 1rem;
      background: rgba(255, 59, 48, 0.08);
      border: 1px solid rgba(255, 59, 48, 0.2);
      border-radius: var(--radius-md);
      color: var(--error);
      font-size: 0.875rem;
      margin-bottom: 1rem;

      mat-icon {
        font-size: 1.125rem;
        width: 1.125rem;
        height: 1.125rem;
      }
    }

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

    /* Modal Styles */
    .modal-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
      animation: fadeIn 0.2s ease;
    }

    .modal-content {
      background: white;
      border-radius: 1rem;
      padding: 2rem;
      width: 100%;
      max-width: 480px;
      box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
      animation: slideUp 0.3s ease;
    }

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

    .modal-header {
      text-align: center;
      margin-bottom: 1.5rem;
    }

    .modal-header h2 {
      font-size: 1.5rem;
      font-weight: 600;
      margin: 0.5rem 0;
      color: #1a1a2e;
    }

    .modal-header p {
      color: #6b7280;
      margin: 0;
    }

    .success-icon {
      font-size: 48px;
      width: 48px;
      height: 48px;
      color: #22c55e;
    }

    .activation-info {
      background: #f9fafb;
      border-radius: 0.5rem;
      padding: 1rem;
      margin-bottom: 1.5rem;
    }

    .info-row {
      display: flex;
      justify-content: space-between;
      padding: 0.25rem 0;
    }

    .info-row .label {
      color: #6b7280;
      font-size: 0.875rem;
    }

    .info-row .value {
      font-weight: 500;
      color: #1a1a2e;
    }

    .activation-code-section,
    .activation-url-section {
      margin-bottom: 1rem;
    }

    .activation-code-section label,
    .activation-url-section label {
      display: block;
      font-size: 0.875rem;
      font-weight: 500;
      color: #374151;
      margin-bottom: 0.5rem;
    }

    .code-display,
    .url-display {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      background: #1a1a2e;
      border-radius: 0.5rem;
      padding: 0.75rem 1rem;
    }

    .code-display code,
    .url-display code {
      flex: 1;
      font-family: monospace;
      font-size: 1.125rem;
      font-weight: 600;
      color: #22c55e;
      letter-spacing: 0.05em;
      word-break: break-all;
    }

    .url-display code {
      font-size: 0.75rem;
    }

    .copy-btn {
      background: transparent;
      border: none;
      color: #9ca3af;
      cursor: pointer;
      padding: 0.25rem;
      display: flex;
      align-items: center;
      transition: color 0.2s;
    }

    .copy-btn:hover {
      color: white;
    }

    .expiration-warning {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.75rem 1rem;
      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: 1.5rem;
    }

    .modal-actions {
      display: flex;
      justify-content: center;
    }
  `],
})
export class StudentFormComponent {
  id = input<string>();

  private fb = inject(FormBuilder);
  private router = inject(Router);
  private studentService = inject(StudentService);
  private notification = inject(NotificationService);
  private errorHandler = inject(ErrorHandlerService);

  form: FormGroup = this.fb.group({
    name: ['', [Validators.required, Validators.minLength(3)]],
    email: ['', [Validators.required, Validators.email]],
  });

  isEditing = signal(false);
  loadingStudent = signal(false);
  saving = signal(false);
  serverError = signal<string | null>(null);
  showActivationModal = signal(false);
  activationData = signal<CreateStudentWithActivationPayload | null>(null);

  constructor() {
    // Use effect to react when route param 'id' becomes available
    effect(() => {
      const studentId = this.id();
      if (studentId && !this.isEditing()) {
        this.isEditing.set(true);
        this.loadStudent(parseInt(studentId, 10));
      }
    });
  }

  private loadStudent(id: number): void {
    this.loadingStudent.set(true);
    this.studentService.getStudent(id).subscribe({
      next: ({ data }) => {
        this.loadingStudent.set(false);
        if (data) {
          this.form.patchValue({ name: data.name, email: data.email });
        } else {
          this.notification.error('Estudiante no encontrado');
          this.router.navigate(['/students']);
        }
      },
      error: (error) => {
        this.loadingStudent.set(false);
        this.errorHandler.handle(error, 'StudentForm.cargar');
        this.router.navigate(['/students']);
      },
    });
  }

  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.saving.set(true);
    this.serverError.set(null);

    const studentId = this.id();

    if (studentId) {
      // Update existing student
      this.studentService.updateStudent(parseInt(studentId, 10), this.form.value).subscribe({
        next: (result) => {
          this.saving.set(false);
          if (result.student) {
            this.notification.success('Estudiante actualizado correctamente');
            this.router.navigate(['/students']);
          } else if (result.errors?.length) {
            this.serverError.set(result.errors.join('. '));
          } else {
            this.serverError.set('No se pudo actualizar el estudiante. Intenta nuevamente.');
          }
        },
        error: (error) => {
          this.saving.set(false);
          const errorInfo = this.errorHandler.handle(error, 'StudentForm.actualizar');
          this.serverError.set(errorInfo.userMessage);
        },
      });
    } else {
      // Create new student - show activation modal
      this.studentService.createStudent(this.form.value).subscribe({
        next: (result) => {
          this.saving.set(false);
          if (result.student && result.activationCode) {
            this.activationData.set(result);
            this.showActivationModal.set(true);
          } else if (result.errors?.length) {
            this.serverError.set(result.errors.join('. '));
          } else {
            this.serverError.set('No se pudo crear el estudiante. Intenta nuevamente.');
          }
        },
        error: (error) => {
          this.saving.set(false);
          const errorInfo = this.errorHandler.handle(error, 'StudentForm.crear');
          this.serverError.set(errorInfo.userMessage);
        },
      });
    }
  }

  copyCode(): void {
    const code = this.activationData()?.activationCode;
    if (code) {
      navigator.clipboard.writeText(code);
      this.notification.success('Codigo copiado al portapapeles');
    }
  }

  copyUrl(): void {
    const url = this.activationData()?.activationUrl;
    if (url) {
      navigator.clipboard.writeText(url);
      this.notification.success('URL copiada al portapapeles');
    }
  }

  formatExpiration(expiresAt?: string): string {
    if (!expiresAt) return '';
    const date = new Date(expiresAt);
    return date.toLocaleString('es-CO', {
      dateStyle: 'medium',
      timeStyle: 'short',
    });
  }

  closeModal(): void {
    this.showActivationModal.set(false);
    this.router.navigate(['/students']);
  }
}
