import { DatePipe, NgIf, DecimalPipe, JsonPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { UntypedFormGroup, UntypedFormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatSort, MatSortModule } from '@angular/material/sort';
import { MatTableDataSource, MatTableModule } from '@angular/material/table';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { Layer, LayerType } from 'src/app/models/layer.model';
import { Record } from 'src/app/models/record.model';
import { NotificationsService } from 'src/app/services/notifications.service';
import { environment } from 'src/environments/environment';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';

@Component({
    selector: 'diunabi-layer-detail',
    templateUrl: './layer-detail.component.html',
    styleUrls: ['./layer-detail.component.scss'],
    standalone: true,
    imports: [FormsModule, ReactiveFormsModule, MatCardModule,
      MatButtonModule, MatGridListModule, MatFormFieldModule, MatInputModule,
      NgIf, MatTableModule, MatSortModule, DecimalPipe, JsonPipe, RouterLink],
    providers: [DatePipe]
})
export class LayerDetailComponent implements OnInit {

  public form!: UntypedFormGroup;
  public document!: Layer;

  valueSum = 0;

  displayedColumns = environment.views.layers.recordColumns.split("|");
  dataSource!: MatTableDataSource<Record>;

  LayerType = LayerType;

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  shortRecords: any = null;

  @ViewChild(MatSort) sort!: MatSort;

  constructor(
    private fb$: UntypedFormBuilder,
    private http$: HttpClient,
    private route$: ActivatedRoute,
    private datePipe: DatePipe,
    private notifications$: NotificationsService
  ) {
    this.form = Layer.getForm(this.fb$);
  }

  async ngOnInit() {
    this.document = await this.load();
    this.dataSource = new MatTableDataSource<Record>(this.document.records);
    this.dataSource.sort = this.sort;
    this.document.fillForm(this.form);
    this.form.disable();
    this.document.created = `${this.datePipe.transform(this.document.createdAt?.toDate(), 'short')}, ${this.document.createdBy?.userName}`;
    this.document.modified = `${this.datePipe.transform(this.document.modifiedAt?.toDate(), 'short')}, ${this.document.modifiedBy?.userName}`;
    this.valueSum =  this.document.records.map(t => t.value1 || 0).reduce((acc, value) => acc + value, 0);
    this.createColumns();

    this.prepareDataForAI();
  }
  private async load(): Promise<Layer> {
      return await Layer.getById(this.route$.snapshot.paramMap.get('id') || "", this.http$);
  }

  createColumns() {
    this.displayedColumns = ['code'];
    for (let i = 1; i < 33; i++) {
      for (const record of this.document.records) {
        const propertyName = `value${i}` as keyof typeof record;
        if (record[propertyName] !== null) {
          this.displayedColumns.push(`value${i}`);
          break;
        }
      }
    }

    for (const record of this.document.records) {
      if (record.desc1 !== null) {
        this.displayedColumns.push(`desc1`);
        break;
      }
    }
  }

  processLayer() {
    Layer.processLayer(this.document.id!, this.http$).then(() => {
      this.notifications$.add({
        text: "Layer processed",
      });
    });
  }

  async export() {
    if (await Layer.exportToGoogleSheet(this.document.id || "", this.http$)) {
      this.notifications$.add({
        text: "The file was saved on Google Drive",
      });
    } else {
      this.notifications$.add({
        text: "Save failed!",
      });
    }
  }

  async prepareDataForAI() {
    const codes = this.document.records.map(x => x.code);
    const weatherURL = 'https://archive-api.open-meteo.com/v1/archive?latitude=54.36685&longitude=18.692&start_date=2023-12-01&end_date=2023-12-31&daily=temperature_2m_mean,rain_sum,snowfall_sum,wind_speed_10m_max&timezone=Europe%2FBerlin';
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    this.http$.get(weatherURL).subscribe((data: any) => {
      console.log('pogoda', data);

      // loop throught all days in december 2023
      const days = data['daily']['time'].length;
      console.log(days);
      this.shortRecords = [];
      for (let i = 0; i < days; i++) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const res: any = {};
        res.day = i+1;
        res.code = 600;
        res.temperature = data['daily']['temperature_2m_mean'][i];
        res.rain = data['daily']['rain_sum'][i];
        res.snow = data['daily']['snowfall_sum'][i];
        res.wind = data['daily']['wind_speed_10m_max'][i];
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const codeValues: any[] = [];
        codes.forEach(code => {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const res: any = { code: code };
          res.value = this.getRecordValue(this.document.records.find(x => x.code === code)!, i+1);
          codeValues.push(res);
        });
        res.sell = codeValues.filter(x => x.value > 0);
        //= codes.map(code => this.getRecordValue(this.document.records.find(x => x.code === code)!, i+1));
        this.shortRecords.push(res);
      }
    });
  }

  getRecordValue(record: Record, index: number) {
    const propertyName = `value${index}` as keyof typeof record;
    return record[propertyName];
  }
}
