import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import {FetchDataFunction} from "@app/_components/simple-paging/paging-get-data-function";

@Component({
    selector: 'app-simple-paging',
    standalone: true,
    imports: [CommonModule, FormsModule],
    templateUrl: './simple-paging.component.html',
    styleUrls: ['./simple-paging.component.scss']
})
export class SimplePagingComponent implements OnInit {
    @Input({ required: true }) fetchDataFunction!: FetchDataFunction;
    @Input() showSearch: boolean = true;
    @Output() dataChange = new EventEmitter<any[]>();

    protected searchTerm = '';
    protected totalItems = 0;
    protected currentPage = 1;
    protected lastPage = 1;

    ngOnInit() {
        this.loadData();
    }

    protected loadData() {
        this.fetchDataFunction(this.currentPage, this.searchTerm || undefined).subscribe({
            next: (data) => {
                this.totalItems = data.totalItems ?? 0;
                if (data.view?.last) {
                    const pageMatch = data.view?.last.match(/page=(\d+)/);
                    if (pageMatch) {
                        this.lastPage = parseInt(pageMatch[1]);
                    }
                }
                this.dataChange.emit(data.member);
            },
            error: (error) => {
                console.error('Error loading data:', error);
            }
        });
    }

    protected onPageChange(step: number) {
        this.currentPage += step;
        this.loadData();
    }

    protected onSearch(term: string) {
        this.searchTerm = term;
        this.currentPage = 1;
        this.loadData();
    }

    protected hasNextPage(): boolean {
        return this.currentPage < this.lastPage;
    }

    protected goToFirstPage() {
        if (this.currentPage !== 1) {
            this.currentPage = 1;
            this.loadData();
        }
    }

    protected goToLastPage() {
        if (this.currentPage !== this.lastPage) {
            this.currentPage = this.lastPage;
            this.loadData();
        }
    }


    protected clearSearch() {
        if (this.searchTerm) {
            this.searchTerm = '';
            this.currentPage = 1;
            this.loadData();
        }
    }
}
