import { Component, ChangeDetectionStrategy, signal, inject, OnInit, input } from '@angular/core';
import { RouterLink } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { EnrollmentService, NotificationService } from '@core/services';
import { Classmate, Student } from '@core/models';
import { LoadingSpinnerComponent, EmptyStateComponent } from '@shared/index';
import { InitialsPipe } from '@shared/pipes/initials.pipe';

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

      @if (loading()) {
        <app-loading-spinner message="Cargando compañeros..." />
      } @else if (!student()) {
        <app-empty-state
          icon="error"
          title="Estudiante no encontrado"
          description="El estudiante solicitado no existe"
        >
          <a routerLink="/students" class="btn btn-primary">Volver</a>
        </app-empty-state>
      } @else {
        <header class="page-header">
          <div>
            <h1>Compañeros de Clase</h1>
            <p class="page-subtitle">{{ student()?.name }}</p>
          </div>
          <a [routerLink]="['/enrollment', studentId()]" class="btn btn-secondary">
            <mat-icon>school</mat-icon>
            Ver Inscripción
          </a>
        </header>

        @if (classmates().length === 0) {
          <div class="card">
            <app-empty-state
              icon="group_off"
              title="Sin materias inscritas"
              description="Inscríbete en materias para ver a tus compañeros de clase"
            >
              <a [routerLink]="['/enrollment', studentId()]" class="btn btn-primary">
                <mat-icon>add</mat-icon>
                Inscribir Materias
              </a>
            </app-empty-state>
          </div>
        } @else {
          <div class="classmates-list">
            @for (item of classmates(); track item.subjectId) {
              <section class="classmates-section card">
                <h2 class="classmates-section-title">
                  <mat-icon>book</mat-icon>
                  {{ item.subjectName }}
                  <span class="classmates-count">{{ item.classmates.length }} {{ item.classmates.length === 1 ? 'compañero' : 'compañeros' }}</span>
                </h2>

                @if (item.classmates.length === 0) {
                  <div class="no-classmates">
                    <mat-icon>person_off</mat-icon>
                    <span>Aún no hay otros estudiantes en esta materia</span>
                  </div>
                } @else {
                  <div class="classmates-grid">
                    @for (classmate of item.classmates; track classmate.studentId) {
                      <div class="classmate-item">
                        <div class="classmate-item-avatar">
                          {{ classmate.name | initials }}
                        </div>
                        <span class="classmate-item-name">{{ classmate.name }}</span>
                      </div>
                    }
                  </div>
                }
              </section>
            }
          </div>
        }
      }
    </div>
  `,
  styles: [`
    .page {
      animation: fadeIn 0.3s ease;
    }

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

    .classmates-list {
      display: flex;
      flex-direction: column;
      gap: 1.5rem;
    }

    .classmates-section {
      padding: 1.5rem;
    }

    .classmates-section-title {
      display: flex;
      align-items: center;
      gap: 0.75rem;
      font-size: 1.125rem;
      font-weight: 600;
      margin-bottom: 1.25rem;
      padding-bottom: 1rem;
      border-bottom: 1px solid var(--border-light);
      color: var(--text-primary);

      mat-icon {
        color: var(--accent);
      }
    }

    .classmates-count {
      margin-left: auto;
      font-size: 0.8125rem;
      font-weight: 500;
      color: var(--text-secondary);
      background: var(--bg-tertiary);
      padding: 0.25rem 0.75rem;
      border-radius: 100px;
    }

    .classmates-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 0.75rem;
    }

    .classmate-item {
      display: flex;
      align-items: center;
      gap: 0.75rem;
      padding: 0.75rem 1rem;
      background: var(--bg-tertiary);
      border-radius: var(--radius-md);
      transition: all var(--transition);

      &:hover {
        background: var(--bg-primary);
      }
    }

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

    .classmate-item-name {
      font-size: 0.9375rem;
      font-weight: 500;
      color: var(--text-primary);
    }

    .no-classmates {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 0.75rem;
      padding: 2rem;
      color: var(--text-tertiary);
      font-size: 0.9375rem;

      mat-icon {
        font-size: 1.5rem;
        width: 1.5rem;
        height: 1.5rem;
      }
    }
  `],
})
export class ClassmatesPageComponent implements OnInit {
  studentId = input.required<string>();

  private enrollmentService = inject(EnrollmentService);
  private notification = inject(NotificationService);

  student = signal<Student | null>(null);
  classmates = signal<Classmate[]>([]);
  loading = signal(true);

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

  private loadData(): void {
    const id = parseInt(this.studentId(), 10);

    this.enrollmentService.getStudentWithEnrollments(id).subscribe({
      next: ({ data }) => {
        this.student.set(data);
      },
      error: () => {
        this.notification.error('Error al cargar el estudiante');
      },
    });

    this.enrollmentService.getClassmates(id).subscribe({
      next: ({ data, loading }) => {
        this.classmates.set(data);
        this.loading.set(loading);
      },
      error: () => {
        this.loading.set(false);
        this.notification.error('Error al cargar compañeros');
      },
    });
  }
}
