import { Component, DestroyRef, inject, OnInit, OnDestroy } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { /*FormControl,*/ FormGroup, FormBuilder, FormArray, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDividerModule } from '@angular/material/divider';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { interval, Observable, Subscription } from 'rxjs';
import { take } from 'rxjs/operators';

import { MenuItems } from '@components/shared';
import { ListErrorsComponent } from '@components/shared';
import { Errors, Qcm, QcmCategory, QcmQuestion, QcmQuestionState, User } from '@models';
import { QcmService, UserService } from '@services';

@Component({
    selector: 'app-qcm',
    imports: [
        FormsModule,
        ReactiveFormsModule,
        MatButtonModule,
        MatCardModule,
        MatDividerModule,
        MatExpansionModule,
        MatIconModule,
        MatMenuModule,
        MatProgressBarModule,
        MatRadioModule,
        MatSelectModule,
        ListErrorsComponent,
    ],
    templateUrl: './qcm.component.html',
    styleUrl: './qcm.component.scss',
})
export class QcmComponent implements OnInit, OnDestroy {
    private route = inject(ActivatedRoute);
    private fb = inject(FormBuilder);
    private _qcmService = inject(QcmService);
    private _userService = inject(UserService);
    menuItems = inject(MenuItems);

    private _currentUser: Subscription = new Subscription();
    private _data: Subscription = new Subscription();
    private _timer: Subscription = new Subscription();
    private _refresh = 1000;
    public qcm: Qcm = {} as Qcm;
    public currentUser: User = {} as User;
    public canModify = false;
    public title = 'QCM Brevets';
    public subtitle = 'Préparation au questionnaires';
    public errors: Errors = { errors: {} };
    public destroyRef = inject(DestroyRef);
    public expandedIndex = 0;
    public questionsCount = 0;
    public answers: Array<QcmQuestionState> = [];
    public qcmForm!: FormGroup;
    public loading = true;
    public totalAnswer = 0;
    public timeProgress = 0;
    public timeProgressColor = 'primary';
    public timeMax = 60 * 45;

    constructor() {
        this.qcmForm = this.fb.group({
            questions: this.fb.array([]),
        });
    }

    get questions(): FormArray {
        return this.qcmForm.controls['questions'] as FormArray;
    }

    ngOnInit() {
        //this._importQuestions();
        //this._importChoices();
        // Retreive the prefetched QCM
        const data$: Observable<{ qcm: Qcm }> = this.route.data as Observable<{ qcm: Qcm }>;
        this._data = data$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((data: { qcm: Qcm }) => {
            this.questionsCount = 0;
            this.qcm = data.qcm;
            if (this.qcm.name === 'bpa') {
                this.title = 'QCM du BPA';
                this.subtitle = 'Préparation au questionnaire du BPA';
            } else {
                this.title = `QCM du brevet ${this.qcm.name.toUpperCase()}`;
                this.subtitle = `Préparation au questionnaire du brevet ${this.qcm.name.toUpperCase()}`;
            }
            //console.log(this.title, this.qcm);
            this.qcm.categories.forEach((category) => {
                this.questionsCount += category.questions.length;
                category.questions.forEach((question) => {
                    this.addQuestion(question);
                });
            });
        });
        // Load the current user's data
        const currentUser$: Observable<User> = this._userService.currentUser;
        this._currentUser = currentUser$.subscribe((userData: User) => {
            this.currentUser = userData;
            this.canModify = userData.role === 'Admin';
        });
        this.loading = false;
    }

    ngOnDestroy() {
        this._data.unsubscribe();
        this._currentUser.unsubscribe();
    }

    private _starTimer(): void {
        this._timer = interval(1000)
            .pipe(take(this.timeMax))
            .subscribe(() => {
                this.timeProgress++;
                if (this.timeProgress > (this.timeMax / 100) * 70 && this.timeProgress <= (this.timeMax / 100) * 90) {
                    this.timeProgressColor = 'warning';
                } else if (
                    this.timeProgress > (this.timeMax / 100) * 90 &&
                    this.timeProgress <= (this.timeMax / 100) * 98
                ) {
                    this.timeProgressColor = 'danger';
                } else if (this.timeProgress > (this.timeMax / 100) * 98) {
                    this.timeProgressColor = 'purple';
                }
                if (this.timeProgress >= this.timeMax) {
                    this.timeProgressColor = 'accent';
                    this._timer.unsubscribe();
                }
            });
    }

    addQuestion(question: QcmQuestion) {
        const item = this.fb.group({
            id: [question.num],
            choice: [''],
        });
        this.answers.push(QcmQuestionState.UNANSWERED);
        this.questions.push(item);
    }

    setExpandedIndex(index: number) {
        this.expandedIndex = index;
    }

    onChange(category: QcmCategory, question: QcmQuestion, value: unknown) {
        //console.log('onChange', category.num, question.num, value);
        if (this.timeProgress === 0) {
            this._starTimer();
        }
        this.qcm.categories[category.num - 1].questions[question.num - 1].choices.forEach((choice) => {
            if (choice.index === value) {
                if (choice.correct) {
                    this.answers[question.num - 1] = QcmQuestionState.VALID;
                    console.log(`Réponse à la question ${question.num} de la catégorie ${category.num} : correcte`);
                } else {
                    this.answers[question.num - 1] = QcmQuestionState.ERROR;
                    console.log(`Réponse à la question ${question.num} de la catégorie ${category.num} : incorrecte`);
                }
            }
        });
        this.totalAnswer++;
        this.questions.controls[question.num - 1].disable();
        //console.log(this.questions.controls[(question.num-1)].disabled);
    }

    onSubmit() {
        console.log('onSubmit');
    }

    private _resetErrors(): void {
        this.errors = { errors: {} };
    }
}
