import { Component, ChangeDetectionStrategy, signal, inject, OnInit } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog';
import { MatTooltipModule } from '@angular/material/tooltip';
import { StudentService, NotificationService, ErrorHandlerService } from '@core/services';
import { Student } from '@core/models';
import { LoadingSpinnerComponent, EmptyStateComponent, ConfirmDialogComponent, ConfirmDialogData } from '@shared/index';
import { CreditsPipe } from '@shared/pipes/credits.pipe';

@Component({
  selector: 'app-student-list',
  standalone: true,
  imports: [
    RouterLink, MatIconModule, MatButtonModule, MatTooltipModule,
    LoadingSpinnerComponent, EmptyStateComponent, CreditsPipe
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="page">
      <header class="page-header">
        <div>
          <h1>Estudiantes</h1>
          <p class="page-subtitle">Gestiona el registro de estudiantes</p>
        </div>
        <a routerLink="/students/new" class="btn btn-primary" data-testid="btn-new-student">
          <mat-icon>add</mat-icon>
          Nuevo Estudiante
        </a>
      </header>

      @if (loading()) {
        <app-loading-spinner message="Cargando estudiantes..." />
      } @else if (students().length === 0) {
        <div class="card">
          <app-empty-state
            icon="school"
            title="Sin estudiantes registrados"
            description="Comienza agregando tu primer estudiante al sistema"
          >
            <a routerLink="/students/new" class="btn btn-primary">
              <mat-icon>add</mat-icon>
              Agregar Estudiante
            </a>
          </app-empty-state>
        </div>
      } @else {
        <div class="card">
          <div class="table-container">
            <table class="data-table" data-testid="students-table">
              <thead>
                <tr>
                  <th>Estudiante</th>
                  <th>Email</th>
                  <th>Créditos</th>
                  <th>Materias</th>
                  <th>Acciones</th>
                </tr>
              </thead>
              <tbody>
                @for (student of students(); track student.id) {
                  <tr>
                    <td>
                      <div class="student-cell">
                        <div class="avatar">{{ getInitials(student.name) }}</div>
                        <span class="student-name">{{ student.name }}</span>
                      </div>
                    </td>
                    <td class="email-cell">{{ student.email }}</td>
                    <td>
                      <div class="credits-cell">
                        <div class="progress-bar">
                          <div
                            class="progress-bar-fill"
                            [style.width.%]="(student.totalCredits / 9) * 100"
                          ></div>
                        </div>
                        <span class="credits-text">{{ student.totalCredits | credits }}</span>
                      </div>
                    </td>
                    <td>
                      <span class="badge badge-info">{{ student.enrollments.length }}/3</span>
                    </td>
                    <td>
                      <div class="actions">
                        <button
                          class="btn btn-icon btn-ghost"
                          [routerLink]="['/students', student.id, 'edit']"
                          matTooltip="Editar"
                        >
                          <mat-icon>edit</mat-icon>
                        </button>
                        <button
                          class="btn btn-icon btn-ghost"
                          [routerLink]="['/enrollment', student.id]"
                          matTooltip="Inscribir materias"
                          data-testid="btn-enroll"
                        >
                          <mat-icon>school</mat-icon>
                        </button>
                        <button
                          class="btn btn-icon btn-ghost"
                          [routerLink]="['/classmates', student.id]"
                          matTooltip="Ver compañeros"
                          [disabled]="student.enrollments.length === 0"
                          data-testid="btn-classmates"
                        >
                          <mat-icon>group</mat-icon>
                        </button>
                        <button
                          class="btn btn-icon btn-danger"
                          (click)="confirmDelete(student)"
                          matTooltip="Eliminar"
                        >
                          <mat-icon>delete</mat-icon>
                        </button>
                      </div>
                    </td>
                  </tr>
                }
              </tbody>
            </table>
          </div>
        </div>
      }
    </div>
  `,
  styles: [`
    .page {
      animation: fadeIn 0.3s ease;
    }

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

    .table-container {
      overflow-x: auto;
    }

    .student-cell {
      display: flex;
      align-items: center;
      gap: 0.75rem;
    }

    .avatar {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: linear-gradient(135deg, #007AFF 0%, #5856D6 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 0.8125rem;
      font-weight: 600;
      flex-shrink: 0;
    }

    .student-name {
      font-weight: 500;
    }

    .email-cell {
      color: var(--text-secondary);
    }

    .credits-cell {
      display: flex;
      flex-direction: column;
      gap: 0.375rem;
      min-width: 120px;
    }

    .credits-text {
      font-size: 0.8125rem;
      color: var(--text-secondary);
    }

    .actions {
      display: flex;
      gap: 0.25rem;
    }

    @media (max-width: 768px) {
      .email-cell {
        display: none;
      }
    }
  `],
})
export class StudentListComponent implements OnInit {
  private studentService = inject(StudentService);
  private notification = inject(NotificationService);
  private errorHandler = inject(ErrorHandlerService);
  private dialog = inject(MatDialog);
  private router = inject(Router);

  students = signal<Student[]>([]);
  loading = signal(true);

  ngOnInit(): void {
    this.loadStudents();
  }

  private loadStudents(): void {
    this.studentService.getStudents().subscribe({
      next: ({ data, loading }) => {
        this.students.set(data);
        this.loading.set(loading);
      },
      error: (error) => {
        this.loading.set(false);
        this.errorHandler.handle(error, 'StudentList.cargar');
      },
    });
  }

  getInitials(name: string): string {
    const parts = name.trim().split(' ');
    if (parts.length === 1) return parts[0].charAt(0).toUpperCase();
    return (parts[0].charAt(0) + parts[parts.length - 1].charAt(0)).toUpperCase();
  }

  confirmDelete(student: Student): void {
    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      data: {
        title: 'Eliminar estudiante',
        message: `¿Estás seguro de eliminar a "${student.name}"? Esta acción no se puede deshacer.`,
        confirmText: 'Eliminar',
        cancelText: 'Cancelar',
        type: 'danger',
      } as ConfirmDialogData,
    });

    dialogRef.afterClosed().subscribe((confirmed) => {
      if (confirmed) {
        this.deleteStudent(student.id);
      }
    });
  }

  private deleteStudent(id: number): void {
    this.studentService.deleteStudent(id).subscribe({
      next: (result) => {
        if (result.success) {
          this.notification.success('Estudiante eliminado correctamente');
        } else if (result.errors?.length) {
          this.notification.error(result.errors.join('. '));
        } else {
          this.notification.error('No se pudo eliminar el estudiante');
        }
      },
      error: (error) => this.errorHandler.handle(error, 'StudentList.eliminar'),
    });
  }
}
