import { Component, Input, inject } from '@angular/core';
import { ChartComponent } from '../../components/chart/chart.component';
import { CommonModule } from '@angular/common';
import { Milestone } from '../../enums/milestone';
import {
  ChartAxisPosition,
  ChartType,
} from '../../components/chart/chart-type';
import { ChartConfig } from '../../components/chart/chart-config';
import { DataService } from '../../services/data.service';
import { KeyValue } from '../../models/key-value';

@Component({
  selector: 'fbi-cohort-section',
  standalone: true,
  imports: [CommonModule, ChartComponent],
  templateUrl: './cohort-section.component.html',
  styleUrl: './cohort-section.component.scss',
})
export class CohortSectionComponent {
  @Input() county: string | string[] = '644';
  @Input() school: string | string[] = '3067';
  @Input() cohort!: string | string[];

  chart: ChartConfig = {
    type: ChartType.Line,
    axis: [
      {
        label: 'Grade',
        source: Milestone.Grade,
        position: ChartAxisPosition.Bottom,
        stacked: true,
      },
      {
        label: [
          'Beginning Learner',
          'Developing Learner',
          'Proficient Learner',
          'Distinguished Learner',
        ],
        source: [
          Milestone.ELA0,
          Milestone.ELA1,
          Milestone.ELA2,
          Milestone.ELA3,
        ],
        position: ChartAxisPosition.Left,
        fill: true,
        stacked: true,
        stack: 'ELA',
        min: 0,
        max: 100,
      },
    ],
  };
  data: Record<string, any>[] = [];

  private dataService = inject(DataService);

  ngOnInit(): void {
    const county = Array.isArray(this.county) ? this.county : [this.county];
    const school = Array.isArray(this.school) ? this.school : [this.school];
    const cohort = (
      Array.isArray(this.cohort) ? this.cohort : [this.cohort]
    ).map((v: string) => parseInt(v));

    this.dataService.Cohorts$.subscribe(
      (cohorts: KeyValue[]) =>
        (this.chart.title = cohorts
          .map((cohort: KeyValue) => cohort.value)
          .join(', '))
    );

    this.dataService.Data$.subscribe((data: Record<string, any>[]) => {
      this.data = data
        .filter(
          (d: Record<string, any>) =>
            county.includes(d[Milestone.County]) &&
            school.includes(d[Milestone.School]) &&
            cohort.includes(d[Milestone.Cohort])
        )
        .sort(
          (a: Record<string, any>, b: Record<string, any>) =>
            a['grade'] - b['grade']
        );
    });
  }
}
