import { Component, OnInit, ViewChild } from "@angular/core";
import { MatPaginator, MatPaginatorModule } from "@angular/material/paginator";
import { MatTableDataSource, MatTableModule } from "@angular/material/table";
import { MatDialog } from "@angular/material/dialog";
import { TranslateModule, TranslateService } from "@ngx-translate/core";

import { MatIconModule } from "@angular/material/icon";
import { MatProgressSpinnerModule } from "@angular/material/progress-spinner";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatButtonModule } from "@angular/material/button";
import { MatInputModule } from "@angular/material/input";
import { ReactiveFormsModule } from "@angular/forms";

import { AddAction } from "../../models/add-action.enum";
import { DropZoneResp } from "../../models/dropzone";
import { DropzoneService } from "../../services/dropzone.service";
import { ServiceComm } from "../../services/service-comm.service";
import { AuthenticationService } from "../../services/authentication.service";
import { NewDropZoneComponent } from "../new-drop-zone/new-drop-zone.component";

@Component({
    selector: "app-list-of-dzs",
    templateUrl: "./list-of-dzs.component.html",
    styleUrls: ["./list-of-dzs.component.css"],
    imports: [
        TranslateModule,
        MatIconModule,
        MatPaginatorModule,
        MatProgressSpinnerModule,
        MatTableModule,
        MatFormFieldModule,
        ReactiveFormsModule,
        MatInputModule,
        MatButtonModule,
    ],
})
export class ListOfDzsComponent implements OnInit {
    public displayedColumns: Array<string> = [
        "isfavorite",
        "name",
        "address",
        "type",
    ];
    public dataSourceTable: MatTableDataSource<DropZoneResp>;
    public isUserAdmin: boolean;
    public resultsLength = 0;
    @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

    constructor(
        private serviceApi: DropzoneService,
        private serviceComm: ServiceComm,
        private authenticationService: AuthenticationService,
        public dialog: MatDialog,
        private translateService: TranslateService,
    ) {
        this.isUserAdmin =
            this.authenticationService.currentUserValue.roles === "admin";
    }

    ngOnInit() {
        this.serviceComm.refreshRequest.subscribe((action) => {
            if (action === AddAction.Dropzone) {
                this.dialog.closeAll();
                this.getListOfDropZones();
            }
        });
        this.serviceComm.forceTranslateTitle.subscribe((data) => {
            if (data === true) {
                this.updateTitle();
            }
        });

        this.updateTitle();
        this.getListOfDropZones();
    }

    private getListOfDropZones() {
        this.serviceApi.getListOfDropZones().subscribe((data) => {
            setTimeout(() => {
                data.sort(
                    (a, b) =>
                        (b.isFavorite ? 1 : 0) - (a.isFavorite ? 1 : 0) ||
                        a.name.localeCompare(b.name),
                );
                this.dataSourceTable = new MatTableDataSource<DropZoneResp>(
                    data,
                );
                this.dataSourceTable.paginator = this.paginator;
                this.resultsLength = data.length;
            }, 500);
        });
    }

    public setToFavorite(dropzone: DropZoneResp) {
        dropzone.isFavorite = true;
        this.serviceApi.setFavoriteDropZone(dropzone);

        const data = this.dataSourceTable.data;
        data.sort((a, b) => (b.isFavorite ? 1 : 0) - (a.isFavorite ? 1 : 0));
        this.dataSourceTable = new MatTableDataSource<DropZoneResp>(data);
        this.dataSourceTable.paginator = this.paginator;
    }

    public removeToFavorite(dropzone: DropZoneResp) {
        dropzone.isFavorite = false;
        this.serviceApi.removeFavoriteDropZone(dropzone);

        const data = this.dataSourceTable.data;
        data.sort((a, b) => (b.isFavorite ? 1 : 0) - (a.isFavorite ? 1 : 0));
        this.dataSourceTable = new MatTableDataSource<DropZoneResp>(data);
        this.dataSourceTable.paginator = this.paginator;
    }

    openDialogToAdd() {
        this.dialog.open(NewDropZoneComponent, {
            height: "400px",
            width: "600px",
        });
    }

    applyFilter(event: Event) {
        const filterValue = (event.target as HTMLInputElement).value;
        this.dataSourceTable.filter = filterValue.trim().toLowerCase();
    }

    private updateTitle() {
        this.translateService.get("ListDz_Title").subscribe((data) => {
            this.serviceComm.updatedComponentTitle(data);
        });
    }
}
