import { ChangeDetectionStrategy, Component } from '@angular/core';
import { DefaultColorTypes, DOSSIER_TEMPLATE_ID, User } from '@red/domain';
import { AdminDialogService } from '../../services/admin-dialog.service';
import { CircleButtonTypes, IListable, ListingComponent, listingProvidersFactory, TableColumnConfig } from '@iqser/common-ui';
import { defaultColorsTranslations } from '@translations/default-colors-translations';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { combineLatest } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import { DefaultColorsService } from '@services/entity-services/default-colors.service';
import { Roles } from '@users/roles';
import { getCurrentUser } from '@iqser/common-ui/lib/users';
import { getParam } from '@iqser/common-ui/lib/utils';

interface ListItem extends IListable {
    readonly key: string;
    readonly value: string;
}

@Component({
    templateUrl: './default-colors-screen.component.html',
    styleUrls: ['./default-colors-screen.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    providers: listingProvidersFactory(DefaultColorsScreenComponent),
})
export class DefaultColorsScreenComponent extends ListingComponent<ListItem> {
    readonly #dossierTemplateId = getParam(DOSSIER_TEMPLATE_ID);
    readonly circleButtonTypes = CircleButtonTypes;
    readonly currentUser = getCurrentUser<User>();
    readonly roles = Roles;
    readonly translations = defaultColorsTranslations;
    readonly tableHeaderLabel = _('default-colors-screen.table-header.title');
    readonly tableColumnConfigs: TableColumnConfig<ListItem>[] = [
        { label: _('default-colors-screen.table-col-names.key'), sortByKey: 'searchKey', width: '2fr' },
        { label: _('default-colors-screen.table-col-names.color'), class: 'flex-center' },
    ];
    readonly context$;

    constructor(private readonly _dialogService: AdminDialogService, private readonly _defaultColorsService: DefaultColorsService) {
        super();

        this.context$ = combineLatest([this._defaultColorsService.all$]).pipe(
            map(([allDefaultColors]) => {
                const color = allDefaultColors.find(c => c.id === this.#dossierTemplateId);
                return DefaultColorTypes.map(key => ({ id: key, key, searchKey: key, value: color[key] }));
            }),
            tap(colors => this.entitiesService.setEntities(colors)),
        );
    }

    openEditColorDialog(color: ListItem) {
        this._dialogService.openDialog('editColor', { colorKey: color.key, dossierTemplateId: this.#dossierTemplateId });
    }
}
