import Image from "next/image";
import type { PredictionTileController } from "@/features/predictions/hooks/use-prediction-tile-controller";
import { predictionTitleFont } from "@/features/predictions/components/tiles/prediction-tile-fonts";
import styles from "@/features/predictions/styles/predictions.module.css";
import type { PredictionCard } from "@/types/predictions";

const MEASURE_CONFIG: Record<
  string,
  { title: string; iconSrc: string; imgWidth: number; imgHeight: number; step?: number }
> = {
  legacy_head: {
    title: "Périmètre Crânien\u00A0?",
    iconSrc: "/depotARanger/perimetre-cranien.png",
    imgWidth: 1348,
    imgHeight: 1542,
    step: 0.5,
  },
  legacy_height: {
    title: "Taille ?",
    iconSrc: "/depotARanger/taille-baby.png",
    imgWidth: 1346,
    imgHeight: 1824,
    step: 0.5,
  },
};

function clampValue(value: number, min?: number, max?: number) {
  if (typeof min === "number" && value < min) {
    return min;
  }

  if (typeof max === "number" && value > max) {
    return max;
  }

  return value;
}

function getStepPrecision(step: number) {
  const decimals = step.toString().split(".")[1];
  return decimals?.length ?? 0;
}

function normalizeMeasureValue(value: number, step: number, min?: number, max?: number) {
  const roundedValue = Math.round(value / step) * step;
  const clampedValue = clampValue(roundedValue, min, max);
  return Number(clampedValue.toFixed(getStepPrecision(step)));
}

type LegacyNumberPredictionTileProps = {
  card: PredictionCard;
  controller: PredictionTileController;
  disabled?: boolean;
  showSubmitButton?: boolean;
};

export function LegacyNumberPredictionTile({
  card,
  controller,
  disabled,
  showSubmitButton,
}: LegacyNumberPredictionTileProps) {
  const mainField = card.fields[0];
  const currentValue =
    controller.draftValues.find((value) => value.fieldId === mainField?.id)?.valueNumber ?? null;
  const measureConfig = card.code ? MEASURE_CONFIG[card.code] : null;
  const step = measureConfig?.step ?? mainField?.stepNumber ?? 0.1;

  if (!mainField || !measureConfig) {
    return null;
  }

  const minValue = mainField.minNumber ?? undefined;
  const maxValue = mainField.maxNumber ?? undefined;
  const canDecrease = !disabled && (currentValue ?? minValue ?? 0) > (minValue ?? Number.NEGATIVE_INFINITY);
  const canIncrease = !disabled && (currentValue ?? minValue ?? 0) < (maxValue ?? Number.POSITIVE_INFINITY);

  const applyStepDelta = (direction: -1 | 1) => {
    const baseValue = currentValue ?? minValue ?? 0;
    const nextValue = normalizeMeasureValue(baseValue + direction * step, step, minValue, maxValue);
    controller.setNumber(mainField.id, nextValue);
  };

  return (
    <article className={`${styles.tile} ${styles.legacyMiniTile} ${styles.legacyMeasureTile}`}>
      <div className={styles.legacyMiniHeader}>
        <h3 className={predictionTitleFont.className}>{measureConfig.title}</h3>
      </div>

      <div className={styles.measureEntryRow}>
        <Image
          src={measureConfig.iconSrc}
          alt=""
          width={measureConfig.imgWidth}
          height={measureConfig.imgHeight}
          className={styles.measureEntryIcon}
        />
        <div className={styles.measureFieldStack}>
          <div className={styles.measureInputWrap}>
            <input
              type="number"
              min={minValue}
              max={maxValue}
              step={step}
              value={currentValue ?? ""}
              disabled={disabled}
              placeholder="..."
              onChange={(event) => {
                const raw = event.target.value;
                if (raw.trim() === "") {
                  controller.setNumber(mainField.id, null);
                  return;
                }

                const nextValue = Number(raw);
                if (Number.isNaN(nextValue)) {
                  return;
                }

                controller.setNumber(mainField.id, nextValue);
              }}
            />
            {card.unit ? <span>{card.unit}</span> : null}
          </div>

          <div className={styles.measureStepControls}>
            <button
              type="button"
              className={styles.measureStepButton}
              onClick={() => applyStepDelta(-1)}
              disabled={!canDecrease}
              aria-label={`Diminuer ${measureConfig.title}`}
            >
              <span aria-hidden="true">-</span>
            </button>
            <button
              type="button"
              className={`${styles.measureStepButton} ${styles.measureStepButtonAccent}`}
              onClick={() => applyStepDelta(1)}
              disabled={!canIncrease}
              aria-label={`Augmenter ${measureConfig.title}`}
            >
              <span aria-hidden="true">+</span>
            </button>
          </div>
        </div>
      </div>

      <div className={styles.legacyMiniPoints}>Gagnez {mainField.points} Points !</div>

      <div className={styles.legacyMiniFooter}>
        {showSubmitButton ? (
          <button
            className={`btn btn-primary ${styles.legacyMiniButton}`}
            onClick={() => void controller.submit()}
            disabled={controller.saving || disabled}
            type="button"
          >
            {controller.saving ? "Validation..." : "Valider mon pronostic"}
          </button>
        ) : null}
        {controller.dirty ? (
          <span className={styles.dirty}>Modifications non enregistrees</span>
        ) : null}
        {controller.successMessage ? <p className={styles.success}>{controller.successMessage}</p> : null}
        {controller.errorMessage ? <p className={styles.error}>{controller.errorMessage}</p> : null}
      </div>
    </article>
  );
}