import { Component, OnInit } from "@angular/core";
import { NgbCalendar, NgbDate, NgbModal } from "@ng-bootstrap/ng-bootstrap";
import {
  ApexAxisChartSeries,
  ApexChart,
  ApexDataLabels,
  ApexPlotOptions,
  ApexYAxis,
  ApexLegend,
  ApexStroke,
  ApexXAxis,
  ApexFill,
  ApexTooltip,
} from "ng-apexcharts";
import { BaseCrudComponent } from "src/app/cores/class-templates/base-crud.component";
import { LaporanService } from "src/app/cores/api-services/laporan/laporan.service";
import { HelpersService } from "src/app/cores/services/helpers.service";
import { LoadingService } from "src/app/cores/services/loading.service";
import {
  latLng,
  tileLayer,
  Map,
  Polyline,
  LatLngExpression,
  FeatureGroup,
} from "leaflet";
import * as L from "leaflet";
import * as dayjs from "dayjs";
import { SubDistricService } from "src/app/cores/api-services/map/sub-district.service";
import { ReportSegmens } from "src/app/cores/api-services/map/report-segmens.service";
import { HttpClient } from "@angular/common/http";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { RekapitulasiService } from "src/app/cores/api-services/rekapitulasi/rekapitulasi.service";
import { JsonDataService } from "src/app/cores/api-services/tes.service";

export type BarOptions = {
  series: ApexAxisChartSeries;
  chart: ApexChart;
  dataLabels: ApexDataLabels;
  plotOptions: ApexPlotOptions;
  yaxis: ApexYAxis;
  xaxis: ApexXAxis;
  fill: ApexFill;
  tooltip: ApexTooltip;
  stroke: ApexStroke;
  legend: ApexLegend;
};

export type SplineOptions = {
  series: ApexAxisChartSeries;
  chart: ApexChart;
  xaxis: ApexXAxis;
  stroke: ApexStroke;
  tooltip: ApexTooltip;
  dataLabels: ApexDataLabels;
};

export type RadarOptions = {
  series: ApexAxisChartSeries;
  chart: ApexChart;
  title: ApexTitleSubtitle;
  xaxis: ApexXAxis;
};

export type PieOptions = {
  series: ApexNonAxisChartSeries;
  chart: ApexChart;
  responsive: ApexResponsive[];
  labels: any;
};

export type PolarOptions = {
  series: ApexNonAxisChartSeries;
  chart: ApexChart;
  responsive: ApexResponsive[];
  labels: any;
  stroke: ApexStroke;
  fill: ApexFill;
};

interface Kerusakan {
  status: string;
  jumlah: number;
}

export interface Graf {
  year: number;
  statusCode: number;
  message: string;
  data: Data;
}

export interface Data {
  month?: Data[];
  "Ditindak Lanjuti"?: number;
  "Dalam Proses"?: number;
  Perbaikan?: number;
  Ditolak?: number;
  "Laporan Selesai & Sudah Divalidasi"?: number;
  "Selesai Perbaikan"?: number;
  "Semua Laporan"?: number;
  [key: string]: number | Data[] | undefined;
}

@Component({
  selector: "app-rekapitulasi",
  templateUrl: "./rekapitulasi.component.html",
  styleUrls: ["./rekapitulasi.component.scss"],
})
export class RekapitulasiComponent
  extends BaseCrudComponent<any>
  implements OnInit
{
  // Rekap
  count!: any;

  hoveredDate: NgbDate | null = null;
  fromDate: NgbDate;
  toDate: NgbDate | null = null;
  showDatePicker = false;

  // Map or Segmen
  public reportSegmensData!: any;
  jsonData: any;

  getJsonData(): void {
    this.tes.getJsonData().subscribe((data) => {
      this.jsonData = data;
      console.log(this.jsonData);
      const series: { name: string; data: number[] }[] = [];
      const cat: string[] = [];

      for (const key in this.jsonData.data) {
        const getMonths =
          Object.prototype.hasOwnProperty.call(this.jsonData.data, key) &&
          typeof this.jsonData.data[key] === "object";

        const isNotSemuaLaporan = key !== "Semua Laporan";

        const getStatus = !getMonths && isNotSemuaLaporan;
        if (getMonths) {
          cat.push(key);
        }
        if (getStatus) {
          const statusData: number[] = [];
          const monthData = this.jsonData.data[key] === "Object";

          console.log("month Date", monthData);
        }
      }
      console.log("Isi Categories", cat);
      console.log("Isi Series Data", series);
    });
  }

  public pieOptions!: PieOptions;
  public splineOptions!: SplineOptions;
  public radarOptions!: RadarOptions;

  constructor(
    private tes: JsonDataService,
    private formBuilder: FormBuilder,
    private reportSegmens: ReportSegmens,
    private subDistrict: SubDistricService,
    private report: LaporanService,
    private calendar: NgbCalendar,
    private rekapitulasi: RekapitulasiService,
    public override modal: NgbModal,
    public override helpers: HelpersService,
    public override api: LaporanService,
    public override loading: LoadingService
  ) {
    super(helpers, loading, api, modal);
    this.getJsonData();
    this.initYears();
    const currentYear = new Date().getFullYear();
    for (let i = currentYear - 5; i < currentYear + 1; i++) {
      this.years.push(i);
    }
    this.loadData();
    this.initializeCharts();
    this.fromDate = calendar.getToday();
    this.toDate = calendar.getNext(calendar.getToday(), "d", 1);
    this.api.endpoint = `report-list`;
  }

  defaultPie: Graf | undefined;
  pieData!: Data;
  splineData!: Data;
  radarData!: Data;

  loadData() {
    this.tes
      .getJsonData()
      .pipe()
      .subscribe({
        next: (response: Graf) => {
          this.pieData = response.data;
          this.splineData = response.data;
          this.radarData = response.data;
          this.defaultPie = response;
          this.quartet(0, 2023);
        },
      });
    this.initializeCharts();
  }

  format(date: any): string {
    const year = this.formYears.value.years;
    let formattedDate = "";

    if (date instanceof Date && !isNaN(date.getTime())) {
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");

      formattedDate = `${year}-${month}-${day}`;
    } else {
      console.log("Nilai date tidak valid.");
    }

    return formattedDate;
  }

  quartet(quartal: number, year: number) {
    let start_date, end_date;

    switch (quartal) {
      case 1:
        start_date = new Date(year, 0, 1);
        end_date = new Date(year, 2, 31);
        break;
      case 2:
        start_date = new Date(year, 3, 1);
        end_date = new Date(year, 5, 30);
        break;
      case 3:
        start_date = new Date(year, 6, 1);
        end_date = new Date(year, 8, 30);
        break;
      case 4:
        start_date = new Date(year, 9, 1);
        end_date = new Date(year, 11, 31);
        break;
    }
    const formattedStartDate = this.format(start_date);
    const formattedEndDate = this.format(end_date);

    console.log(formattedStartDate, formattedEndDate);

    this.rekapitulasi.endpoint = `report-list/range-count?start_date=${formattedStartDate}&end_date=${formattedEndDate}`;
    this.rekapitulasi.getAll().subscribe({
      next: ({ data }) => {
        this.count = data;
      },
    });

    if (quartal === 0) {
      const allData = this.defaultPie?.data.month || [];
      this.calculateTotalStatus(allData || []);
      this.calculateTotalSpline(allData || []);
    } else {
      this.initializeCharts();

      const monthsPerQuarter = 3;
      const startMonthIndex = (quartal - 1) * monthsPerQuarter;
      const endMonthIndex = startMonthIndex + monthsPerQuarter;

      const quarterData = this.pieData.month?.slice(
        startMonthIndex,
        endMonthIndex
      );

      const splineData = this.splineData.month?.slice(
        startMonthIndex,
        endMonthIndex
      );

      const radarData = this.radarData.month?.slice(
        startMonthIndex,
        endMonthIndex
      );

      switch (quartal) {
        case 1:
          this.splineOptions.xaxis.categories = ["Jan", "Feb", "Mar"];
          this.radarOptions.xaxis.categories = ["Jan", "Feb", "Mar"];

          break;
        case 2:
          this.splineOptions.xaxis.categories = ["Apr", "May", "Jun"];
          this.radarOptions.xaxis.categories = ["Apr", "May", "Jun"];
          break;
        case 3:
          this.splineOptions.xaxis.categories = ["Jul", "Aug", "Sep"];
          this.radarOptions.xaxis.categories = ["Jul", "Aug", "Sep"];
          break;
        case 4:
          this.splineOptions.xaxis.categories = ["Oct", "Nov", "Dec"];
          this.radarOptions.xaxis.categories = ["Oct", "Nov", "Dec"];
          break;
      }

      this.selectedFilter = `Kuartal ${quartal}`;

      this.calculateTotalSpline(radarData || []);
      this.calculateTotalStatus(quarterData || []);
    }
  }

  calculateTotalSpline(data: any[]) {
    const statusTotals: {
      [key: string]: any | number[];
    } = {};

    console.log("tes", statusTotals);

    data.forEach((monthData) => {
      Object.keys(monthData).forEach((status) => {
        if (status !== "month") {
          if (!statusTotals[status]) {
            statusTotals[status] = [];
          }
          statusTotals[status].push(monthData[status] || 0);
        }
      });
    });

    console.log(this.splineOptions);

    for (const [key, value] of Object.entries(statusTotals)) {
      this.splineOptions.series.push({ name: `${key}`, data: value });
    }
    for (const [key, value] of Object.entries(statusTotals)) {
      this.radarOptions.series.push({ name: `${key}`, data: value });
    }

    return statusTotals;
  }

  calculateTotalStatus(data: any[]) {
    const statusTotals: { [key: string]: number } = {};

    data.forEach((monthData) => {
      Object.keys(monthData).forEach((status) => {
        if (status !== "month") {
          if (!statusTotals[status]) {
            statusTotals[status] = 0;
          }
        }
        statusTotals[status] += monthData[status] || 0;
      });
    });

    for (const [key, value] of Object.entries(statusTotals)) {
      this.pieOptions.labels.push(key);
      this.pieOptions.series.push(value);
    }
    return statusTotals;
  }

  formYears: FormGroup = {} as FormGroup;
  form: FormGroup = {} as FormGroup;
  selectedFilter: string = "Filter";

  years: number[] = [];

  start_date!: string;
  end_date!: string;

  initYears(): void {
    this.formYears = this.formBuilder.group({
      years: [2023, [Validators.required]],
    });
  }

  getYears() {
    this.formYears.valueChanges;
  }

  getMonthRange(): { startDate: string; endDate: string } {
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();

    const startDate = new Date(year, month, 1);

    const endDate = new Date(year, month + 1, 0);
    startDate.setDate(startDate.getDate() + 1);
    endDate.setDate(endDate.getDate() + 1);

    this.start_date = startDate.toISOString().slice(0, 10);
    this.end_date = endDate.toISOString().slice(0, 10);

    this.selectedFilter = `Bulan Sekarang`;
    // this.initForm();

    return { startDate: "", endDate: "" };
  }

  getYearRange(): { startDate: string; endDate: string } {
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear();

    const startDate = new Date(currentYear, 0, 1);
    const endDate = new Date(currentYear, 11, 31);
    startDate.setDate(startDate.getDate() + 1);
    endDate.setDate(endDate.getDate() + 1);

    this.start_date = startDate.toISOString().slice(0, 10);
    this.end_date = endDate.toISOString().slice(0, 10);

    this.selectedFilter = `Tahun Sekarang`;
    // this.initForm();
    console.log(startDate, endDate);

    return { startDate: "", endDate: "" };
  }

  level!: any;
  type: any;

  submitDate(): void {
    // Count Status-Laporan
    this.rekapitulasi.endpoint = `report-list/range-count?start_date=${this.form.value.start_date}&end_date=${this.form.value.end_date}`;
    this.rekapitulasi.getAll().subscribe({
      next: ({ data }) => {
        this.count = data;

        const defaultData = {
          "Ditindak Lanjuti": 0,
          "Dalam Proses": 0,
          Perbaikan: 0,
          "Laporan Selesai & Sudah Divalidasi": 0,
          "Selesai Perbaikan": 0,
          Ditolak: 0,
        };

        this.count = { ...defaultData, ...this.count };
      },
    });

    // Count Tingkat-Kerusakan
    this.rekapitulasi.endpoint = `report-segmens/range-level-count?start_date=${this.form.value.start_date}&end_date=${this.form.value.end_date}`;
    this.rekapitulasi.getAll().subscribe({
      next: ({ data }) => {
        this.level = data;
        this.pieOptions.series = Object.values(this.level);
        this.pieOptions.labels = Object.keys(this.level).map(
          (key) => `${key}: ${this.level[key]}`
        );

        const filteredData: Record<string, any> = Object.entries(this.level)
          .filter(([key]) => key !== "Total Semua Tingkat Kerusakan")
          .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {});

        this.pieOptions.series = Object.values(filteredData);
        this.pieOptions.labels = Object.keys(filteredData).map(
          (key) => `${key}: ${filteredData[key]}`
        );
      },
    });

    // Count Tipe-Kerusakan
    this.rekapitulasi.endpoint = `report-segmens/range-type-count?start_date=${this.form.value.start_date}&end_date=${this.form.value.end_date}`;
    this.rekapitulasi.getAll().subscribe({
      next: ({ data }) => {
        this.type = data;
      },
    });

    // Show Laporan
    this.api.endpoint = `report-list/range?start_date=${this.start_date}&end_date=${this.end_date}`;
    this.api.getAll().subscribe({
      next: ({ data }) => {
        this.updateReportSegmens(data);
      },
    });
  }

  toggleDatePicker() {
    this.showDatePicker = !this.showDatePicker;
  }

  formatDate(date: NgbDate): string {
    const year = date.year;
    const month = date.month < 10 ? "0" + date.month : date.month;
    const day = date.day < 10 ? "0" + date.day : date.day;

    return `${year}-${month}-${day}`;
  }

  formatDateAndValues(): { startDate: string; endDate: string | null } {
    const startDate = this.formatDate(this.fromDate);
    let endDate = this.toDate ? this.formatDate(this.toDate) : null;

    if (endDate === null) {
      endDate = startDate;
    }

    return { startDate, endDate };
  }

  savedDates!: { startDate: string; endDate: string | null };

  saveDates() {
    this.savedDates = this.formatDateAndValues();
  }

  showFormatDate() {
    const { startDate, endDate } = this.formatDateAndValues();
    return endDate ? `${startDate} - ${endDate}` : startDate;
  }

  // onDateSelection(date: NgbDate) {
  //   if (!this.fromDate && !this.toDate) {
  //     this.fromDate = date;
  //   } else if (this.fromDate && !this.toDate && date.after(this.fromDate)) {
  //     this.toDate = date;
  //   } else {
  //     this.toDate = null;
  //     this.fromDate = date;
  //   }
  //   this.formatDateAndValues();
  // }

  // isHovered(date: NgbDate) {
  //   return (
  //     this.fromDate &&
  //     !this.toDate &&
  //     this.hoveredDate &&
  //     date.after(this.fromDate) &&
  //     date.before(this.hoveredDate)
  //   );
  // }

  // isInside(date: NgbDate) {
  //   return this.toDate && date.after(this.fromDate) && date.before(this.toDate);
  // }

  // isRange(date: NgbDate) {
  //   return (
  //     date.equals(this.fromDate) ||
  //     (this.toDate && date.equals(this.toDate)) ||
  //     this.isInside(date) ||
  //     this.isHovered(date)
  //   );
  // }

  summaryReport(): void {
    this.api.endpoint = "report-list/count";
    this.api.getAll().subscribe({
      next: ({ data }) => {
        this.count = data;
      },
    });

    this.initializeCharts();
  }

  reportList(): void {
    this.api.endpoint = "report-list";
    this.queryLimit = 5;
    this.searchFields = "no_ticket,user.fullname,segmens.segmen.name";
    this.queries = {
      page: 1,
      sort: "-created_at",
      limit: 5,
      embed: "status_report,user,segmens,segmens.segmen,segmens.photos",
    };
    this.getAll();
  }

  override ngOnInit(): void {
    this.summaryReport();
    this.getMap();
  }

  // Map
  map: Map | undefined;

  showOption: boolean = true;
  isExpand = true;
  isCollapsed: boolean = false;
  selectedOption: string = "DSS";
  selectedData: any[] = [];

  statusDss: Kerusakan[] = [];
  statusTitikLaporan: Kerusakan[] = [];

  // Map Layer
  polylineLayer: FeatureGroup = new FeatureGroup();
  polygonLayer: FeatureGroup = new FeatureGroup();
  pointLayer: FeatureGroup = new FeatureGroup();

  public mapOptions = {
    layers: [
      tileLayer("http://tile.openstreetmap.org/{z}/{x}/{y}.png", {
        maxZoom: 22,
        minZoom: 11,
      }),
    ],
    scrollWheelZoom: false,
    zoom: 14,
    dragging: true,
    doubleClickZoom: false,
    touchZoom: false,
    tap: false,
    center: latLng(-7.8699381, 112.5285772),
  };

  initMap(map: Map) {
    if (!this.map) this.map = map;
    this.map.zoomControl.setPosition("bottomright");
  }

  getMap(): void {
    this.getSubDistrict();
    this.getReportSegmens();
  }

  toggleFullscreen() {
    const mapElement = document.getElementById("map");

    if (mapElement) {
      if (!document.fullscreenElement) {
        if (mapElement.requestFullscreen) {
          mapElement.requestFullscreen();
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        }
      }
    }
  }

  toggleCollapse() {
    if (!this.isCollapsed) {
      this.getStatusDss();
    }
    this.isCollapsed = !this.isCollapsed;
  }

  onOptionChange(selectedValue: any) {
    this.selectedOption = selectedValue;

    if (this.map) {
      this.map.removeLayer(this.pointLayer);
      this.map.removeLayer(this.polygonLayer);
      this.map.removeLayer(this.polylineLayer);
    }

    this.selectedData = [];

    if (selectedValue === "DSS") {
      if (this.map) {
        this.map.closePopup();
      }
    } else if (selectedValue === "Titik Laporan") {
      this.getStatusTitik();
      this.getStatusSegmenByReport();
    }

    if (this.map) {
      if (selectedValue === "DSS") {
        this.polygonLayer.addTo(this.map);
        this.polylineLayer.addTo(this.map);
      } else if (selectedValue === "point") {
        this.pointLayer.addTo(this.map);
      }
    }
  }

  getStatusTitik() {
    const statusMap: { [key: string]: string } = {
      "Dalam Proses": "#586AF5",
      "Tindak Lanjut": "#FFAB00",
      "Selesai Perbaikan": "#663000",
      Perbaikan: "#F35625",
      Selesai: "#24D07A",
    };

    const colors: string[] = Object.values(statusMap);

    this.statusTitikLaporan = Object.keys(statusMap).map((status, index) => ({
      status,
      jumlah: 0,
      color: colors[index],
    }));
  }

  getColorByStatusTitikLaporan(status_id: string): string {
    const colorMap: { [key: string]: string } = {
      "Dalam Proses": "#586AF5",
      "Tindak Lanjut": "#FFAB00",
      "Selesai Perbaikan": "#663000",
      Perbaikan: "#F35625",
      Selesai: "#24D07A",
    };

    return colorMap[status_id] || "transparent";
  }

  getStatusDss() {
    const colorMap: { [key: string]: string } = {
      "Berlubang Parah": "#215A99",
      "Berlubang Sedang": "#2B79CC",
      "Berlubang Ringan": "#87C0FF",
      "Terkelupas Parah": "#18795F",
      "Terkelupas Sedang": "#1CA762",
      "Terkelupas Ringan": "#4FDA95",
      "Retak Parah": "#992A44",
      "Retak Sedang": "#FF4671",
      "Retak Ringan": "#FF90AA",
      "Bergelombang Parah": "#322564",
      "Bergelombang Sedang": "#644BC8",
      "Bergelombang Ringan": "#977EFB",
    };
    const colors: string[] = Object.values(colorMap);

    this.statusDss = Object.keys(colorMap).map((status, index) => ({
      status,
      jumlah: 0,
      color: colors[index],
    }));
  }

  getColorByStatusDss(status: string, userLevel?: string): string {
    const userStatus = `${status} ${userLevel}`;
    const colorMap: { [key: string]: string } = {
      "Berlubang Parah": "#215A99",
      "Berlubang Sedang": "#2B79CC",
      "Berlubang Ringan": "#87C0FF",
      "Terkelupas Parah": "#18795F",
      "Terkelupas Sedang": "#1CA762",
      "Terkelupas Ringan": "#4FDA95",
      "Retak Parah": "#992A44",
      "Retak Sedang": "#FF4671",
      "Retak Ringan": "#FF90AA",
      "Bergelombang Parah": "#322564",
      "Bergelombang Sedang": "#644BC8",
      "Bergelombang Ringan": "#977EFB",
      NULL: "#000000",
    };
    return colorMap[userStatus] || colorMap[status];
  }

  getIconByStatus(status: string): string {
    switch (status) {
      case "PROG":
        return "assets/images/icon/marker-dalam_proses.png";
      case "FOLUP":
        return "assets/images/icon/marker-tindak_lanjut.png";
      case "DONE":
        return "assets/images/icon/marker-selesai.png";
      case "RPR":
        return "assets/images/icon/marker-perbaikan.png";
      case "FIXED":
        return "assets/images/icon/marker-selesai-perbaikan.png";
      default:
        return "assets/images/icon/marker-default.svg";
    }
  }

  getSubDistrict(): void {
    this.subDistrict.getAll().subscribe(
      (response) => {
        const data = response.data;

        if (data && data.length > 0) {
          this.polygonLayer.clearLayers();

          for (const item of data) {
            const geojson = JSON.parse(item.geojson);

            const polygon = L.geoJSON(geojson, {
              style: {
                fillColor: "green",
                weight: 2,
                color: "white",
              },
            });

            polygon.on("click", (e) => {
              const layer = e.target;
              const name = item.name;

              const popup = L.popup().setContent(name);

              layer.bindPopup(popup).openPopup();
            });

            polygon.addTo(this.polygonLayer);
          }
          if (this.map) {
            this.polygonLayer.addTo(this.map);
          }
        }
      },
      (error) => {}
    );
  }

  getReportSegmens(): void {
    this.loading.isLoading();
    this.reportSegmens
      .getAll({
        embed: "segmen,analytic_data",
      })
      .subscribe(
        ({ data }) => {
          this.updateReportSegmens(data);
        },
        (error) => {
          /* Tangani kesalahan jika ada */
        }
      );
  }

  updateReportSegmens(data: any[]): void {
    this.reportSegmensData = data;

    if (data && data.length > 0) {
      this.polylineLayer.clearLayers();

      for (const feature of data) {
        const geojson = JSON.parse(feature.segmen.geojson);

        const coordinates = geojson.coordinates;
        const featureCoordinates: LatLngExpression[] = coordinates.map(
          (coord: [number, number]) => ({
            lat: coord[1],
            lng: coord[0],
          })
        );

        const status_level = feature.user_level;
        const status_type = feature.user_type;

        const polyline = new Polyline(featureCoordinates, {
          color: this.getColorByStatusDss(status_type, status_level),
          weight: 5,
        });

        this.polylineLayer.addLayer(polyline);
      }

      if (this.map) {
        this.polylineLayer.addTo(this.map);
      }
    }
  }

  getStatusSegmenByReport(): void {
    this.report.endpoint = "report-list";
    this.report
      .getAll({
        embed:
          "segmens.segmen,segmens.analytic_data,segmens.photos,status_report,user",
      })
      .subscribe((response) => {
        const data = response.data;

        if (data && data[0]?.segmens && data[0]?.segmens.length > 0) {
          this.pointLayer.clearLayers();

          for (const segmenData of data) {
            const segmens = segmenData.segmens;
            for (const segmen of segmens) {
              const geojson = JSON.parse(segmen?.segmen?.geojson);
              const coordinates = geojson.coordinates;

              const latLngCoordinates: LatLngExpression[] = coordinates.map(
                (coord: [number, number]) => ({
                  lat: coord[1],
                  lng: coord[0],
                })
              );

              const hasil = segmen.user_type + " " + segmen.user_level;

              const status_id = segmenData.status_id;

              if (status_id !== "RJT") {
                const customIcon = L.icon({
                  iconUrl: this.getIconByStatus(status_id),
                  iconSize: [32, 32],
                  iconAnchor: [16, 32],
                });

                const marker = L.marker(latLngCoordinates[0], {
                  icon: customIcon,
                }).addTo(this.pointLayer);

                this.pointLayer.setStyle({ className: "mask" });

                marker.addTo(this.pointLayer);
                marker.on("click", (e) => {
                  for (const photo of segmen.photos) {
                    if (this.map) {
                      L.popup({
                        className: "custom-popup",
                      })
                        .setLatLng(e.latlng)
                        .setContent(
                          `
                <div>
                  <div>
                    <div class="d-flex justify-content-between align-items-center text-wrap" style:"display: flex">
                      <p class="text-uppercase fs-6 fw-bold mb-2"
                        style="font-size: 14px; color: ${
                          segmenData.status_report.id === "PROG"
                            ? "#586AF5"
                            : segmenData.status_report.id === "RPR"
                            ? "#F35625"
                            : segmenData.status_report.id === "FIXED"
                            ? "#663000"
                            : segmenData.status_report.id === "FOLUP"
                            ? "#FFAB00"
                            : segmenData.status_report.id === "DONE"
                            ? "#24D07A"
                            : "black"
                        };">
                        ${segmenData.status_report.name}
                      </p>
                      <p class="fs-6 mb-2" style="text-align: right;">
                        No.Tiket ${segmenData.no_ticket}
                      </p>
                    </div>

                    <div class="d-flex mb-2 align-items-center">
                      <img 
                        class="location-image" 
                        src="${photo.abs_path}"
                        style="width: 94px; height: 94px; border-radius: 8px;">
                      <div class="ms-3">
                        <div class="d-flex mb-1">
                          <i class="bi bi-person me-2" style="color: #586af5"></i>
                          Nama ${segmenData.user.fullname}
                        </div>
                        <div class="d-flex mb-1">
                          <i class="bi bi-geo-alt me-2" style="color: #586af5"></i>
                          ${segmen.segmen.name}
                        </div>
                        <div class="d-flex mb-1">
                          <i class="bi bi-calendar2 me-2" style="color: #586af5"></i>
                          ${dayjs(segmenData.created_at).format("DD-MM-YYYY")}
                        </div>
                      </div>
                    </div>

                    <div class="d-flex mb-2">
                      <Label class="d-flex align-self-center me-3">Keterangan :</Label>
                      <small class="btn btn-custom" 
                        style="color: white; background-color: ${
                          hasil === "Berlubang Parah"
                            ? "#215A99"
                            : hasil === "Berlubang Sedang"
                            ? "#2B79CC"
                            : hasil === "Berlubang Ringan"
                            ? "#87C0FF"
                            : hasil === "Terkelupas Parah"
                            ? "#18795F"
                            : hasil === "Terkelupas Sedang"
                            ? "#1CA762"
                            : hasil === "Terkelupas Ringan"
                            ? "#4FDA95"
                            : hasil === "Retak Parah"
                            ? "#992A44"
                            : hasil === "Retak Sedang"
                            ? "#FF4671"
                            : hasil === "Retak Ringan"
                            ? "#FF90AA"
                            : hasil === "Bergelombang Parah"
                            ? "#322564"
                            : hasil === "Bergelombang Sedang"
                            ? "#644BC8"
                            : hasil === "Bergelombang Ringan"
                            ? "#977EFB"
                            : "black"
                        };"
                      >
                        ${segmen.user_type}
                        ${segmen.user_level}
                      </small>
                    </div>

                    <p 
                      class="description text-justify mb-0"
                      style="font-size: 14px; letter-spacing: 0.15px; text-align: justify">
                      ${segmenData.note}
                    </p>
                  </div>
                </div>
                `
                        )
                        .openOn(this.map);
                    }
                  }
                });
              }
              this.getColorByStatusTitikLaporan(segmenData.status_report.name);
            }
          }
          this.getStatusTitik();
          if (this.map) {
            this.pointLayer.addTo(this.map);
          }
        }
      });
  }

  initializeCharts() {
    this.pieOptions = {
      series: [],
      chart: {
        width: 380,
        type: "pie",
      },
      labels: [],
      responsive: [
        {
          breakpoint: 480,
          options: {
            chart: {
              width: 200,
            },
            legend: {
              position: "bottom",
            },
          },
        },
      ],
    };
    this.splineOptions = {
      series: [],
      chart: {
        height: 350,
        type: "area",
      },
      dataLabels: {
        enabled: false,
      },
      stroke: {
        curve: "smooth",
        fill: {
          colors: ["none"],
        },
      },
      xaxis: {
        categories: [
          "Jan",
          "Feb",
          "Mar",
          "Apr",
          "May",
          "Jun",
          "Jul",
          "Aug",
          "Sep",
          "Oct",
          "Nov",
          "Dec",
        ],
      },
      tooltip: {
        x: {
          format: "dd/MM/yy HH:mm",
        },
      },
    };
    this.radarOptions = {
      series: [],
      chart: {
        height: 350,
        type: "radar",
      },
      title: {
        text: "Basic Radar Chart",
      },
      xaxis: {
        categories: [
          "Jan",
          "Feb",
          "Mar",
          "Apr",
          "May",
          "Jun",
          "Jul",
          "Aug",
          "Sep",
          "Oct",
          "Nov",
          "Dec",
        ],
      },
    };
  }
}
