import { DatePipe } from '@angular/common';
import { Component, Input, inject } from '@angular/core';
import { MatIconButton } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog';
import { MatIcon } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { TranslateModule } from '@ngx-translate/core';
import { EpgItemDescriptionComponent } from '@iptvnator/ui/epg';
import { EpgItem } from '@iptvnator/shared/interfaces';

@Component({
    selector: 'app-epg-view',
    templateUrl: './epg-view.component.html',
    imports: [DatePipe, MatIconButton, MatIcon, MatListModule, TranslateModule],
    styleUrls: ['./epg-view.component.scss'],
})
export class EpgViewComponent {
    @Input() epgItems: EpgItem[] = [];

    dialog = inject(MatDialog);

    isCurrentProgram(item: EpgItem): boolean {
        const end = this.getProgramEnd(item);
        const now = new Date().getTime();
        const start = new Date(item.start).getTime();
        const stop = new Date(end).getTime();
        return now >= start && now <= stop;
    }

    getProgress(item: EpgItem): number {
        const now = new Date().getTime();
        const start = new Date(item.start).getTime();
        const end = new Date(this.getProgramEnd(item)).getTime();

        const total = end - start;
        const current = now - start;

        return Math.min(Math.max((current / total) * 100, 0), 100);
    }

    getProgramEnd(item: EpgItem): string {
        return item.stop ?? item.end;
    }

    showDetails(item: EpgItem) {
        this.dialog.open(EpgItemDescriptionComponent, {
            width: '600px',
            data: {
                title: item.title ?? 'No title',
                desc: item.description ?? 'No description',
            },
        });
    }
}
