import { Component, inject, signal, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { DatePipe } from '@angular/common';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzMessageService } from 'ng-zorro-antd/message';
import { EnrollmentService } from '../../services/enrollment.service';
import { CourseService } from '../../services/course.service';
import { AuthService } from '../../services/auth.service';
import { Course, EnrollmentWithProgress } from '../../models/types';
import { BottomNav } from '../../components/bottom-nav/bottom-nav';
import { forkJoin, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Component({
  selector: 'app-my-courses',
  imports: [NzIconModule, BottomNav, DatePipe],
  providers: [NzMessageService],
  templateUrl: './my-courses.html',
  styleUrl: './my-courses.css'
})
export class MyCoursesPage implements OnInit {
  private readonly enrollmentService = inject(EnrollmentService);
  private readonly courseService = inject(CourseService);
  private readonly authService = inject(AuthService);
  private readonly router = inject(Router);
  private readonly message = inject(NzMessageService);

  enrollments = signal<EnrollmentWithProgress[]>([]);
  createdCourses = signal<Course[]>([]);
  loading = signal(false);

  get currentUser() {
    return this.authService.currentUser();
  }

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

  loadAll(): void {
    const user = this.currentUser;
    if (!user) return;
    this.loading.set(true);

    forkJoin({
      created: this.courseService.getMyCourses(user.userId).pipe(catchError(() => of([]))),
      enrollments: this.enrollmentService.getEnrollments(user.userId).pipe(catchError(() => of([])))
    }).subscribe({
      next: ({ created, enrollments }) => {
        this.createdCourses.set(created);

        if (enrollments.length === 0) {
          this.enrollments.set([]);
          this.loading.set(false);
          return;
        }

        const progressRequests = enrollments.map((e: any) =>
          this.enrollmentService.getCourseProgress(e.courseId, user.userId).pipe(
            catchError(() => of(undefined))
          )
        );

        forkJoin(progressRequests).subscribe({
          next: (progressList) => {
            const enriched: EnrollmentWithProgress[] = enrollments.map((e: any, i: number) => ({
              ...e,
              progress: progressList[i] ?? undefined
            }));
            this.enrollments.set(enriched);
            this.loading.set(false);
          },
          error: () => {
            this.enrollments.set(enrollments);
            this.loading.set(false);
          }
        });
      },
      error: () => {
        this.loading.set(false);
        this.message.error('Impossible de charger vos cours');
      }
    });
  }

  openCourse(enrollment: EnrollmentWithProgress): void {
    this.router.navigate(['/courses', enrollment.courseId]);
  }

  editCourse(course: Course): void {
    this.router.navigate(['/courses', course.id, 'edit']);
  }

  createCourse(): void {
    this.router.navigate(['/create']);
  }

  deleteCourse(course: Course, event: Event): void {
    event.stopPropagation();
    if (!confirm(`Supprimer "${course.title}" ?`)) return;
    this.courseService.deleteCourse(course.id).subscribe({
      next: () => {
        this.createdCourses.set(this.createdCourses().filter(c => c.id !== course.id));
        this.message.success('Cours supprimé');
      },
      error: () => this.message.error('Impossible de supprimer ce cours')
    });
  }

  getProgressPercent(enrollment: EnrollmentWithProgress): number {
    return Math.round(enrollment.progress?.progressPercentage ?? 0);
  }
}
