import { LisioComponent, LisioComponentStyles } from "@lisio/lisio-engine";
import { Chart } from "chart.js/auto";
import type { ChartConfiguration, TooltipItem } from "chart.js";
import ChartDataLabels from "chartjs-plugin-datalabels";
import { customChartStyles } from "./custom-chart.css";

Chart.register(ChartDataLabels);

type PieChartConfig = {
  type: "pie";
  labels: string[];
  values: number[];
  colors: string[];
};

type StackedBarDataset = {
  label: string;
  values: number[];
  color: string;
};

type StackedBarChartConfig = {
  type: "stackedBar";
  labels: string[];
  datasets: StackedBarDataset[];
  tooltipSuffix?: string;
};

type GaugeThreshold = {
  value: number;
  color: string;
};

type GaugeChartConfig = {
  type: "gauge";
  value: number;
  min: number;
  max: number;
  thresholds: GaugeThreshold[];
  targetValue?: number;
  markerValue?: number;
  backgroundColor?: string;
};

type ProgressSegment = {
  value: number;
  color: string;
};

type ProgressChartConfig = {
  type: "progress";
  segments: ProgressSegment[];
  total?: number;
  backgroundColor?: string;
};

type CustomChartConfig =
  | PieChartConfig
  | StackedBarChartConfig
  | GaugeChartConfig
  | ProgressChartConfig;

type CanvasContext = {
  context: CanvasRenderingContext2D;
  width: number;
  height: number;
};

class CarbonConverter {
  private _gridCarbonIntensity = 494;

  private _opDataCentersRatio = 5.5e-11;

  private _opNetworksRatio = 5.9e-11;

  private _opUserDevicesRatio = 8e-11;

  private _emDataCentersRatio = 1.2e-11;

  private _emNetworksRatio = 1.3e-11;

  private _emUserDevicesRatio = 8.1e-11;

  private _gCO2ToCarRatio = 0.0046;

  private _gCO2ToKmPlaneRatio = 0.006;

  private _gCO2ToKmTGVRatio = 0.341;

  private _gCO2ToMailsRatio = 0.406;

  private _gCO2ToPhoneChargeRatio = 1 / 8.2;

  private calculateOpDataCenters(bytes: number) {
    return bytes * this._opDataCentersRatio * this._gridCarbonIntensity;
  }

  private calculateEmDataCenters(bytes: number) {
    return bytes * this._emDataCentersRatio * this._gridCarbonIntensity;
  }

  private calculateOpNetworks(bytes: number) {
    return bytes * this._opNetworksRatio * this._gridCarbonIntensity;
  }

  private calculateEmNetworks(bytes: number) {
    return bytes * this._emNetworksRatio * this._gridCarbonIntensity;
  }

  private calculateOpUserDevices(bytes: number) {
    return bytes * this._opUserDevicesRatio * this._gridCarbonIntensity;
  }

  private calculateEmUserDevices(bytes: number) {
    return bytes * this._emUserDevicesRatio * this._gridCarbonIntensity;
  }

  private calculateTotalOp(bytes: number) {
    return (
      this.calculateOpDataCenters(bytes) +
      this.calculateOpNetworks(bytes) +
      this.calculateOpUserDevices(bytes)
    );
  }

  private calculateTotalEm(bytes: number) {
    return (
      this.calculateEmDataCenters(bytes) +
      this.calculateEmNetworks(bytes) +
      this.calculateEmUserDevices(bytes)
    );
  }

  public convertBytesToCO2(bytes: number) {
    const operational = this.calculateTotalOp(bytes);
    const embodied = this.calculateTotalEm(bytes);
    return {
      operational,
      embodied,
      total: operational + embodied,
    };
  }

  private calculateCO2ToCar(gramCO2: number) {
    return gramCO2 * this._gCO2ToCarRatio;
  }

  private calculateCO2ToPlane(gramCO2: number) {
    return gramCO2 * this._gCO2ToKmPlaneRatio;
  }

  private calculateCO2ToTGV(gramCO2: number) {
    return gramCO2 * this._gCO2ToKmTGVRatio;
  }

  private calculateCO2ToMails(gramCO2: number) {
    return gramCO2 * this._gCO2ToMailsRatio;
  }

  private calculateCO2ToPhoneCharge(gramCO2: number) {
    return gramCO2 * this._gCO2ToPhoneChargeRatio;
  }

  public convertToEquivalence(gramCO2: number) {
    return {
      car: this.calculateCO2ToCar(gramCO2),
      plane: this.calculateCO2ToPlane(gramCO2),
      tgv: this.calculateCO2ToTGV(gramCO2),
      mails: this.calculateCO2ToMails(gramCO2),
      phoneCharges: this.calculateCO2ToPhoneCharge(gramCO2),
    };
  }
}

const carbonConverter = new CarbonConverter();

function clamp(value: number, min: number, max: number): number {
  return Math.min(Math.max(value, min), max);
}

function prepareCanvas(
  canvas: HTMLCanvasElement,
  fallbackHeight: number,
  useElementHeight: boolean = true,
): CanvasContext | undefined {
  const context = canvas.getContext("2d");
  if (context == undefined) {
    return undefined;
  }
  const devicePixelRatio = window.devicePixelRatio || 1;
  const width = Math.max(Math.round(canvas.clientWidth || 240), 240);
  const heightSource = useElementHeight
    ? canvas.clientHeight || fallbackHeight
    : fallbackHeight;
  const height = Math.max(Math.round(heightSource), fallbackHeight);
  canvas.style.height = `${height}px`;
  canvas.width = Math.round(width * devicePixelRatio);
  canvas.height = Math.round(height * devicePixelRatio);
  context.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0);
  context.clearRect(0, 0, width, height);
  return { context, width, height };
}

function drawRoundedRect(
  context: CanvasRenderingContext2D,
  x: number,
  y: number,
  width: number,
  height: number,
  radius: number,
): void {
  const safeRadius = Math.min(radius, height / 2, width / 2);
  context.beginPath();
  context.moveTo(x + safeRadius, y);
  context.lineTo(x + width - safeRadius, y);
  context.quadraticCurveTo(x + width, y, x + width, y + safeRadius);
  context.lineTo(x + width, y + height - safeRadius);
  context.quadraticCurveTo(
    x + width,
    y + height,
    x + width - safeRadius,
    y + height,
  );
  context.lineTo(x + safeRadius, y + height);
  context.quadraticCurveTo(x, y + height, x, y + height - safeRadius);
  context.lineTo(x, y + safeRadius);
  context.quadraticCurveTo(x, y, x + safeRadius, y);
  context.closePath();
}

function drawEmptyState(canvas: HTMLCanvasElement, text: string): void {
  const preparedCanvas = prepareCanvas(canvas, 200);
  if (preparedCanvas == undefined) {
    return;
  }
  const { context, width, height } = preparedCanvas;
  context.fillStyle = "#F4F6F8";
  drawRoundedRect(context, 0, 0, width, height, 20);
  context.fill();
  context.fillStyle = "#5F6772";
  context.textAlign = "center";
  context.textBaseline = "middle";
  context.font = "600 15px Calibri, sans-serif";
  context.fillText(text, width / 2, height / 2);
}

export function formatNumber(value: number): string {
  if (value >= 1_000_000_000) {
    return `${(value / 1_000_000_000).toFixed(3)}kt`;
  }
  if (value >= 1_000_000) {
    return `${(value / 1_000_000).toFixed(3)}t`;
  }
  if (value >= 1_000) {
    return `${(value / 1_000).toFixed(3)}kg`;
  }
  return `${value.toFixed(3)}g`;
}

export function formatBytes(bytes: number): string {
  if (bytes >= 1_073_741_824) {
    return `${(bytes / 1_073_741_824).toFixed(3)} Go`;
  }
  if (bytes >= 1_048_576) {
    return `${(bytes / 1_048_576).toFixed(3)} Mo`;
  }
  if (bytes >= 1024) {
    return `${(bytes / 1024).toFixed(3)} Ko`;
  }
  return `${bytes.toFixed(0)} o`;
}

export function convertBytesToCO2(bytes: number) {
  return carbonConverter.convertBytesToCO2(bytes);
}

export function convertCO2ToEquivalences(gramCO2: number) {
  return carbonConverter.convertToEquivalence(gramCO2);
}

class CustomChart extends LisioComponent {
  private static readonly _maxRenderAttempts = 12;

  private _config: CustomChartConfig;

  private _chart?: Chart;

  public async render(): Promise<string> {
    return `<canvas id="${this._id || ""}" class="lisio-custom-chart ${this.renderClasses()}"></canvas>`;
  }

  public override postRender(): void {
    this.scheduleRender();
  }

  public updateConfig(config: CustomChartConfig): void {
    this._config = config;
    this.scheduleRender();
  }

  private scheduleRender(attempt: number = 0): void {
    requestAnimationFrame(() => {
      if (!(this._htmlElement instanceof HTMLCanvasElement)) {
        return;
      }

      const defaultView = this._htmlElement.ownerDocument?.defaultView;
      const computedWidth =
        defaultView == undefined
          ? 0
          : Number.parseFloat(defaultView.getComputedStyle(this._htmlElement).width);

      if (
        !this._htmlElement.isConnected ||
        defaultView == undefined ||
        this._htmlElement.parentElement == undefined ||
        !(computedWidth > 0)
      ) {
        if (attempt < CustomChart._maxRenderAttempts) {
          this.scheduleRender(attempt + 1);
        }
        return;
      }

      try {
        this._chart?.destroy();
        this._chart = undefined;

        switch (this._config.type) {
          case "pie": {
            this.renderPieChart(this._htmlElement, this._config);
            break;
          }
          case "stackedBar": {
            this.renderStackedBarChart(this._htmlElement, this._config);
            break;
          }
          case "gauge": {
            this.renderGaugeChart(this._htmlElement, this._config);
            break;
          }
          case "progress": {
            this.renderProgressChart(this._htmlElement, this._config);
            break;
          }
        }
      } catch (error) {
        if (
          attempt < CustomChart._maxRenderAttempts &&
          error instanceof TypeError &&
          String(error.message).includes("getComputedStyle")
        ) {
          this.scheduleRender(attempt + 1);
          return;
        }
        console.error(error);
      }
    });
  }

  private renderPieChart(
    canvas: HTMLCanvasElement,
    config: PieChartConfig,
  ): void {
    const total = config.values.reduce((sum, value) => sum + value, 0);
    if (total <= 0) {
      drawEmptyState(canvas, "Pas de donnees disponibles");
      return;
    }

    const chartConfiguration: ChartConfiguration<"pie", number[], string> = {
      type: "pie",
      data: {
        labels: config.labels,
        datasets: [
          {
            data: config.values,
            backgroundColor: config.colors,
            borderWidth: 0,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false,
          },
          tooltip: {
            callbacks: {
              label: (context: TooltipItem<"pie">) => {
                const rawValue = Number(context.raw ?? 0);
                const percentage = total === 0 ? 0 : (rawValue / total) * 100;
                return `${context.label}: ${percentage.toFixed(1)}%`;
              },
            },
          },
          datalabels: {
            color: "#FFFFFF",
            font: {
              weight: "bold",
              size: 12,
            },
            formatter: (value: number) => {
              const percentage = total === 0 ? 0 : (value / total) * 100;
              return `${percentage.toFixed(1)}%`;
            },
          },
        },
      },
    };

    this._chart = new Chart(canvas, chartConfiguration);
  }

  private renderStackedBarChart(
    canvas: HTMLCanvasElement,
    config: StackedBarChartConfig,
  ): void {
    const hasData = config.datasets.some(dataset =>
      dataset.values.some(value => value > 0),
    );
    if (!hasData) {
      drawEmptyState(canvas, "Aucune donnee sur 7 jours");
      return;
    }

    // Only the topmost non-zero segment of each stacked bar should get
    // rounded corners, and only on top - the bar's bottom and every inner
    // boundary between stacked segments must stay flat.
    const isTopSegment = (datasetIndex: number, dataIndex: number): boolean => {
      for (let index = datasetIndex + 1; index < config.datasets.length; index++) {
        if (config.datasets[index].values[dataIndex] > 0) {
          return false;
        }
      }
      return true;
    };

    const chartConfiguration: ChartConfiguration<"bar", number[], string> = {
      type: "bar",
      data: {
        labels: config.labels,
        datasets: config.datasets.map((dataset, datasetIndex) => ({
          label: dataset.label,
          data: dataset.values,
          backgroundColor: dataset.color,
          borderRadius: context =>
            isTopSegment(datasetIndex, context.dataIndex)
              ? { topLeft: 5, topRight: 5, bottomLeft: 0, bottomRight: 0 }
              : 0,
          borderSkipped: false,
          stack: "daily-eco",
          maxBarThickness: 28,
        })),
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          x: {
            stacked: true,
            grid: {
              display: false,
            },
            ticks: {
              color: "#5B6470",
              font: {
                size: 11,
              },
            },
          },
          y: {
            stacked: true,
            beginAtZero: true,
            grid: {
              color: "rgba(115, 127, 142, 0.18)",
            },
            ticks: {
              color: "#5B6470",
              callback: value => {
                const normalizedValue = Number(value);
                return normalizedValue.toFixed(normalizedValue < 1 ? 2 : 1);
              },
            },
          },
        },
        plugins: {
          legend: {
            display: false,
          },
          datalabels: {
            display: false,
          },
          tooltip: {
            callbacks: {
              label: context => {
                const parsedValue =
                  typeof context.parsed === "number"
                    ? context.parsed
                    : Number((context.parsed as { y?: number }).y ?? 0);
                return `${context.dataset.label}: ${parsedValue.toFixed(3)}${config.tooltipSuffix ?? ""}`;
              },
            },
          },
        },
      },
    };

    this._chart = new Chart(canvas, chartConfiguration);
  }

  private renderGaugeChart(
    canvas: HTMLCanvasElement,
    config: GaugeChartConfig,
  ): void {
    const preparedCanvas = prepareCanvas(canvas, 110, false);
    if (preparedCanvas == undefined) {
      return;
    }
    const { context, width, height } = preparedCanvas;
    const trackX = 16;
    const trackWidth = width - 32;
    const trackY = height * 0.48;
    const trackHeight = 12;
    const safeMax = Math.max(config.max, config.min + 1);
    const centerValue =
      config.markerValue != undefined &&
      config.markerValue > config.min &&
      config.markerValue < safeMax
        ? config.markerValue
        : undefined;
    const leftSpan =
      centerValue == undefined ? 0 : centerValue - config.min;
    const rightSpan =
      centerValue == undefined ? 0 : safeMax - centerValue;
    const thresholds = [...config.thresholds].sort((left, right) => left.value - right.value);
    const getTrackX = (value: number): number => {
      const clampedValue = clamp(value, config.min, safeMax);
      const ratio =
        centerValue == undefined || leftSpan <= 0 || rightSpan <= 0
          ? (clampedValue - config.min) / (safeMax - config.min)
          : clampedValue <= centerValue
            ? ((clampedValue - config.min) / leftSpan) * 0.5
            : 0.5 + ((clampedValue - centerValue) / rightSpan) * 0.5;
      return trackX + ratio * trackWidth;
    };
    // Segments are drawn as plain (non-rounded) rectangles clipped to the
    // track's rounded outline, so the bar reads as one continuous shape
    // with only its two exterior (leftmost/rightmost) sides rounded,
    // instead of every segment looking like its own rounded pill.
    const drawSegment = (startValue: number, endValue: number, color: string): void => {
      const segmentStart = clamp(startValue, config.min, safeMax);
      const segmentEnd = clamp(endValue, config.min, safeMax);
      if (segmentEnd <= segmentStart) {
        return;
      }
      const startX = getTrackX(segmentStart);
      const endX = getTrackX(segmentEnd);
      context.fillStyle = color;
      context.fillRect(startX, trackY, Math.max(endX - startX, 1), trackHeight);
    };

    context.save();
    drawRoundedRect(context, trackX, trackY, trackWidth, trackHeight, trackHeight / 2);
    context.clip();

    context.fillStyle = config.backgroundColor ?? "#E9EDF1";
    context.fillRect(trackX, trackY, trackWidth, trackHeight);

    const rightThreshold =
      centerValue == undefined
        ? undefined
        : thresholds.find(threshold => threshold.value > centerValue);
    if (centerValue != undefined && rightThreshold != undefined) {
      drawSegment(centerValue, safeMax, rightThreshold.color);
    }

    let segmentStart = config.min;
    for (const threshold of thresholds) {
      const segmentEnd =
        centerValue == undefined
          ? clamp(threshold.value, config.min, safeMax)
          : Math.min(clamp(threshold.value, config.min, safeMax), centerValue);
      if (segmentEnd <= segmentStart) {
        continue;
      }
      drawSegment(segmentStart, segmentEnd, threshold.color);
      segmentStart = segmentEnd;
      if (centerValue != undefined && segmentStart >= centerValue) {
        break;
      }
    }

    context.restore();

    // Ticks protrude the same distance above and below the bar for every
    // marker, so their vertical spacing reads as aligned rather than each
    // tick sticking out by a different amount.
    const tickOvershoot = 8;
    const drawTick = (value: number | undefined, color: string) => {
      if (value == undefined) {
        return;
      }
      const x = getTrackX(value);
      context.strokeStyle = color;
      context.lineWidth = 2;
      context.beginPath();
      context.moveTo(x, trackY - tickOvershoot);
      context.lineTo(x, trackY + trackHeight + tickOvershoot);
      context.stroke();
    };

    drawTick(config.targetValue, "#37C978");
    drawTick(config.markerValue, "#17212B");

    const currentX = getTrackX(config.value);
    context.fillStyle = "#121922";
    context.beginPath();
    context.arc(currentX, trackY + trackHeight / 2, 6, 0, Math.PI * 2);
    context.fill();
    context.strokeStyle = "#FFFFFF";
    context.lineWidth = 2;
    context.stroke();
  }

  private renderProgressChart(
    canvas: HTMLCanvasElement,
    config: ProgressChartConfig,
  ): void {
    const preparedCanvas = prepareCanvas(canvas, 44, false);
    if (preparedCanvas == undefined) {
      return;
    }
    const { context, width } = preparedCanvas;
    const trackX = 0;
    const trackWidth = width;
    const trackY = 10;
    const trackHeight = 16;
    const total =
      config.total ??
      config.segments.reduce((sum, segment) => sum + segment.value, 0);

    context.fillStyle = config.backgroundColor ?? "#E9EDF1";
    drawRoundedRect(context, trackX, trackY, trackWidth, trackHeight, 999);
    context.fill();

    if (total <= 0) {
      return;
    }

    // Segments are drawn as plain (non-rounded) rectangles clipped to the
    // track's rounded outline, so the bar reads as one continuous shape
    // with only its two exterior (leftmost/rightmost) sides rounded,
    // instead of every segment looking like its own rounded pill.
    context.save();
    drawRoundedRect(context, trackX, trackY, trackWidth, trackHeight, trackHeight / 2);
    context.clip();

    let currentX = trackX;
    config.segments.forEach((segment, index) => {
      if (segment.value <= 0) {
        return;
      }
      const segmentWidth =
        index === config.segments.length - 1
          ? trackWidth - (currentX - trackX)
          : Math.max((segment.value / total) * trackWidth, 4);
      context.fillStyle = segment.color;
      context.fillRect(currentX, trackY, segmentWidth, trackHeight);
      currentX += segmentWidth;
    });

    context.restore();
  }

  constructor(id: string, cssClasses: string[], config: CustomChartConfig) {
    super("custom-chart", id, cssClasses);
    this._config = config;
  }
}

new LisioComponentStyles(CustomChart.name, customChartStyles);

export { CustomChart };
export type { CustomChartConfig, ProgressSegment, StackedBarDataset };
