import Image from "next/image";
import type { PredictionTileController } from "@/features/predictions/hooks/use-prediction-tile-controller";
import {
  predictionMetricsFont,
  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 OPTION_ICONS: Record<string, string> = {
  fille: "/images/pictos/choix-fille.png",
  garcon: "/images/pictos/choix-garcon.png",
  "garçon": "/images/pictos/choix-garcon.png",
};

const GIRL_VALUES = new Set(["fille", "girl"]);

function formatSexDisplayValue(value: string) {
  const normalizedValue = value.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");

  if (normalizedValue === "garcon" || normalizedValue === "boy") {
    return "garçon";
  }

  if (normalizedValue === "fille" || normalizedValue === "girl") {
    return "fille";
  }

  return value;
}

type LegacySexPredictionTileProps = {
  card: PredictionCard;
  controller: PredictionTileController;
  disabled?: boolean;
  showSubmitButton?: boolean;
  onSelect?: (value: string) => void;
};

export function LegacySexPredictionTile({
  card,
  controller,
  disabled,
  showSubmitButton,
  onSelect,
}: LegacySexPredictionTileProps) {
  const mainField = card.fields[0];
  const seenOptionValues = new Set<string>();
  const visibleOptions = card.options.filter((option) => {
    const normalizedOptionValue = option.value
      .toLowerCase()
      .normalize("NFD")
      .replace(/[\u0300-\u036f]/g, "");

    if (seenOptionValues.has(normalizedOptionValue)) {
      return false;
    }

    seenOptionValues.add(normalizedOptionValue);
    return true;
  });
  const selectedValue =
    controller.draftValues.find((value) => value.fieldId === mainField?.id)?.valueText ?? "";
  const normalizedSelectedValue = selectedValue.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
  const hasSelection = normalizedSelectedValue.length > 0;
  const selectedIsGirl = GIRL_VALUES.has(normalizedSelectedValue);
  const selectedDisplayValue = hasSelection ? formatSexDisplayValue(selectedValue) : "Choisissez";

  if (!mainField) {
    return null;
  }

  return (
    <article className={`${styles.tile} ${styles.legacyMiniTile} ${styles.legacySexTile}`}>
      <div className={styles.legacyMiniHeader}>
        <h3 className={predictionTitleFont.className}>Sexe ?</h3>
        <Image
          src="/images/pictos/bebe-garcon.png"
          alt=""
          width={2162}
          height={1984}
          className={styles.legacySexTopBaby}
        />
      </div>

      <div className={styles.sexChoiceRow}>
        {visibleOptions.map((option) => {
          const optionValue = option.value.toLowerCase();
          const iconSrc = OPTION_ICONS[optionValue];
          const normalizedOptionValue = optionValue.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
          const isSelected = normalizedSelectedValue === normalizedOptionValue;
          const isGirlOption = GIRL_VALUES.has(normalizedOptionValue);

          return (
            <button
              key={option.id}
              type="button"
              className={`${styles.sexChoiceButton} ${isSelected ? styles.sexChoiceButtonActive : ""} ${isSelected ? (isGirlOption ? styles.sexChoiceButtonActiveGirl : styles.sexChoiceButtonActiveBoy) : ""}`}
              disabled={disabled}
              aria-label={option.label}
              onClick={() => {
                controller.setText(mainField.id, option.value);
                onSelect?.(option.value);
              }}
            >
              {iconSrc ? (
                <Image src={iconSrc} alt="" width={72} height={72} className={styles.sexChoiceIcon} />
              ) : null}
            </button>
          );
        })}
      </div>

      <div className={styles.sexAnswerRow} aria-live="polite">
        <span
          className={`${styles.sexAnswerBadge} ${styles.predictionAnswerBadgeSurface} ${predictionMetricsFont.className} ${hasSelection ? styles.predictionAnswerBadgeSurfaceVisible : styles.predictionAnswerBadgeSurfacePlaceholder} ${hasSelection ? (selectedIsGirl ? styles.predictionAnswerBadgeSurfaceGirl : styles.predictionAnswerBadgeSurfaceBoy) : ""}`}
        >
          {selectedDisplayValue}
        </span>
      </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>
  );
}